diff --git a/AGENTS.md b/AGENTS.md index 7c5db2b..eee9c56 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -73,7 +73,8 @@ Served by Python's ThreadingHTTPServer. Pages use `{{CSS}}`/`{{JS}}` template su | `/device-config` or `/device-config.html` | 302 to `/plugins` — the standalone Device Config page is retired; its options live in the **Controller Plugin** section on the Plugins page (the Settings submenu has no separate entry for it) | | `/configuration.html` or `/configuration` | 302 to `/plugins` (old Device Config URL; the section now lives on /plugins) | | `/appearance` or `/appearance.html` | 302 to `/config` — the Light Mode toggle now lives in the Configuration page's Appearance section (the Settings submenu has no Appearance entry) | -| `/plugins` or `/plugins.html` | Plugins, in three sections: **Test Plugins** (device plugins and monkeytester-ai), **Build Plugin** (its Configure panel holds the code host) and **Controller Plugin** (the one controller plugin; its Configure panel holds friendly names for the devices it serves, moved from the retired Device Config page). Every section: title + "?" generic intro box, an **Add row** (name, address, optional pairing token; the controller's Add row is only an address and shows only while none is set), its status line, then a **table** of the added plugins — Name, Status, Address (editable; Save address greyed until it differs), Details, Actions (Save address, Configure where a panel exists, Remove). Configure opens the panel inline under the row. Signed-in users | +| `/plugins` or `/plugins.html` | Plugins, in three sections: **Test Plugins** (device plugins and monkeytester-ai), **Build Plugin** (its Configure panel holds the code host) and **Controller Plugin** (the one controller plugin; its Configure panel holds friendly names for the devices it serves, moved from the retired Device Config page). Every section: title + "?" generic intro box, an **Add row** (name, address, optional pairing token; the controller's Add row is only an address and shows only while none is set), its status line, then a **table** of the added plugins — Name, Status, Address (editable; Save address greyed until it differs), Details, Actions (Save address, Configure where a panel exists, Remove). Configure opens the panel inline under the row. When the row's data has `docs: true`, the Details cell ends with a thin rule (`hr.pt-docs-sep`) and a small **Documentation** link (`a.pt-docs`, `target=_blank`, `rel=noopener noreferrer`, `href=/plugins/docs/`); the Details cell is plain HTML re-rendered via `setHtml`, so the address `` is never touched. Signed-in users | +| `/plugins/docs/` | A plugin's documentation page (all three sections; `` = the row key, `controller` for the Mobile Controller unless a plugin has that name). Page route: unauthenticated → 302 `/login`; any signed-in user. `` must match `^[A-Za-z0-9._-]{1,64}$` and be a registered device plugin, monkeytester-ai, build plugin or the controller, else 404 HTML. The viewer resolves base URL + token from its own config (`plugin_docs_target`; never from the request), reads the plugin's `GET /health` `docs` (valid only per `security_utils.plugin_docs_path`: starts with `/`, not `//`, no `\`, scheme, CR/LF, ≤ 256 chars; else 404 "This plugin has no documentation"), then fetches `` with `X-Plugin-Token` (`X-Controller-Token` for the controller), 10 s, no redirects, `text/html` only, ≤ 2 MiB, and serves it with a sandbox CSP (`PLUGIN_DOCS_CSP`), `nosniff`, `Referrer-Policy: no-referrer`, `no-store` (the `harden_handler` defaults skip headers a route already sent). Offline/redirect/non-HTML/oversize/plugin error → 502 HTML "Couldn't load the documentation for : " with a link back to /plugins. Status data: every `/api/plugins` row and `/api/config/controller` `live` carry `docs: true/false` from the same validation. Tests: `tests/test_plugin_docs.py`; contract text in PLUGIN_API.md / BUILD_PLUGIN_API.md (`GET /docs`) | | `/models` or `/models.html` | 302 to `/plugins` — the vision provider (Local model or GitHub Copilot) is chosen in the monkeytester-ai plugin's Configure panel there | | `/copilot` or `/copilot.html` | 302 to `/plugins` — GitHub Copilot is signed in on the monkeytester-ai plugin | | `/run-status` or `/run-status.html` | Run Status: active and queued runs/tests. Signed-in users | diff --git a/BUILD_PLUGIN_API.md b/BUILD_PLUGIN_API.md index 2032e8f..d10e5b4 100644 --- a/BUILD_PLUGIN_API.md +++ b/BUILD_PLUGIN_API.md @@ -57,6 +57,7 @@ Same as [PLUGIN_API.md](PLUGIN_API.md): "viewer_url": "http://192.168.1.10:8089", "queue": {"running": "br_0123456789abcdef", "waiting": 0}, "capabilities": ["logs", "cancel"], + "docs": "/docs", "error": null } ``` @@ -68,10 +69,21 @@ Same as [PLUGIN_API.md](PLUGIN_API.md): → `android`). Build & Test offers only these. - `recipes`: the file in the app repo that builds each platform. - `capabilities`: optional parts of this contract the plugin supports (`logs`, `cancel`). +- `docs` (optional): path of the plugin's documentation page, `"/docs"`; present only when + the page can be served (see `GET /docs` below). MonkeyTester refuses a plugin whose `contract` differs or whose `contract_version` it does not support. +### `GET /docs` (optional) + +The plugin's README as one self-contained HTML page, exactly as in +[PLUGIN_API.md → `GET /docs`](PLUGIN_API.md#get-docs-optional): pairing token required +like every route but `/health`, `text/html; charset=utf-8` under a strict CSP, `404` when +the README can't be read. The viewer's Build Plugin row shows a **Documentation** link +when `/health` reports `docs`; it opens `/plugins/docs/`, which the viewer fetches +with the saved token and serves under a sandbox CSP. + ### `GET /config` / `POST /config` `GET` → `{forge_kind, forge_url, token: {configured, last4, saved_at}, user, viewer_url}`. diff --git a/PLUGIN_API.md b/PLUGIN_API.md index ae38f6d..361f73c 100644 --- a/PLUGIN_API.md +++ b/PLUGIN_API.md @@ -99,15 +99,48 @@ Readiness. Never blocks on hardware. "host": {"os": "linux", "hostname": "server"}, "devices": 1, "capabilities": ["events", "uploads"], + "docs": "/docs", "error": null } ``` `capabilities` lists the optional parts of this contract the plugin supports. +`docs` (optional) is the path of the plugin's documentation page, normally `"/docs"` +(see [`GET /docs`](#get-docs-optional)). Advertise it only when the page can actually be +served (a packaged install without its README omits the field); no field means no +documentation, and the viewer shows no link. + MonkeyTester refuses a plugin whose `contract` differs or whose `contract_version` is not one it supports. +### `GET /docs` (optional) + +The plugin's documentation (setup, endpoints, configuration) as one self-contained +HTML page, rendered from the repo's `README.md` by the shared `docs_page.py`. Offered +only when `GET /health` has `"docs": "/docs"`. + +- Auth like every other route: only `/health` is open, so with a token configured + `/docs` needs `X-Plugin-Token` (401 otherwise). +- `200`, `Content-Type: text/html; charset=utf-8`, with + `Content-Security-Policy: default-src 'none'; style-src 'unsafe-inline'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'`, + `X-Content-Type-Options: nosniff`, `Cache-Control: no-store`. No scripts, no + external assets. +- README missing or unreadable: `404` with the usual error body. + +Browsers never call it directly. On Settings → Plugins, a row whose plugin reports +`docs` shows a **Documentation** link under its address; it opens the viewer's +`GET /plugins/docs/` in a new tab, and the viewer fetches the page from the +plugin with the plugin's saved token (no redirects followed, `text/html` only, at most +2 MiB) and serves it under a sandbox CSP (`… img-src data: …; sandbox`), so nothing in +it can run on the viewer's origin. The viewer accepts `docs` only as a path: a string +starting with `/` (not `//`), no `\`, no scheme, no CR/LF, at most 256 characters. + +The same applies to monkeytester-ai (pairing token as `X-Plugin-Token`), to build +plugins ([BUILD_PLUGIN_API.md](BUILD_PLUGIN_API.md)) and to the Mobile Controller: its +`GET /health` may carry `"docs": "/docs"` and its `GET /docs` takes `X-Controller-Token` +like its other routes; its row's link is `/plugins/docs/controller`. + ### `GET /devices` ```json diff --git a/app.py b/app.py index 41ffcc8..d62fcbf 100644 --- a/app.py +++ b/app.py @@ -9,6 +9,8 @@ import sys import threading import time +import urllib.error +import urllib.request import uuid import zipfile import io @@ -287,7 +289,8 @@ def controller_status(): "error": f"API version is {version}, expected {CONTROLLER_API_VERSION}; " "update whichever is older"} return {"ok": bool(body.get("ok")), "url": base, "api_version": version, - "appium": body.get("appium"), "adb": body.get("adb")} + "appium": body.get("appium"), "adb": body.get("adb"), + "docs": sec.plugin_docs_path(body.get("docs")) is not None} _PLUGIN_SELECTED_CACHE = {} # plugin name -> (selected model id, when) @@ -710,9 +713,126 @@ def plugins_overview(): out["plugins"].append(row) out["ai_plugin"] = {"name": pc.AI_PLUGIN_NAME, "url": url, "configured": bool(url), "token": token_info(key), "managed": managed} + # docs: the plugin's /health advertises a valid GET /docs path, so the + # /plugins row shows its Documentation link (served via /plugins/docs/). + for row in out["plugins"]: + row["docs"] = sec.plugin_docs_path(row.get("docs")) is not None return out +# ─── Plugin documentation (GET /plugins/docs/) ─── +# A plugin whose /health advertises "docs": "/docs" serves its README as an +# HTML page. The browser never talks to a plugin: the viewer fetches the page +# with that plugin's saved token and serves it under a sandbox CSP, so a +# script in the plugin's page can never run on the viewer's origin. +PLUGIN_DOCS_NAME_RE = re.compile(r"^[A-Za-z0-9._-]{1,64}$") +PLUGIN_DOCS_HEALTH_TIMEOUT = 3 +PLUGIN_DOCS_TIMEOUT = 10 +PLUGIN_DOCS_MAX_BYTES = 2 * 1024 * 1024 +PLUGIN_DOCS_CSP = ("default-src 'none'; style-src 'unsafe-inline'; img-src data:; " + "base-uri 'none'; form-action 'none'; frame-ancestors 'none'; sandbox") +PLUGIN_DOCS_ERROR_CSP = ("default-src 'none'; style-src 'unsafe-inline'; base-uri 'none'; " + "form-action 'none'; frame-ancestors 'none'") +CONTROLLER_ROW_KEY = "controller" # the Controller Plugin row's key on /plugins + + +class PluginDocsError(Exception): + """status 404 (no such plugin / no documentation) or 502 (fetch failed).""" + + def __init__(self, status, message): + super().__init__(message) + self.status = status + self.message = message + + +def plugin_docs_target(name): + """(base url, request headers) for a /plugins row key, from the viewer's + own config — the same lookups the rows and Configure panels use — or None + for an unknown name. Device plugins, monkeytester-ai and build plugins + send X-Plugin-Token; the Mobile Controller (row key "controller", unless a + plugin is registered under that name) sends X-Controller-Token.""" + if not isinstance(name, str) or not PLUGIN_DOCS_NAME_RE.fullmatch(name): + return None + pc = _plugin_client() + cfg = load_config() + if name == pc.AI_PLUGIN_NAME: + url = ai_plugin_url(cfg) + if not url: + return None + key = ai_pairing_token(cfg) + return url.rstrip("/"), ({"X-Plugin-Token": key} if key else {}) + try: + devices = pc.load_plugins(cfg) + except pc.PluginError: + devices = {} + if name in devices: + token = auth.plugin_token(name) or devices[name].token or "" + return devices[name].url.rstrip("/"), ({"X-Plugin-Token": token} if token else {}) + registry = _builds().registry_plugins() + if name in registry: + token = registry[name].get("token") or builds._saved_token(name) + return registry[name]["url"].rstrip("/"), ({"X-Plugin-Token": token} if token else {}) + if name == CONTROLLER_ROW_KEY: + base = _controller_url() + if base: + return base, _controller_headers() + return None + + +class _NoRedirect(urllib.request.HTTPRedirectHandler): + """Turn every 3xx into an HTTPError: the docs proxy never follows one.""" + + def redirect_request(self, req, fp, code, msg, headers, newurl): + return None + + +def fetch_plugin_docs(name): + """The plugin's documentation page as bytes. Raises PluginDocsError: + 404 for an unknown name or a missing/invalid /health `docs` path, 502 + when the plugin is offline, redirects, answers non-HTML, an error or + more than PLUGIN_DOCS_MAX_BYTES.""" + target = plugin_docs_target(name) + if not target: + raise PluginDocsError(404, f"There is no plugin named {name!r} on this viewer.") + base, headers = target + opener = urllib.request.build_opener(_NoRedirect) + + def open_(path, timeout, accept): + req = urllib.request.Request(sec.check_http_url(base + path), + headers={**headers, "Accept": accept}) + return opener.open(req, timeout=timeout) # nosec B310 + + try: + with open_("/health", PLUGIN_DOCS_HEALTH_TIMEOUT, "application/json") as resp: + health = json.loads(resp.read(256 * 1024).decode() or "{}") + except urllib.error.HTTPError as e: + e.close() + raise PluginDocsError(502, f"GET /health answered HTTP {e.code}") from None + except Exception as e: + raise PluginDocsError(502, f"the plugin is unreachable ({getattr(e, 'reason', e)})") from None + docs = sec.plugin_docs_path(health.get("docs") if isinstance(health, dict) else None) + if not docs: + raise PluginDocsError(404, "This plugin has no documentation.") + try: + with open_(docs, PLUGIN_DOCS_TIMEOUT, "text/html") as resp: + if resp.headers.get_content_type() != "text/html": + raise PluginDocsError(502, "the plugin answered with " + f"{resp.headers.get_content_type()}, not text/html") + body = resp.read(PLUGIN_DOCS_MAX_BYTES + 1) + except PluginDocsError: + raise + except urllib.error.HTTPError as e: + e.close() + if 300 <= e.code < 400: + raise PluginDocsError(502, f"the plugin answered with a redirect (HTTP {e.code})") from None + raise PluginDocsError(502, f"GET {docs} answered HTTP {e.code}") from None + except Exception as e: + raise PluginDocsError(502, f"the plugin is unreachable ({getattr(e, 'reason', e)})") from None + if len(body) > PLUGIN_DOCS_MAX_BYTES: + raise PluginDocsError(502, "the page is larger than 2 MiB") + return body + + AI_NOT_CONFIGURED = ("no monkeytester-ai plugin configured — set its address first " "in Settings → Device Plugins (its Configure panel)") @@ -2862,6 +2982,10 @@ def do_GET(self): self.end_headers() elif path == "/plugins" or path == "/plugins.html": self.serve_page("plugins.html") + elif path.startswith("/plugins/docs/"): + # A plugin's documentation page, fetched from the plugin by the + # viewer (the /plugins rows' Documentation link opens it). + self.serve_plugin_docs(path[len("/plugins/docs/"):]) elif path == "/models" or path == "/models.html": # The model picker now lives inside the Device Plugins panel: # clicking the AI plugin row configures it there. Old bookmarks @@ -3244,6 +3368,52 @@ def serve_page(self, filename): else: self.send_error(404) + def serve_plugin_docs(self, name): + """GET /plugins/docs/: the plugin's GET /docs page, proxied with + its saved token and served under a sandbox CSP (PLUGIN_DOCS_CSP), so + nothing in it can run on the viewer's origin. Unknown name or no + documentation → 404 page; fetch failure → 502 page.""" + try: + body = fetch_plugin_docs(name) + except PluginDocsError as e: + self.send_plugin_docs_error(name, e.status, e.message) + return + self.send_response(200) + self.send_header("Content-Type", "text/html; charset=utf-8") + self.send_header("Content-Length", str(len(body))) + self.send_header("Content-Security-Policy", PLUGIN_DOCS_CSP) + self.send_header("X-Content-Type-Options", "nosniff") + self.send_header("Referrer-Policy", "no-referrer") + self.send_header("Cache-Control", "no-store") + self.end_headers() + self.wfile.write(body) + + def send_plugin_docs_error(self, name, status, message): + """Small self-contained HTML page for a docs failure, everything escaped.""" + import html as _html + shown = name if PLUGIN_DOCS_NAME_RE.fullmatch(name or "") else "this plugin" + if status == 404: + title = "No documentation" + text = message + else: + title = "Documentation unavailable" + text = f"Couldn't load the documentation for {shown}: {message}" + page = ("" + f"{_html.escape(title)}" + f"

