diff --git a/.github/workflows/skills-index-freshness.yml b/.github/workflows/skills-index-freshness.yml index dcfcc5a0dd..a0007b4b7f 100644 --- a/.github/workflows/skills-index-freshness.yml +++ b/.github/workflows/skills-index-freshness.yml @@ -6,6 +6,10 @@ name: Skills Index Freshness Check # this workflow opens a GitHub issue so we hear about it before users do. # # Triggered every 4 hours so we catch a stuck cron within one tick. +# +# The check-catalog-cors job watches the same host from Hermes Desktop's side: +# it fetches /docs/api/plugins.json with a browser's Origin header and files +# its own issue when a browser would block the fetch. on: schedule: @@ -165,3 +169,74 @@ jobs: --title "$TITLE_PREFIX Skills index is stale or degraded ($STATUS)" \ --body "$BODY" fi + + check-catalog-cors: + # Desktop's hermes://plugin/install?catalog= links fetch /docs/api/plugins.json + # cross-origin. A browser rejects that fetch when any response in the redirect + # chain lacks Access-Control-Allow-Origin (#136483). The probe above uses + # curl -L, which never checks CORS, so it stays green while Desktop is blocked. + if: github.repository == 'NousResearch/hermes-agent' + runs-on: ubuntu-latest + timeout-minutes: 5 + environment: trusted-automation + steps: + - uses: actions/checkout@f548e57e544e1ff5a4c46bf1e1b8685f8e4a348a # v7.0.1 + + - name: Fetch the plugin catalog the way Desktop does + id: probe + run: | + set +e + detail=$(python3 scripts/ci/check_catalog_cors.py) + code=$? + echo "$detail" + echo "detail=$detail" >> "$GITHUB_OUTPUT" + case "$code" in + 0) echo "status=ok" >> "$GITHUB_OUTPUT" ;; + 1) echo "status=blocked" >> "$GITHUB_OUTPUT" ;; + *) echo "status=unreachable" >> "$GITHUB_OUTPUT" ;; + esac + + - name: Get GitHub App token + if: steps.probe.outputs.status != 'ok' + id: app-token + uses: ./.github/actions/get-app-token + with: + client-id: ${{ vars.APP_CLIENT_ID }} + private-key: ${{ secrets.APP_PRIVATE_KEY }} + + - name: Open issue when Desktop cannot read the catalog + if: steps.probe.outputs.status != 'ok' + env: + GH_TOKEN: ${{ steps.app-token.outputs.token }} + STATUS: ${{ steps.probe.outputs.status }} + DETAIL: ${{ steps.probe.outputs.detail }} + run: | + # Own title prefix, so these reports never land on a skills-index issue. + TITLE_PREFIX="[plugin-catalog-cors-watchdog]" + existing=$(gh issue list \ + --repo "${{ github.repository }}" \ + --state open \ + --search "in:title \"$TITLE_PREFIX\"" \ + --json number,title \ + --jq '.[] | select(.title | startswith("'"$TITLE_PREFIX"'")) | .number' \ + | head -1) + BODY="Hermes Desktop cannot read the plugin catalog. + + **Status:** \`$STATUS\` + **Detail:** $DETAIL + + Desktop's \`hermes://plugin/install?catalog=\` links fetch \`/docs/api/plugins.json\` cross-origin. + A browser rejects that fetch when any response in the redirect chain, including the docs host's + redirect to GitHub Pages, lacks \`Access-Control-Allow-Origin\`. Every catalog install link then + shows \"Could not load the Hermes plugin catalog\". Background: #136483. + + This issue was opened by \`.github/workflows/skills-index-freshness.yml\` (job \`check-catalog-cors\`). Close it once the header is back; the next probe will reopen it if it's still broken." + if [ -n "$existing" ]; then + echo "Appending to existing issue #$existing" + gh issue comment "$existing" --repo "${{ github.repository }}" --body "Probe still failing at $(date -u +%FT%TZ): \`$STATUS\` — $DETAIL" + else + echo "Opening new watchdog issue" + gh issue create --repo "${{ github.repository }}" \ + --title "$TITLE_PREFIX Desktop cannot read the plugin catalog ($STATUS)" \ + --body "$BODY" + fi diff --git a/scripts/ci/check_catalog_cors.py b/scripts/ci/check_catalog_cors.py new file mode 100644 index 0000000000..a6bd9e3f8b --- /dev/null +++ b/scripts/ci/check_catalog_cors.py @@ -0,0 +1,96 @@ +#!/usr/bin/env python3 +"""Fetch a docs catalog URL the way Hermes Desktop does, and fail when a browser would block it. + +The Desktop renderer fetches ``/docs/api/plugins.json`` cross-origin (a packaged build sends +``Origin: null``). A browser checks CORS on every response of a redirect chain, so the docs host's +redirect to GitHub Pages needs ``Access-Control-Allow-Origin`` as much as the final response does +(#136483). ``curl -L`` never checks it, which is why the skills-index watchdog stayed green while +every ``hermes://plugin/install?catalog=`` link failed. + +Exit 0: every hop allows the origin and the final body is a non-empty JSON array. +Exit 1: a browser would reject the fetch (missing header, error status, unusable body). +Exit 2: the host could not be reached after retries. +Prints one summary line for the workflow. +""" + +from __future__ import annotations + +import json +import sys +import time +import urllib.error +import urllib.request +from email.message import Message +from urllib.parse import urljoin + +DEFAULT_URL = "https://hermes-agent.nousresearch.com/docs/api/plugins.json" +ORIGIN = "null" +MAX_HOPS = 5 +TIMEOUT_SECONDS = 20 +ATTEMPTS = 3 +RETRY_DELAY_SECONDS = 10.0 +_REDIRECTS = (301, 302, 303, 307, 308) + + +class Rejected(Exception): + """A browser would refuse to hand this response to the renderer.""" + + +class _HopByHop(urllib.request.HTTPRedirectHandler): + def redirect_request(self, *args, **kwargs): + return None # surface each hop so its own headers are checked + + +def _fetch(opener: urllib.request.OpenerDirector, url: str) -> tuple[int, Message, bytes]: + request = urllib.request.Request(url, headers={"Origin": ORIGIN, "Accept": "application/json"}) + try: + with opener.open(request, timeout=TIMEOUT_SECONDS) as response: + return response.status, response.headers, response.read() + except urllib.error.HTTPError as exc: # unfollowed redirects and error statuses land here + if exc.code >= 500: + raise OSError(f"{url} answered {exc.code}") from exc + return exc.code, exc.headers, exc.read() + + +def check(url: str) -> str: + opener = urllib.request.build_opener(_HopByHop) + for hops in range(MAX_HOPS + 1): + status, headers, body = _fetch(opener, url) + allowed = headers.get("Access-Control-Allow-Origin") + if allowed not in ("*", ORIGIN): + raise Rejected(f"{status} from {url} sends Access-Control-Allow-Origin {allowed!r}, " + "so a browser blocks the fetch here") + if status in _REDIRECTS and headers.get("Location"): + url = urljoin(url, headers["Location"]) + continue + if status != 200: + raise Rejected(f"{url} answered {status}") + try: + rows = json.loads(body) + except ValueError as exc: + raise Rejected(f"{url} is not JSON: {exc}") from exc + if not isinstance(rows, list) or not rows: + raise Rejected(f"{url} is not a non-empty JSON array") + return f"{len(rows)} rows after {hops} redirect(s)" + raise Rejected(f"more than {MAX_HOPS} redirects") + + +def main(argv: list[str]) -> int: + url = argv[1] if len(argv) > 1 else DEFAULT_URL + for attempt in range(1, ATTEMPTS + 1): + try: + print(f"ok: {check(url)}") + return 0 + except Rejected as exc: + print(f"blocked: {exc}") + return 1 + except OSError as exc: # URLError, timeouts, resets and 5xx are retried + if attempt == ATTEMPTS: + print(f"unreachable: {url}: {exc}") + return 2 + time.sleep(RETRY_DELAY_SECONDS) + return 2 + + +if __name__ == "__main__": + sys.exit(main(sys.argv)) diff --git a/tests/ci/test_check_catalog_cors.py b/tests/ci/test_check_catalog_cors.py new file mode 100644 index 0000000000..f2f032247f --- /dev/null +++ b/tests/ci/test_check_catalog_cors.py @@ -0,0 +1,62 @@ +"""scripts/ci/check_catalog_cors.py against a loopback docs host that redirects like the real one.""" + +from __future__ import annotations + +import json +import sys +import threading +from collections.abc import Iterator +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from pathlib import Path + +import pytest + +REPO = Path(__file__).resolve().parents[2] +sys.path.insert(0, str(REPO / "scripts" / "ci")) + +import check_catalog_cors as probe + + +class _DocsHost(BaseHTTPRequestHandler): + """``/bare`` and ``/allowed`` 301 to ``/plugins.json``; only ``/allowed`` sends the CORS header.""" + + def do_GET(self) -> None: + if self.path == "/plugins.json": + body = json.dumps([{"name": "fish-audio"}]).encode() + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.send_header("Access-Control-Allow-Origin", "*") + self.end_headers() + self.wfile.write(body) + return + self.send_response(301) + self.send_header("Location", "/plugins.json") + if self.path == "/allowed": + self.send_header("Access-Control-Allow-Origin", "*") + self.end_headers() + + def log_message(self, format: str, *args) -> None: + pass + + +@pytest.fixture +def docs_host() -> Iterator[str]: + server = ThreadingHTTPServer(("127.0.0.1", 0), _DocsHost) + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + try: + yield f"http://127.0.0.1:{server.server_address[1]}" + finally: + server.shutdown() + server.server_close() + + +def test_redirect_without_cors_header_fails_the_probe(docs_host, capsys): + assert probe.main(["probe", f"{docs_host}/bare"]) == 1 + out = capsys.readouterr().out + assert out.startswith("blocked: 301 from ") and "/bare" in out + + +def test_redirect_with_cors_header_reaches_the_catalog(docs_host, capsys): + assert probe.main(["probe", f"{docs_host}/allowed"]) == 0 + assert capsys.readouterr().out.strip() == "ok: 1 rows after 1 redirect(s)"