Skip to content

The agent that grows with you

fix(skills): review fixes — raw fetch falls back on DNS block, restore never writes through links or over user files

Teknium51e712b651cd
diff --git a/tests/hermes_cli/test_skills_hub.py b/tests/hermes_cli/test_skills_hub.py
index abc9cac3c26..76d796e78e9 100644
--- a/tests/hermes_cli/test_skills_hub.py
+++ b/tests/hermes_cli/test_skills_hub.py
@@ -778,3 +778,30 @@ def test_built_in_restore_survives_leftovers_and_records_every_outcome_as_bundle
(real / "llm-wiki" / "SKILL.md").unlink() # missing behind the symlink: refused, and still bundled
assert cli_hub.do_install("llm-wiki", console=console, skip_confirm=True) is False
assert rows == [("bundled", "success"), ("bundled", "failed")]
+
+
+def test_built_in_restore_into_a_leftover_dir_never_writes_through_links_or_over_user_files(tmp_path):
+ """The leftover-tolerant restore copied with dirs_exist_ok: it followed a symlinked file out of
+ skills/ (clobbering the target), overwrote a user-edited file, and called a dir holding another
+ skill's SKILL.md the built-in "already available"."""
+ from tools import skill_usage, skills_sync
+ from tools.skills_sync_bundled_ops import ensure_bundled_skill
+
+ src = dict(skills_sync._discover_bundled_skills(skills_sync._get_bundled_dir()))["arxiv"]
+ dest = skill_usage._skills_dir() / src.parent.name / "arxiv"
+ victim = tmp_path / "victim.txt"
+ victim.write_text("USER SECRET\n")
+ (dest / "scripts").mkdir(parents=True)
+ (dest / "scripts" / "search_arxiv.py").symlink_to(victim)
+ assert ensure_bundled_skill("arxiv")["action"] == "not_restored"
+ assert victim.read_text() == "USER SECRET\n" and not (dest / "SKILL.md").exists()
+
+ (dest / "scripts" / "search_arxiv.py").unlink()
+ (dest / "scripts" / "search_arxiv.py").write_text("# my local edits\n")
+ assert ensure_bundled_skill("arxiv")["action"] == "restored"
+ assert (dest / "scripts" / "search_arxiv.py").read_text() == "# my local edits\n"
+ assert (dest / "SKILL.md").read_bytes() == (src / "SKILL.md").read_bytes()
+
+ (dest / "SKILL.md").write_text("---\nname: my-own-thing\ndescription: x\n---\nmine\n")
+ assert ensure_bundled_skill("arxiv")["action"] == "not_restored"
+ assert "my-own-thing" in (dest / "SKILL.md").read_text()
diff --git a/tests/tools/test_skills_hub_github_fetch.py b/tests/tools/test_skills_hub_github_fetch.py
index 2872fde2008..d798c6bb71c 100644
--- a/tests/tools/test_skills_hub_github_fetch.py
+++ b/tests/tools/test_skills_hub_github_fetch.py
@@ -28,3 +28,25 @@ def test_pinned_file_comes_from_raw_and_spends_no_api_call(monkeypatch, raw_stat
assert GitHubSource(auth)._fetch_file_bytes("o/r", "s/a b.md", ref="c" * 40) == b"body"
assert hosts == (["raw.githubusercontent.com"] if raw_status == 200
else ["raw.githubusercontent.com", "api.github.com"])
+
+
+def test_unreachable_raw_host_falls_back_to_the_api_and_is_tried_once(monkeypatch):
+ """A DNS-poisoned or NXDOMAIN raw.githubusercontent.com (api.github.com fine) raises
+ SSRFConnectionBlocked, a ValueError the raw attempt did not catch: every install failed before
+ the API fallback. A dropped-packet firewall costs a 15 s timeout per file, so stop after one."""
+ import tools.skills_hub as hub
+ from tools.url_safety import SSRFConnectionBlocked
+ hosts = []
+
+ def fake_get(url, **_kw):
+ hosts.append(url.split("/")[2])
+ if "raw.githubusercontent.com" in url:
+ raise SSRFConnectionBlocked("DNS resolution failed for: raw.githubusercontent.com")
+ return httpx.Response(200, content=b"body")
+
+ monkeypatch.setattr(hub, "_skills_hub_http_get", fake_get)
+ auth = MagicMock(spec=GitHubAuth)
+ auth.get_headers.return_value = {}
+ source = GitHubSource(auth)
+ assert [source._fetch_file_bytes("o/r", f"s/{i}.md", ref="c" * 40) for i in range(3)] == [b"body"] * 3
+ assert hosts == ["raw.githubusercontent.com"] + ["api.github.com"] * 3
diff --git a/tools/skills_hub_github.py b/tools/skills_hub_github.py
index 55b81e4bc23..8eec6f3eee1 100644
--- a/tools/skills_hub_github.py
+++ b/tools/skills_hub_github.py
@@ -1,6 +1,5 @@
"""Skills Hub GitHub adapter: API auth, tap providers, and the Contents/Trees source."""
-import contextlib
import json
import logging
import subprocess
@@ -250,6 +249,7 @@ class GitHubSource(SkillSource):
# repo -> skills.sh.json grouping map; None = fetched, no sidecar.
self._skillsh_groupings: dict[str, Optional[dict[str, str]]] = {}
self._rate_limited: bool = False
+ self._raw_unusable = False # raw host unreachable here: later files go straight to the API
@property
def is_rate_limited(self) -> bool: # whether the GitHub API rate limit was hit during operations
@@ -567,12 +567,17 @@ class GitHubSource(SkillSource):
raw.githubusercontent.com first: the same bytes at the same commit, outside the REST rate
limit. Through the Contents API every file in a skill folder cost one call, so an anonymous
user (60/h) could never install a skill with more than ~58 files. A private repo or a raw
- miss falls back to the API."""
- if ref:
- with contextlib.suppress(httpx.HTTPError):
+ miss falls back to the API. A transport failure (DNS-poisoned or NXDOMAIN raw host surfaces as
+ SSRFConnectionBlocked, a dropping firewall as a 15 s timeout) also falls back, and marks raw
+ unusable for the rest of this source's flow."""
+ if ref and not self._raw_unusable:
+ try:
raw = hub()._skills_hub_http_get(
f"https://raw.githubusercontent.com/{repo}/{ref}/{quote(path, safe='/')}",
timeout=15.0, follow_redirects=False)
+ except (httpx.HTTPError, OSError, ValueError): # ValueError: SSRFConnectionBlocked
+ self._raw_unusable = True
+ else:
if raw.status_code == 200:
return raw.content
resp = self._github_get(
diff --git a/tools/skills_sync_bundled_ops.py b/tools/skills_sync_bundled_ops.py
index 0636dc9ede5..86f888e9082 100644
--- a/tools/skills_sync_bundled_ops.py
+++ b/tools/skills_sync_bundled_ops.py
@@ -1,6 +1,7 @@
"""Bundled-skill maintenance ops: reset, diff, list-modified, opt-out, remove-pristine.
Profile-scoped paths and patchable helpers resolve through ``_ss()`` at call time."""
+import os
import shutil
from pathlib import Path
from typing import List, Optional, Tuple
@@ -79,7 +80,10 @@ def ensure_bundled_skill(name: str) -> dict:
"""Make bundled ``name`` active: ``{ok, action, path, message}``, action ``present`` (any active
copy, user edits included, is left alone), ``restored`` (copied from the bundled source and
re-tracked, so an opt-out, curator prune or manual delete no longer hides it), or
- ``hub_shadowed`` (a hub install owns the name; it is the user's to remove, never overwritten)."""
+ ``hub_shadowed`` (a hub install owns the name; it is the user's to remove, never overwritten).
+ A restore into a leftover dir only adds the missing files (a user file is never overwritten) and
+ the manifest records the bundled hash, so a dest that kept user files reads as user-modified and
+ ``hermes update`` leaves it alone: intended, the user's data wins."""
from tools import skill_usage
ss, manifest, bundled_dir, bundled_by_name = _bundled_state()
src = bundled_by_name[name]
@@ -91,19 +95,27 @@ def ensure_bundled_skill(name: str) -> dict:
f"`hermes skills install {name}`.")}
# The rglob walk does not descend a symlinked category the loader follows, so the canonical
# SKILL.md counts as present too.
+ skill_md = dest / "SKILL.md"
active = next((md.parent for md in ss._iter_active_skill_mds()
if ss._read_skill_name(md, md.parent.name) == name), None) or (
- dest if (dest / "SKILL.md").is_file() else None)
+ dest if skill_md.is_file() and ss._read_skill_name(skill_md, name) == name else None)
if active is not None or name in ss._build_external_skill_index():
return {"ok": True, "action": "present", "path": active, "message": ""}
try: # the hub's containment check: a symlinked category must not carry the copy out of skills/
+ from pm.filesystem import is_junction
from tools.skills_hub_install import _resolve_lock_install_path
rel = dest.relative_to(ss._skills_dir()).as_posix()
_resolve_lock_install_path(rel, dest.name)
- # A dir with no SKILL.md (a delete or earlier copy that died partway) is no skill; copying
- # around its leftovers beats failing with EEXIST on every retry.
+ # A dir with no SKILL.md (a delete or earlier copy that died partway) is no skill; filling in
+ # its missing files beats failing with EEXIST on every retry. A link inside it would carry the
+ # copy out of skills/, and a SKILL.md there is another skill: refuse both.
+ if os.path.lexists(skill_md):
+ raise ValueError("the directory holds a different skill's SKILL.md")
+ if dest.exists() and any(p.is_symlink() or is_junction(p) for p in dest.rglob("*")):
+ raise ValueError("the leftover directory contains a symlink or junction")
dest.parent.mkdir(parents=True, exist_ok=True)
- shutil.copytree(src, dest, ignore=_ignore_runtime_cache, dirs_exist_ok=True)
+ shutil.copytree(src, dest, ignore=_ignore_runtime_cache, dirs_exist_ok=True,
+ copy_function=lambda s, d: d if os.path.lexists(d) else shutil.copy2(s, d))
except (OSError, ValueError) as e:
return {"ok": False, "action": "not_restored", "path": dest,
"message": f"Could not copy the built-in skill '{name}' to {dest}: {e}"}