{_html.escape(title)}

{_html.escape(text)}

" + "

Back to Plugins

").encode() + self.send_response(status) + self.send_header("Content-Type", "text/html; charset=utf-8") + self.send_header("Content-Length", str(len(page))) + # Its own CSP without `sandbox`: the page is the viewer's own (no + # plugin bytes), and its Back link must keep the session cookie. + self.send_header("Content-Security-Policy", PLUGIN_DOCS_ERROR_CSP) + self.send_header("Referrer-Policy", "no-referrer") + self.send_header("Cache-Control", "no-store") + self.end_headers() + self.wfile.write(page) + def serve_font(self, name): """GET /fonts/.woff2 — one of the woff2 files in fonts/. diff --git a/build_plugin_client.py b/build_plugin_client.py index a13369b..4e4a312 100644 --- a/build_plugin_client.py +++ b/build_plugin_client.py @@ -317,6 +317,9 @@ def health_entry(client, timeout=3): viewer_url=str(body.get("viewer_url") or ""), queue={"running": queue.get("running"), "waiting": queue.get("waiting")} if queue else None, capabilities=[str(c) for c in body.get("capabilities") or [] if isinstance(c, str)]) + if isinstance(body.get("docs"), str): + # Optional GET /docs path, raw; the viewer validates it (docs: true/false). + entry["docs"] = body["docs"] if not entry["ok"]: entry["error"] = str(body.get("error") or "plugin reports not ok") return entry diff --git a/mt-tests/scripts/plugin_client.py b/mt-tests/scripts/plugin_client.py index 8c7977e..bb7d325 100644 --- a/mt-tests/scripts/plugin_client.py +++ b/mt-tests/scripts/plugin_client.py @@ -717,6 +717,10 @@ def check(client): config=None) if body is not None: entry["capabilities"] = body.get("capabilities") or [] + # The optional /health `docs` path, raw: the viewer validates it + # and passes only a docs true/false on to the browser. + if isinstance(body.get("docs"), str): + entry["docs"] = body["docs"] try: entry["devices"] = client.devices(timeout=timeout) except PluginError: diff --git a/plugins.html b/plugins.html index dcc837d..066836e 100644 --- a/plugins.html +++ b/plugins.html @@ -36,6 +36,12 @@ .plugin-table td.pt-address { min-width: 220px; } .plugin-table td.pt-address input { width: 100%; box-sizing: border-box; background: var(--card); border: 1px solid var(--border); color: var(--text); padding: 4px 8px; font-family: monospace; font-size: 0.8rem; } .plugin-table td.pt-address code { font-family: monospace; font-size: 0.8rem; color: var(--text); word-break: break-all; } +/* Documentation link at the bottom of the Details cell, under a thin rule: + shown only when the plugin's /health advertises docs; opens + /plugins/docs/ in a new tab. */ +.plugin-table td.pt-details hr.pt-docs-sep { border: 0; border-top: 1px solid var(--border); margin: 6px 0; } +.plugin-table td.pt-details a.pt-docs { font-size: 0.8rem; color: var(--accent); text-decoration: underline; } +.plugin-table td.pt-details a.pt-docs:hover { color: var(--text); } .plugin-table td.pt-details { font-size: 0.75rem; color: var(--text-muted); line-height: 1.5; } .plugin-table td.pt-details code { font-family: monospace; font-size: 0.75rem; } .plugin-table td.pt-details .bad { color: var(--fail); } @@ -231,17 +237,34 @@

Plugins

btn.disabled = !inp || !inp.value.trim() || normAddr(inp.value) === normAddr(inp.dataset.saved); } +// The Details cell, plus a Documentation link under a thin rule when the +// plugin's /health advertises docs. The cell is plain HTML (no inputs), so it +// is safe to re-render through setHtml on every refresh. +function detailsWithDocs(r) { + if (!r.docs) return r.details; + return r.details + '
Documentation'; +} + function updatePluginRow(tr, r) { const [tdName, tdStatus, tdAddr, tdDetails, tdActions] = tr.children; if (tdName.textContent !== r.name) tdName.textContent = r.name; setHtml(tdStatus, r.status); if (r.readonly) { - setHtml(tdAddr, "" + escapeHtml(r.saved || "\u2014") + ""); + let code = tdAddr.querySelector("code.pt-addr-ro"); + if (!code) { + tdAddr.textContent = ""; + code = document.createElement("code"); + code.className = "pt-addr-ro"; + tdAddr.appendChild(code); + } + const text = r.saved || "\u2014"; + if (code.textContent !== text) code.textContent = text; } else { let inp = tdAddr.querySelector("input.pt-addr"); if (!inp) { - tdAddr.innerHTML = ""; - tdAddr.__html = null; + tdAddr.textContent = ""; inp = document.createElement("input"); inp.type = "url"; inp.className = "pt-addr"; @@ -258,13 +281,13 @@

Plugins

inp.dataset.saved = r.saved; } } - setHtml(tdDetails, r.details); + setHtml(tdDetails, detailsWithDocs(r)); setHtml(tdActions, r.actions); tr.classList.toggle("configuring", !!r.open); updateRowDirty(tr); } -// rows: [{key, name, status, saved, readonly, details, actions, open}]. +// rows: [{key, name, status, saved, readonly, docs, details, actions, open}]. // onConfigureGone(): called when the plugin with the open configure row // disappeared (removed elsewhere) — the section closes its panel. function syncPluginTable(tbody, rows, emptyMsg, onConfigureGone) { @@ -461,7 +484,7 @@

Plugins

return { key: p.name, name: p.name, status: statusCell(p.ok, p.__ai && !aiPluginState.configured), - saved: p.url || "", readonly: managed, + saved: p.url || "", readonly: managed, docs: !!p.docs, details: detailsHtml(p, { managed }), open, actions: actionsHtml({ save: !managed, configure: !!(p.config || p.__ai), remove: !managed, open }), @@ -535,7 +558,7 @@

Plugins

const open = panelOpen && buildPanelPlugin === p.name; return { key: p.name, name: p.name, status: statusCell(p.ok, false), - saved: p.url || "", readonly: false, + saved: p.url || "", readonly: false, docs: !!p.docs, details: detailsHtml(p, { build: true }), open, actions: actionsHtml({ save: true, configure: true, remove: true, open }), }; @@ -1603,7 +1626,7 @@

Plugins

const rows = configured ? [{ key: "controller", name: data.name || "controller", status: statusCell(!!live.ok, false), - saved: data.url || "", readonly: false, + saved: data.url || "", readonly: false, docs: !!live.docs, details: controllerDetails(data), open: controllerPanelOpen, actions: actionsHtml({ save: true, configure: true, remove: true, open: controllerPanelOpen }), }] : []; diff --git a/security_utils.py b/security_utils.py index 4a6ee08..a763f76 100644 --- a/security_utils.py +++ b/security_utils.py @@ -197,6 +197,25 @@ def write_private_json(path, data): raise +# ─── Plugin documentation path (GET /plugins/docs/) ─── + +def plugin_docs_path(value): + """The `docs` field of a plugin's /health when it is a safe same-origin + path, else None. Valid: a string starting with "/" (not "//"), no + backslash, no scheme, no CR/LF/NUL, at most 256 characters. The viewer + appends it to the plugin's own base URL, so anything that could name + another host or protocol is refused.""" + if not isinstance(value, str) or not value or len(value) > 256: + return None + if not value.startswith("/") or value.startswith("//"): + return None + if any(c in value for c in ("\\", "\r", "\n", "\x00")): + return None + if re.match(r"^/*[A-Za-z][A-Za-z0-9+.-]*:", value) or "://" in value: + return None + return value + + # ─── HTTP handler hardening ─── SECURITY_HEADERS = ( @@ -231,16 +250,30 @@ def harden_handler(cls): def send_response(self, code, message=None): self._mt_response_started = True + self._mt_header_names = set() orig_send_response(self, code, message) def end_headers(self): if not getattr(self, "_mt_security_headers_sent", False): self._mt_security_headers_sent = True + sent = getattr(self, "_mt_header_names", None) or set() for name, value in SECURITY_HEADERS: - self.send_header(name, value) + if name.lower() not in sent: + self.send_header(name, value) orig_end_headers(self) + orig_send_header = cls.send_header + + def send_header(self, keyword, value): + # A route may set its own value for a hardening header (the plugin + # docs page sends Referrer-Policy: no-referrer); end_headers then + # skips the default instead of sending the header twice. + sent = self.__dict__.setdefault("_mt_header_names", set()) + sent.add(str(keyword).lower()) + orig_send_header(self, keyword, value) + cls.send_response = send_response + cls.send_header = send_header cls.end_headers = end_headers def guard(method, not_found_if_silent): diff --git a/tests/test_app_api.py b/tests/test_app_api.py index ee9559e..60817a5 100644 --- a/tests/test_app_api.py +++ b/tests/test_app_api.py @@ -269,7 +269,7 @@ def test_live_plugin_state_is_reported(self): "contract_version": 1, "plugin": {"name": "esp32", "version": "0.1.0"}, "capabilities": ["flash"], - "config": None, + "config": None, "docs": False, "devices": [{"id": "ab:cd", "model": "C3", "state": "ready"}]}) self.assertFalse(by_name["monkeytester-ai"]["ok"]) # listed, not configured diff --git a/tests/test_plugin_docs.py b/tests/test_plugin_docs.py new file mode 100644 index 0000000..c9a8cb7 --- /dev/null +++ b/tests/test_plugin_docs.py @@ -0,0 +1,236 @@ +"""GET /plugins/docs/: the viewer proxies a plugin's GET /docs page +(PLUGIN_API.md "Documentation"), and /api/plugins carries `docs`.""" +import json +import threading +import unittest +import urllib.error +import urllib.request +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from unittest.mock import patch + +import app +import security_utils as sec +import viewer_auth as auth +from tests.test_app_api import ServerCase, SignedInHandler, raw_get + +CONTRACT_HEALTH = {"ok": True, "contract": "monkeytester-plugin", "contract_version": 1, + "plugin": {"name": "esp32-sensor", "version": "1.0.0"}} +DOCS_PAGE = b"

ESP32 sensor

" + + +class DocsPlugin(BaseHTTPRequestHandler): + """A plugin that serves /health (+ docs field) and GET /docs.""" + health = {} + docs_status = 200 + docs_type = "text/html; charset=utf-8" + docs_body = DOCS_PAGE + docs_location: "str | None" = None + seen = [] # (path, X-Plugin-Token, X-Controller-Token) + + def log_message(self, *args): + pass + + def do_GET(self): + DocsPlugin.seen.append((self.path, self.headers.get("X-Plugin-Token"), + self.headers.get("X-Controller-Token"))) + if self.path == "/health": + body = json.dumps(DocsPlugin.health).encode() + self.send_response(200) + self.send_header("Content-Type", "application/json") + elif self.path == "/devices": + body = b'{"devices": []}' + self.send_response(200) + self.send_header("Content-Type", "application/json") + elif self.path == "/docs": + body = DocsPlugin.docs_body + self.send_response(DocsPlugin.docs_status) + self.send_header("Content-Type", DocsPlugin.docs_type) + if DocsPlugin.docs_location: + self.send_header("Location", DocsPlugin.docs_location) + else: + body = b'{"error": "not found"}' + self.send_response(404) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + +class PluginDocsCase(ServerCase): + @classmethod + def setUpClass(cls): + super().setUpClass() + cls.docs = ThreadingHTTPServer(("127.0.0.1", 0), DocsPlugin) + cls.docs_url = f"http://127.0.0.1:{cls.docs.server_address[1]}" + threading.Thread(target=cls.docs.serve_forever, daemon=True).start() + + @classmethod + def tearDownClass(cls): + cls.docs.shutdown() + cls.docs.server_close() + super().tearDownClass() + + def setUp(self): + super().setUp() + DocsPlugin.health = dict(CONTRACT_HEALTH, docs="/docs") + DocsPlugin.docs_status, DocsPlugin.docs_type = 200, "text/html; charset=utf-8" + DocsPlugin.docs_body, DocsPlugin.docs_location, DocsPlugin.seen = DOCS_PAGE, None, [] + (self.runs / "config.json").write_text(json.dumps({"plugins": {"esp32-sensor": self.docs_url}})) + auth.save_tokens({"plugins": {"esp32-sensor": {"token": "esp-token-1234", "saved_at": 1}}}) + + def fetch(self, path, auth_=True): + """(status, headers, body) without following redirects.""" + class NoRedirect(urllib.request.HTTPRedirectHandler): + def redirect_request(self, *a, **k): + return None + req = urllib.request.Request(f"http://127.0.0.1:{self.port}{path}") + handlers: list = [NoRedirect()] + if auth_: + handlers.append(SignedInHandler(self.port)) + else: + req.add_header("Cookie", "none=1") + opener = urllib.request.build_opener(*handlers) + try: + with opener.open(req, timeout=20) as resp: + return resp.status, resp.headers, resp.read() + except urllib.error.HTTPError as e: + with e: + return e.code, e.headers, e.read() + + +class ProxyTests(PluginDocsCase): + def test_passes_the_page_through_under_a_sandbox_csp(self): + status, headers, body = self.fetch("/plugins/docs/esp32-sensor") + self.assertEqual(status, 200) + self.assertEqual(body, DOCS_PAGE) + self.assertEqual(headers["Content-Type"], "text/html; charset=utf-8") + csp = headers["Content-Security-Policy"] + self.assertEqual(csp, app.PLUGIN_DOCS_CSP) + self.assertTrue(csp.endswith("; sandbox")) + self.assertIn("default-src 'none'", csp) + self.assertEqual(headers.get_all("Referrer-Policy"), ["no-referrer"]) + self.assertEqual(headers.get_all("X-Content-Type-Options"), ["nosniff"]) + self.assertEqual(headers["Cache-Control"], "no-store") + + def test_sends_the_plugins_saved_token(self): + self.fetch("/plugins/docs/esp32-sensor") + self.assertIn(("/docs", "esp-token-1234", None), DocsPlugin.seen) + + def test_controller_gets_its_controller_token(self): + (self.runs / "config.json").write_text(json.dumps({"controller_url": self.docs_url})) + auth.save_tokens({"plugins": {}, "controller": {"token": "ctl-token-5678", "saved_at": 1}}) + status, _, body = self.fetch("/plugins/docs/controller") + self.assertEqual((status, body), (200, DOCS_PAGE)) + self.assertIn(("/docs", None, "ctl-token-5678"), DocsPlugin.seen) + + def test_ai_plugin_gets_its_pairing_token(self): + (self.runs / "config.json").write_text(json.dumps({ + "plugins": {}, "visual_plugin_url": self.docs_url, "visual_plugin": "monkeytester-ai", + "visual_api_key": "ai-pairing-9999"})) + status, _, _ = self.fetch("/plugins/docs/monkeytester-ai") + self.assertEqual(status, 200) + self.assertIn(("/docs", "ai-pairing-9999", None), DocsPlugin.seen) + + def test_build_plugin(self): + (self.runs / "config.json").write_text(json.dumps({ + "plugins": {"build-local": {"url": self.docs_url, "token": ""}}})) + auth.save_tokens({"plugins": {"build-local": {"token": "build-tok-4321", "saved_at": 1}}}) + status, _, _ = self.fetch("/plugins/docs/build-local") + self.assertEqual(status, 200) + self.assertIn(("/docs", "build-tok-4321", None), DocsPlugin.seen) + + def test_unknown_name_is_404_without_contacting_anything(self): + for name in ("nope", "bad%20name", "a" * 65, "controller"): + status, headers, body = self.fetch("/plugins/docs/" + name) + self.assertEqual(status, 404, name) + self.assertTrue(headers["Content-Type"].startswith("text/html"), name) + self.assertEqual(DocsPlugin.seen, []) + + def test_invalid_or_missing_docs_path_is_404(self): + for docs in ("//evil.example/docs", "http://x/docs", "docs", "/a\\b", "/a\r\nb", + "/" + "x" * 300, 5, None): + DocsPlugin.health = dict(CONTRACT_HEALTH, docs=docs) + if docs is None: + DocsPlugin.health.pop("docs") + DocsPlugin.seen = [] + status, _, body = self.fetch("/plugins/docs/esp32-sensor") + self.assertEqual(status, 404, repr(docs)) + self.assertIn(b"no documentation", body) + self.assertEqual([p for p, _, _ in DocsPlugin.seen], ["/health"], repr(docs)) + + def test_redirect_is_502_and_not_followed(self): + DocsPlugin.docs_status, DocsPlugin.docs_location = 302, "/health" + status, _, body = self.fetch("/plugins/docs/esp32-sensor") + self.assertEqual(status, 502) + self.assertIn(b"redirect", body) + self.assertEqual([p for p, _, _ in DocsPlugin.seen], ["/health", "/docs"]) + + def test_non_html_is_502(self): + DocsPlugin.docs_type = "application/json" + status, _, body = self.fetch("/plugins/docs/esp32-sensor") + self.assertEqual(status, 502) + self.assertIn(b"Couldn't load the documentation for esp32-sensor", body) + self.assertIn(b'href="/plugins"', body) + + def test_plugin_error_status_is_502(self): + DocsPlugin.docs_status = 404 + status, _, _ = self.fetch("/plugins/docs/esp32-sensor") + self.assertEqual(status, 502) + + def test_oversize_is_502(self): + with patch.object(app, "PLUGIN_DOCS_MAX_BYTES", 64): + status, _, body = self.fetch("/plugins/docs/esp32-sensor") + self.assertEqual(status, 502) + self.assertIn(b"larger than", body) + + def test_offline_is_502(self): + (self.runs / "config.json").write_text(json.dumps({"plugins": {"esp32-sensor": "http://127.0.0.1:9"}})) + status, _, body = self.fetch("/plugins/docs/esp32-sensor") + self.assertEqual(status, 502) + self.assertIn(b"unreachable", body) + + def test_error_page_escapes_the_reason(self): + DocsPlugin.docs_type = "text/evil" + _, _, body = self.fetch("/plugins/docs/esp32-sensor") + self.assertNotIn(b"evil", body) + + def test_unauthenticated_redirects_to_login(self): + status, body = raw_get(self.port, "/plugins/docs/esp32-sensor", auth=False) + self.assertEqual(status, 302) + self.assertEqual(DocsPlugin.seen, []) + status, headers, _ = self.fetch("/plugins/docs/esp32-sensor", auth_=False) + self.assertEqual(status, 302) + self.assertTrue(headers["Location"].startswith("/login")) + + +class StatusDataTests(PluginDocsCase): + def test_api_plugins_carries_docs(self): + DocsPlugin.health = dict(CONTRACT_HEALTH, docs="/docs") + rows = {p["name"]: p for p in self.get_json("/api/plugins")["plugins"]} + self.assertIs(rows["esp32-sensor"]["docs"], True) + + def test_api_plugins_docs_false_without_or_with_invalid_field(self): + for health in (dict(CONTRACT_HEALTH), dict(CONTRACT_HEALTH, docs="//evil")): + DocsPlugin.health = health + rows = {p["name"]: p for p in self.get_json("/api/plugins")["plugins"]} + self.assertIs(rows["esp32-sensor"]["docs"], False) + + def test_controller_live_carries_docs(self): + (self.runs / "config.json").write_text(json.dumps({"controller_url": self.docs_url})) + DocsPlugin.health = {"ok": True, "api_version": app.CONTROLLER_API_VERSION, "docs": "/docs"} + self.assertIs(self.get_json("/api/config/controller")["live"]["docs"], True) + DocsPlugin.health = {"ok": True, "api_version": app.CONTROLLER_API_VERSION} + self.assertIs(self.get_json("/api/config/controller")["live"]["docs"], False) + + +class DocsPathTests(unittest.TestCase): + def test_validation(self): + self.assertEqual(sec.plugin_docs_path("/docs"), "/docs") + self.assertEqual(sec.plugin_docs_path("/api/docs?x=1"), "/api/docs?x=1") + for bad in ("", "docs", "//x", "/\\x", "http://x", "https://x/docs", "/a\nb", "/a\rb", + "/x\x00", "/a://b", "/" + "a" * 256, None, 3, ["/docs"]): + self.assertIsNone(sec.plugin_docs_path(bad), repr(bad)) + + +if __name__ == "__main__": + unittest.main()