From 635fd764cf5a5c62d3b5370774f369e4db430fe4 Mon Sep 17 00:00:00 2001 From: gbarnai Date: Sun, 29 Nov 2026 15:00:16 -0500 Subject: [PATCH 1/2] fix: run the registry's check script in a separate process Submit to Registry now starts tools/check.py as its own program with a clean environment, a temporary home folder, a time limit and its output kept, and stops it and the programs it started when the limit passes. The engine self check covers it. --- backend/HASHOUT_LOG.md | 5 +- backend/app/services/publish.py | 41 +---- backend/app/services/registry_check.py | 126 +++++++++++++ backend/app/services/registry_check_worker.py | 62 +++++++ backend/formext_engine.py | 37 ++++ docs/MANUAL.md | 2 +- frontend/src/panes/run/HASHOUT_LOG.md | 2 +- tests/publish/test_registry_check_process.py | 167 ++++++++++++++++++ 8 files changed, 405 insertions(+), 37 deletions(-) create mode 100644 backend/app/services/registry_check.py create mode 100644 backend/app/services/registry_check_worker.py create mode 100644 tests/publish/test_registry_check_process.py diff --git a/backend/HASHOUT_LOG.md b/backend/HASHOUT_LOG.md index 3be5f3f..0a4d768 100644 --- a/backend/HASHOUT_LOG.md +++ b/backend/HASHOUT_LOG.md @@ -4,13 +4,14 @@ The living log of the form.ext engine. Read it before editing `backend/`. Core f ## Unreleased: loopback requests, window-only checkout, plain launcher words {#loopback} -- refers-to: app/services/local_host.py; app/services/agent_start.py; app/services/settings.py; app/services/consent.py; app/cli.py; ../setup/agents.py +- refers-to: app/services/local_host.py; app/services/agent_start.py; app/services/settings.py; app/services/consent.py; app/cli.py; ../setup/agents.py; app/services/registry_check.py; app/services/registry_check_worker.py; formext_engine.py - `LoopbackHostGuard` (outermost middleware) refuses any HTTP request or WebSocket whose Host is not localhost, 127.0.0.1, ::1 or tauri.localhost; in-process calls pass. `/api/live` checks Origin and Host with the same `origin_ok` the terminal routes use. Test clients use `http://127.0.0.1:8640`, and WebSocket tests give the full `ws://127.0.0.1:8640/...` address because the test client ignores its base address for sockets. - `registry.checkout` changes only with the window key, like `agent_access`. The `submit` tool's `checkout` goes in the body of `POST /api/publish/{pid}/registry` (and `/registry/pull-request`) and is used for that submit only. - The consent request's `what` names the local path argument (`LOCAL_PATHS`), made absolute before the check. At most `MAX_WAITING` (8) requests wait at once. `run_op` asks `forwards()` once. `package` writes only to a folder or a `.formpkg` name, through a temporary file. - `agent_lookup.py` stays the shared 1.0.1 copy. `agent_start.start_argv` wraps it: on Windows an npm `.cmd` launcher is followed to its script (with the `node.exe` beside it or `node` on PATH) or its `.exe`; any other `.cmd` or `.bat` goes through `cmd.exe /c` only when every word is plain. On Windows the MCP launcher is `formext.bat`. - The consent `what` shows the resolved path, keeps a trailing separator, and writes control, format and line separator characters as `\uXXXX`. `package` writes its temporary file with `tempfile.mkstemp`. `POST /api/window/key` checks Origin and Host with `origin_ok`. Words given to `cmd.exe /c` may not hold any of `& | < > ^ ( ) !` even inside spaces, since `cmd /c` can strip the outer quotes. The refusal (`agent_start.RefusedWord`) says to pass long or special text through stdin or a file when the program accepts one. -- Not run: anything on Windows. +- `publish._run_registry_check` no longer imports the registry's `tools/check.py`. `services/registry_check.py` starts `services/registry_check_worker.py` (`python -I`, or `formext-engine registry-check` when frozen) with the checkout as working folder and an environment made only of `PASSED_VARS` (PATH, locale, temp and the Windows system variables) plus a scratch `HOME`, `USERPROFILE`, `APPDATA`, `XDG_*` and npm cache in a temporary folder removed afterwards. The worker calls the same functions as before and writes its answer to a file; standard output and error go to a second file, so programs the script starts are kept too (last `OUTPUT_LIMIT` bytes). The child gets its own session (a new process group on Windows); past `FORMEXT_REGISTRY_CHECK_TIMEOUT` (default 300 s) the group is killed (`taskkill /T` on Windows) and the submit answers 400 with a sentence. This supersedes the in-process owner decision in `#pr-lock`, and with it the shared `redirect_stdout` race. The self check adds `registry_check_isolated`: a stand-in script must answer from another process id and must not see a variable set in the engine. +- Not run: the frozen engine's `registry-check` entry and the Windows paths (process group, `taskkill`). ## v0.11.0: one runner for the tests, by layer {#test-runner} diff --git a/backend/app/services/publish.py b/backend/app/services/publish.py index 22af408..3e191c3 100644 --- a/backend/app/services/publish.py +++ b/backend/app/services/publish.py @@ -7,7 +7,7 @@ import time from pathlib import Path -from app.services import paths, portal, registry, settings, sources +from app.services import paths, portal, registry, registry_check, settings, sources from app.services.bus import bus from app.services.keys import keys from app.services.package import DEFAULT_URL, packages @@ -428,41 +428,16 @@ def _registry_checks(root: Path, folder: Path, manifest: dict, chosen: str | Non def _run_registry_check(checkout: Path, script: Path, root: Path, folder: Path, manifest: dict) -> dict: - import contextlib - import importlib.util - import io - import sys - from types import SimpleNamespace - - added = [str(checkout / "tools"), str(checkout / "contract" / "tools")] - for p in added: - if p not in sys.path: - sys.path.insert(0, p) - spec = importlib.util.spec_from_file_location("formext_registry_check", script) - if spec is None or spec.loader is None: - raise WorkspaceError(f"{script} cannot be imported") - module = importlib.util.module_from_spec(spec) - buf = io.StringIO() url = registry.index_url() - with contextlib.redirect_stdout(buf), contextlib.redirect_stderr(buf): - try: - sys.modules[spec.name] = module - spec.loader.exec_module(module) - probe = module.Result("published index") - published = module.published_index(None if url == registry.DEFAULT_URL else url, probe) - blocked, _ = module.registry.load_blocklist() - args = SimpleNamespace(skip_npm=False) - result = module.check_extension(folder, args, published, None, True, blocked) - except (SystemExit, AttributeError, TypeError) as e: - raise WorkspaceError(f"the registry's tools/check.py in {checkout} could not run on the folder ({e})") from None - lines = [f"Form Extension Registry checks ({script})"] + [f"note: {n}" for n in probe.notes] - lines += ["", f"{result.name}: {'FAILED' if result.errors else 'passed'}"] - lines += [f" ok {p}" for p in result.passed] + [f" error {e}" for e in result.errors] + [f" note {n}" for n in result.notes] - noise = buf.getvalue().strip() + result, noise = registry_check.run(script, checkout, folder, "" if url == registry.DEFAULT_URL else url) + name, errors = result.get("name") or folder.name, result.get("errors") or [] + lines = [f"Form Extension Registry checks ({script})"] + [f"note: {n}" for n in result.get("probe_notes") or []] + lines += ["", f"{name}: {'FAILED' if errors else 'passed'}"] + lines += [f" ok {p}" for p in result.get("passed") or []] + [f" error {e}" for e in errors] + [f" note {n}" for n in result.get("notes") or []] if noise: lines += ["", noise] - problems = [{"level": "error", "where": result.name, "message": e} for e in result.errors] - return {"by": "registry", "tool": str(script), "ok": not result.errors, "problems": problems, "report": "\n".join(lines), "note": f"The registry's own tools/check.py from {checkout} ran on the folder (imported, nothing vendored), as CI runs it on a pull request."} + problems = [{"level": "error", "where": name, "message": e} for e in errors] + return {"by": "registry", "tool": str(script), "ok": not errors, "problems": problems, "report": "\n".join(lines), "note": f"The registry's own tools/check.py from {checkout} ran on the folder in a process of its own (a clean environment, a scratch home, a time limit), as CI runs it on a pull request."} def submit(pid: str, checkout: str | None = None) -> dict: diff --git a/backend/app/services/registry_check.py b/backend/app/services/registry_check.py new file mode 100644 index 0000000..b11023e --- /dev/null +++ b/backend/app/services/registry_check.py @@ -0,0 +1,126 @@ +"""Runs a registry clone's tools/check.py in a process of its own: a clean environment with a scratch home, a time limit, +its output kept, and the whole process tree stopped when the limit passes.""" +from __future__ import annotations + +import json +import os +import signal +import subprocess +import sys +import tempfile +from pathlib import Path + +from app.services import paths, registry_check_worker +from app.services.workspace import WorkspaceError + +TIMEOUT_VAR = "FORMEXT_REGISTRY_CHECK_TIMEOUT" +TIMEOUT = 300.0 +OUTPUT_LIMIT = 64_000 +STOP_WAIT = 5 +WINDOWS = sys.platform == "win32" +PASSED_VARS = ("PATH", "LANG", "LC_ALL", "LC_CTYPE", "TZ", "TMPDIR", "TEMP", "TMP", "SYSTEMROOT", "SYSTEMDRIVE", "WINDIR", "COMSPEC", "PATHEXT") + + +def timeout() -> float: + raw = os.environ.get(TIMEOUT_VAR, "").strip() + try: + value = float(raw) if raw else TIMEOUT + except ValueError: + return TIMEOUT + return value if value > 0 else TIMEOUT + + +def child_env(home: Path, base: dict | None = None) -> dict: + source = os.environ if base is None else base + env = {k: source[k] for k in PASSED_VARS if source.get(k)} + env.update({ + "HOME": str(home), + "USERPROFILE": str(home), + "APPDATA": str(home / "AppData" / "Roaming"), + "LOCALAPPDATA": str(home / "AppData" / "Local"), + "XDG_CONFIG_HOME": str(home / ".config"), + "XDG_CACHE_HOME": str(home / ".cache"), + "npm_config_cache": str(home / ".npm"), + "GIT_TERMINAL_PROMPT": "0", + "PYTHONDONTWRITEBYTECODE": "1", + "PYTHONIOENCODING": "utf-8", + "PYTHONUTF8": "1", + }) + return env + + +def command(script: Path, checkout: Path, folder: Path, url: str, answer: Path) -> list[str]: + args = [str(script), str(checkout), str(folder), url, str(answer)] + if paths.frozen(): + return [sys.executable, "registry-check", *args] + return [sys.executable, "-I", registry_check_worker.__file__, *args] + + +def _stop(proc: subprocess.Popen) -> None: + if WINDOWS: + subprocess.run(["taskkill", "/PID", str(proc.pid), "/T", "/F"], stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0), timeout=STOP_WAIT * 2, check=False) + else: + try: + os.killpg(proc.pid, signal.SIGKILL) + except OSError: + pass + try: + proc.kill() + except OSError: + pass + try: + proc.wait(timeout=STOP_WAIT) + except subprocess.TimeoutExpired: + pass + + +def _start(argv: list[str], cwd: Path, env: dict, log) -> subprocess.Popen: + flags = (getattr(subprocess, "CREATE_NO_WINDOW", 0) | getattr(subprocess, "CREATE_NEW_PROCESS_GROUP", 0)) if WINDOWS else 0 + return subprocess.Popen(argv, cwd=str(cwd), env=env, stdin=subprocess.DEVNULL, stdout=log, stderr=subprocess.STDOUT, + start_new_session=not WINDOWS, creationflags=flags) + + +def _output(log: Path) -> str: + try: + data = log.read_bytes() + except OSError: + return "" + text = data[-OUTPUT_LIMIT:].decode("utf-8", errors="replace").strip() + return ("(earlier output cut)\n" + text) if len(data) > OUTPUT_LIMIT else text + + +def _seconds(value: float) -> str: + shown = f"{value:g}" + return f"{shown} second" + ("" if shown == "1" else "s") + + +def run(script: Path, checkout: Path, folder: Path, url: str) -> tuple[dict, str]: + """The script's answer ({name, passed, errors, notes, probe_notes}) and everything it printed.""" + limit = timeout() + with tempfile.TemporaryDirectory(prefix="formext-registry-check-", ignore_cleanup_errors=True) as tmp: + box = Path(tmp) + home = box / "home" + home.mkdir() + answer, log_path = box / "answer.json", box / "output.txt" + try: + with open(log_path, "wb") as log: + proc = _start(command(script, checkout, folder, url, answer), checkout, child_env(home), log) + try: + code = proc.wait(timeout=limit) + except subprocess.TimeoutExpired: + _stop(proc) + raise WorkspaceError(f"the registry's tools/check.py in {checkout} did not finish within {_seconds(limit)}, so it was stopped") from None + except OSError as e: + raise WorkspaceError(f"the registry's tools/check.py in {checkout} could not be started ({e})") from None + _stop(proc) + output = _output(log_path) + try: + out = json.loads(answer.read_text(encoding="utf-8")) + except (OSError, ValueError): + tail = output.splitlines()[-1] if output else f"exit code {code}" + raise WorkspaceError(f"the registry's tools/check.py in {checkout} could not run on the folder ({tail})") from None + if not isinstance(out, dict) or out.get("error"): + reason = out.get("error") if isinstance(out, dict) else "no answer" + raise WorkspaceError(f"the registry's tools/check.py in {checkout} could not run on the folder ({reason})") + return out, output diff --git a/backend/app/services/registry_check_worker.py b/backend/app/services/registry_check_worker.py new file mode 100644 index 0000000..189b387 --- /dev/null +++ b/backend/app/services/registry_check_worker.py @@ -0,0 +1,62 @@ +"""The child side of a registry check: loads a registry clone's tools/check.py and runs it on one folder. + +It runs in its own process, started by registry_check.run, and imports nothing from the engine. It writes one JSON +answer to the file it is given; whatever the script prints goes to this process's own output, which the engine keeps. +""" +from __future__ import annotations + +import importlib.util +import json +import sys +from pathlib import Path +from types import SimpleNamespace + +MODULE = "formext_registry_check" +USAGE = "usage: registry-check SCRIPT CHECKOUT FOLDER INDEX_URL ANSWER" + + +def _check(script: Path, checkout: Path, folder: Path, url: str) -> dict: + sys.path[:0] = [str(checkout / "tools"), str(checkout / "contract" / "tools")] + spec = importlib.util.spec_from_file_location(MODULE, script) + if spec is None or spec.loader is None: + return {"error": f"{script} cannot be imported"} + module = importlib.util.module_from_spec(spec) + sys.modules[spec.name] = module + spec.loader.exec_module(module) + probe = module.Result("published index") + published = module.published_index(url or None, probe) + blocked, _ = module.registry.load_blocklist() + result = module.check_extension(folder, SimpleNamespace(skip_npm=False), published, None, True, blocked) + return { + "name": str(result.name), + "passed": [str(p) for p in result.passed], + "errors": [str(e) for e in result.errors], + "notes": [str(n) for n in result.notes], + "probe_notes": [str(n) for n in probe.notes], + } + + +def _answer(script: Path, checkout: Path, folder: Path, url: str) -> dict: + try: + return _check(script, checkout, folder, url) + except SystemExit as e: + return {"error": f"it exited with {e.code!r}"} + except Exception as e: + return {"error": f"{type(e).__name__}: {e}"} + + +def main(argv: list[str] | None = None) -> int: + args = sys.argv[1:] if argv is None else argv + if len(args) != 5: + print(USAGE, file=sys.stderr) + return 2 + script, checkout, folder, url, answer = args + out = _answer(Path(script), Path(checkout), Path(folder), url) + sys.stdout.flush() + sys.stderr.flush() + Path(answer).write_text(json.dumps(out), encoding="utf-8") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/backend/formext_engine.py b/backend/formext_engine.py index 19fd506..e683110 100644 --- a/backend/formext_engine.py +++ b/backend/formext_engine.py @@ -62,6 +62,7 @@ def checks(contract) -> dict: "registry_pr_lock": registry_lock_serialises(Path(tmp) / ".lock"), "registry_pr_push_held": pull_requests_serialise(Path(tmp) / "registry"), "registry_pr_lock_gives_up": registry_lock_gives_up(Path(tmp) / "wait.lock"), + "registry_check_isolated": registry_check_isolated(Path(tmp) / "registry"), "window_key_writes": window_key_writes(), "window_key_bootstrap": window_key_bootstrap(), "seal_catches_edit": seal_catches_edit(), @@ -317,6 +318,40 @@ def file_lock_taken(lock_file) -> bool: return False +SELFCHECK_SCRIPT = """import os +class Result: + def __init__(self, name): + self.name, self.passed, self.errors, self.notes = name, [], [], [] +class registry: + @staticmethod + def load_blocklist(): + return set(), None +def published_index(url, probe): + return {} +def check_extension(folder, args, published, base, changed, blocked): + r = Result(folder.name) + r.passed.append(str(os.getpid())) + r.notes.append(os.environ.get("FORMEXT_SELFCHECK_PROBE", "absent")) + return r +""" + + +def registry_check_isolated(root) -> bool: + from app.services import registry_check + + script = root / "tools" / "check.py" + script.parent.mkdir(parents=True) + script.write_text(SELFCHECK_SCRIPT, encoding="utf-8") + os.environ["FORMEXT_SELFCHECK_PROBE"] = "present" + try: + out, _ = registry_check.run(script, root, root, "") + except Exception: + return False + finally: + os.environ.pop("FORMEXT_SELFCHECK_PROBE", None) + return out.get("passed") not in ([], [str(os.getpid())]) and out.get("notes") == ["absent"] and not out.get("errors") + + def watch_shell(data) -> None: from app.services import runtime, startup @@ -441,6 +476,8 @@ def main() -> int: return passthrough("app.cli", args[1:]) if args and args[0] == "mcp": return passthrough("app.mcp", args[1:]) + if args and args[0] == "registry-check": + return passthrough("app.services.registry_check_worker", args[1:]) try: return serve() except Exception: diff --git a/docs/MANUAL.md b/docs/MANUAL.md index fff697e..fe13f2f 100644 --- a/docs/MANUAL.md +++ b/docs/MANUAL.md @@ -196,7 +196,7 @@ Publish turns a build into what the catalogue needs. - **The index entry**: the package's row for formai.studio's extensions index (`formai-extensions`, format 1): id, name, product, version, description, permissions, the package address (by default `https://formai.studio/extensions/packages/-.formpkg`), SHA-256, size, and the signature when signed. It is checked against the contract's `extensions.schema.json` before anything is written. - **Prepare Submission** builds the package if needed, signs it with your publisher key (Settings chooses the default key), and writes a submission folder in the data folder (`submissions/-/`): the `.formpkg`, `entry.json`, a one-package `extensions.json` with your publisher entry, a `README.md` for the reviewer, and `submission.json`. Reveal opens the folder. - **Send to FormPortal** installs the package through FormPortal's command line (`formportal cli extension-install --path `) when it is found, otherwise opens the package with FormPortal or with the system's handler for `.formpkg`. FormPortal applies its own checks and signature policy, and its answer is shown. -- **Submit to Registry** is how an extension becomes official. It writes the project into a folder in form.ext-registry's layout, `submissions/registry/extensions//` in the data folder: `package/` (exactly what goes in the `.formpkg`), the source beside it (`src/`, `package.json` and its lock file when the project has them, `docs/`), and `README.md`, `LICENSE` and `CHANGELOG.md` (form.ext writes the ones the project lacks, for you to finish). The screenshot slot is `docs/screenshot.png`, shown in the README. Then it runs the registry's checks on the folder. There is no clone to set up: form.ext keeps its own copy of `nodemode-dev/form.ext-registry` (the `registry` host source, see [Host sources](#host-sources)), fetches it before each submit, and runs that copy's `tools/check.py`, exactly the checks CI runs on a pull request (contract, version and immutability against the published index, reproducible build, code bans, permissions declared and used, README, licence, changelog and screenshot, block list). If you set **Registry checkout** to your own clone of the registry (the setting `registry.checkout`), that clone is used instead. If the copy cannot be fetched, form.ext runs its own Check and the metadata checks, and says which ran. +- **Submit to Registry** is how an extension becomes official. It writes the project into a folder in form.ext-registry's layout, `submissions/registry/extensions//` in the data folder: `package/` (exactly what goes in the `.formpkg`), the source beside it (`src/`, `package.json` and its lock file when the project has them, `docs/`), and `README.md`, `LICENSE` and `CHANGELOG.md` (form.ext writes the ones the project lacks, for you to finish). The screenshot slot is `docs/screenshot.png`, shown in the README. Then it runs the registry's checks on the folder. There is no clone to set up: form.ext keeps its own copy of `nodemode-dev/form.ext-registry` (the `registry` host source, see [Host sources](#host-sources)), fetches it before each submit, and runs that copy's `tools/check.py`, exactly the checks CI runs on a pull request (contract, version and immutability against the published index, reproducible build, code bans, permissions declared and used, README, licence, changelog and screenshot, block list). If you set **Registry checkout** to your own clone of the registry (the setting `registry.checkout`), that clone is used instead. If the copy cannot be fetched, form.ext runs its own Check and the metadata checks, and says which ran. The registry's script runs as a separate program, never inside form.ext itself: it gets none of form.ext's environment variables (so no tokens or keys), a temporary home folder that is deleted afterwards (so it does not see your GitHub or npm sign-ins), and five minutes to finish. Everything it prints, and everything the programs it starts print, is shown in the report. If it takes longer, form.ext stops it and every program it started, and says so. The time limit, in seconds, can be changed with the environment variable `FORMEXT_REGISTRY_CHECK_TIMEOUT`. A new project's README already has a `## Permissions` section, one line per permission ending in the placeholder "Why: say here what the extension does with it.", and a `## Screenshot` section for `docs/screenshot.png`. Write the reasons, save the screenshot, and the project is ready. A missing LICENSE is written with the full text when the manifest's licence is Apache-2.0 or MIT. diff --git a/frontend/src/panes/run/HASHOUT_LOG.md b/frontend/src/panes/run/HASHOUT_LOG.md index 1d4a1c8..866e306 100644 --- a/frontend/src/panes/run/HASHOUT_LOG.md +++ b/frontend/src/panes/run/HASHOUT_LOG.md @@ -62,7 +62,7 @@ The answer's `method` is `cli`, `app` or `system`. The installed Tauri app answe - logged: v0.1.1 ยท 2026-11-07 - `POST /api/publish/{id}/registry` writes `submissions/registry/extensions//` (staged, then one rename) in form.ext-registry's layout: every package file under `package/` (whatever the project's `package_prefix`), every other project file at the same path (`src/`, `package.json`, `package-lock.json`, `docs/`, `README.md` and the rest) except `import.json`, `dist/` and `build/`, and `README.md`, `LICENSE`, `CHANGELOG.md` written from the manifest when the project has none (listed in `made`). The generated README has what the registry's check 6 needs: a description, the screenshot `![...](docs/screenshot.png)` and a `## Permissions` section naming each permission with a "Why:" for the author to finish; the generated LICENSE is an SPDX line and a note to put the full text in. The record (`.submission.json` beside `extensions/`) is `{project, id, version, folder, files, made, screenshot, screenshot_slot, checks, update, published_version, commands, prepared_at}`; `GET /api/publish/{id}` returns it as `registry.submission` with `registry.folder`, `registry.checkout` and `registry.repo`. -- The checks: when the setting `registry.checkout` names a folder with `tools/check.py`, that file is imported (`importlib`, registered in `sys.modules` so its dataclasses work; it puts its own `tools/` and the clone's `contract/tools` on `sys.path`) and its own functions run: `published_index` (form.ext's registry address when it is not the default, else the script's own default with its `gh` fallback), `registry.load_blocklist`, then `check_extension(folder, {skip_npm: False}, published, None, True, blocked)`. The folder is outside the clone's `extensions/`, which the script's `main` refuses, so `main` is not called; `changed` is true because a submission is a change, and no base commit is compared. The report is printed in `main`'s words. Without a checkout, `_own_checks` runs Check on `package/` (errors only), api and native, README, LICENSE, CHANGELOG and the screenshot, and the note says the registry's script did not run. Nothing of the registry is vendored. +- The checks: when the setting `registry.checkout` names a folder with `tools/check.py`, that file is loaded in a separate process (`services/registry_check.py`, see `backend/HASHOUT_LOG.md#loopback`; the worker registers it in `sys.modules` so its dataclasses work and puts its own `tools/` and the clone's `contract/tools` on `sys.path`) and its own functions run: `published_index` (form.ext's registry address when it is not the default, else the script's own default with its `gh` fallback), `registry.load_blocklist`, then `check_extension(folder, {skip_npm: False}, published, None, True, blocked)`. The folder is outside the clone's `extensions/`, which the script's `main` refuses, so `main` is not called; `changed` is true because a submission is a change, and no base commit is compared. The report is printed in `main`'s words. Without a checkout, `_own_checks` runs Check on `package/` (errors only), api and native, README, LICENSE, CHANGELOG and the screenshot, and the note says the registry's script did not run. Nothing of the registry is vendored. - `update` and `published_version` come from the Library's registry shelf when it can be read. `commands` are `[{say, run}]`: `gh repo fork --clone --remote`, a branch `add--` (or `update-`) from `upstream/main`, copy the folder in, `python3 tools/check.py extensions/`, commit (`feat(): ...`), push, `gh pr create --repo nodemode-dev/form.ext-registry`. Arguments are shell-quoted. By default form.ext runs none of them; on request, `POST /api/publish/{id}/registry/pull-request` runs the fork, branch, push and pull request itself (see the Publish pane's log, v0.4.0). - `POST /api/publish/{id}/registry/reveal` opens the folder. The CLI and MCP `submit {id, checkout?}` saves `checkout` as the setting first (it must hold `tools/check.py`). - Found while testing: a project with no `src/` (a starter, or a package imported from the registry) fails the registry's permission check, because the script then reads the shipped files and the bundled SDK (`ui/formext.js`) names every SDK method. A project that keeps its source in `src/` passes. diff --git a/tests/publish/test_registry_check_process.py b/tests/publish/test_registry_check_process.py new file mode 100644 index 0000000..16be10c --- /dev/null +++ b/tests/publish/test_registry_check_process.py @@ -0,0 +1,167 @@ +import os +import sys +import time +from pathlib import Path + +import pytest + +from .conftest import PNG, make_remote + +SHOT = {"docs/screenshot.png": {"base64": PNG}} +SCRIPT = """import os, subprocess, sys, time +from pathlib import Path + + +class Result: + def __init__(self, name): + self.name, self.passed, self.errors, self.notes = name, [], [], [] + + +class registry: + @staticmethod + def load_blocklist(): + return set(), None + + +def published_index(url, probe): + probe.notes.append("index read") + return {{}} + + +def check_extension(folder, args, published, base, changed, blocked): + r = Result("extensions/" + folder.name) + r.passed.append("ran") +{body} + return r +""" + + +def registry_with(remotes, body: str) -> None: + lines = "\n".join(" " + line for line in body.strip("\n").splitlines()) + make_remote(remotes, "form.ext-registry", {"tools/check.py": SCRIPT.format(body=lines)}) + + +def submit(client, pid): + return client.post(f"/api/publish/{pid}/registry") + + +def notes(out) -> dict: + found = {} + for line in out["checks"]["report"].splitlines(): + text = line.strip() + if text.startswith("note ") and "=" in text: + key, _, value = text[6:].partition("=") + found[key] = value + return found + + +def gone(pid: int) -> bool: + try: + os.kill(pid, 0) + except ProcessLookupError: + return True + except PermissionError: + return False + return False + + +def test_the_registry_check_runs_in_a_process_of_its_own_and_its_result_is_reported(client, make_project, remotes): + registry_with(remotes, 'r.notes.append(f"pid={os.getpid()}")') + p = make_project(files=SHOT) + res = submit(client, p["id"]) + assert res.status_code == 200, res.text + out = res.json() + assert out["checks"]["by"] == "registry" + assert out["checks"]["ok"] is True + assert "ok ran" in out["checks"]["report"] + assert "note: index read" in out["checks"]["report"] + assert int(notes(out)["pid"]) != os.getpid() + assert "process of its own" in out["checks"]["note"] + + +def test_the_registry_check_gets_none_of_the_engines_secrets_and_a_scratch_home(client, make_project, remotes, monkeypatch): + monkeypatch.setenv("FORMEXT_EXAMPLE_API_KEY", "value-only-the-engine-has") + monkeypatch.setenv("GH_TOKEN", "value-only-the-engine-has") + registry_with(remotes, """ +r.notes.append("names=" + ",".join(sorted(os.environ))) +r.notes.append("home=" + os.environ.get("HOME", "")) +if "value-only-the-engine-has" in os.environ.values(): + r.errors.append("an engine secret reached the check") +""") + p = make_project(files=SHOT) + res = submit(client, p["id"]) + assert res.status_code == 200, res.text + out = res.json() + assert out["checks"]["ok"] is True, out["checks"]["report"] + seen = notes(out) + names = set(seen["names"].split(",")) + assert "FORMEXT_EXAMPLE_API_KEY" not in names and "GH_TOKEN" not in names + assert "value-only-the-engine-has" not in out["checks"]["report"] + assert seen["home"] and seen["home"] != os.environ["HOME"] + assert not Path(seen["home"]).exists() + + +def test_a_registry_check_cannot_change_the_engines_own_environment(client, make_project, remotes): + registry_with(remotes, """ +os.environ["FORMEXT_SET_BY_A_CHECK"] = "1" +sys.modules["json"] = None +""") + p = make_project(files=SHOT) + try: + res = submit(client, p["id"]) + assert "FORMEXT_SET_BY_A_CHECK" not in os.environ + assert sys.modules.get("json") is not None + finally: + os.environ.pop("FORMEXT_SET_BY_A_CHECK", None) + if sys.modules.get("json") is None: + sys.modules.pop("json", None) + assert res.status_code == 200, res.text + assert client.get(f"/api/publish/{p['id']}").status_code == 200 + + +def test_what_the_check_and_the_programs_it_starts_print_is_kept_in_the_report(client, make_project, remotes): + registry_with(remotes, """ +print("said on standard output") +print("said on standard error", file=sys.stderr) +subprocess.run([sys.executable, "-c", "print('said by a program the check started')"], check=True) +""") + p = make_project(files=SHOT) + res = submit(client, p["id"]) + assert res.status_code == 200, res.text + report = res.json()["checks"]["report"] + assert "said on standard output" in report + assert "said on standard error" in report + assert "said by a program the check started" in report + + +@pytest.mark.skipif(os.name == "nt", reason="the stopped programs are looked up with os.kill(pid, 0), which ends a program on Windows") +def test_a_registry_check_over_its_time_limit_is_stopped_with_the_programs_it_started(client, make_project, remotes, monkeypatch): + monkeypatch.setenv("FORMEXT_REGISTRY_CHECK_TIMEOUT", "1") + registry_with(remotes, """ +child = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(60)"]) +(folder.parent / (folder.name + ".pids")).write_text(f"{os.getpid()} {child.pid}") +time.sleep(20) +""") + p = make_project(files=SHOT) + started = time.monotonic() + res = submit(client, p["id"]) + took = time.monotonic() - started + assert res.status_code == 400, res.text + assert "did not finish within 1 second, so it was stopped" in res.json()["detail"] + assert took < 15 + folder = Path(client.get(f"/api/publish/{p['id']}").json()["registry"]["folder"]) + pids = [int(n) for n in (folder.parent / (folder.name + ".pids")).read_text().split()] + deadline = time.monotonic() + 5 + while not all(gone(n) for n in pids) and time.monotonic() < deadline: + time.sleep(0.1) + assert all(gone(n) for n in pids) + + +def test_a_registry_check_missing_a_function_it_needs_is_refused_with_a_sentence(client, make_project, remotes): + make_remote(remotes, "form.ext-registry", {"tools/check.py": "def published_index(url, probe):\n return {}\n"}) + p = make_project(files=SHOT) + res = submit(client, p["id"]) + assert res.status_code == 400 + detail = res.json()["detail"] + assert "could not run on the folder" in detail + assert "AttributeError" in detail or "Result" in detail From fa6f77c1a8f435243b8714b0437d95290e36e15e Mon Sep 17 00:00:00 2001 From: gbarnai Date: Sun, 29 Nov 2026 15:12:04 -0500 Subject: [PATCH 2/2] fix: keep the registry check answering on Windows when taskkill cannot run taskkill now runs only while the check is still running, and a taskkill that cannot start or does not return no longer turns a finished or timed out check into an engine error. The manual names the few environment settings the check is given. --- backend/HASHOUT_LOG.md | 1 + backend/app/services/registry_check.py | 8 +++++-- docs/MANUAL.md | 2 +- tests/publish/test_registry_check_process.py | 25 ++++++++++++++++++++ 4 files changed, 33 insertions(+), 3 deletions(-) diff --git a/backend/HASHOUT_LOG.md b/backend/HASHOUT_LOG.md index 0a4d768..3dc54a2 100644 --- a/backend/HASHOUT_LOG.md +++ b/backend/HASHOUT_LOG.md @@ -11,6 +11,7 @@ The living log of the form.ext engine. Read it before editing `backend/`. Core f - `agent_lookup.py` stays the shared 1.0.1 copy. `agent_start.start_argv` wraps it: on Windows an npm `.cmd` launcher is followed to its script (with the `node.exe` beside it or `node` on PATH) or its `.exe`; any other `.cmd` or `.bat` goes through `cmd.exe /c` only when every word is plain. On Windows the MCP launcher is `formext.bat`. - The consent `what` shows the resolved path, keeps a trailing separator, and writes control, format and line separator characters as `\uXXXX`. `package` writes its temporary file with `tempfile.mkstemp`. `POST /api/window/key` checks Origin and Host with `origin_ok`. Words given to `cmd.exe /c` may not hold any of `& | < > ^ ( ) !` even inside spaces, since `cmd /c` can strip the outer quotes. The refusal (`agent_start.RefusedWord`) says to pass long or special text through stdin or a file when the program accepts one. - `publish._run_registry_check` no longer imports the registry's `tools/check.py`. `services/registry_check.py` starts `services/registry_check_worker.py` (`python -I`, or `formext-engine registry-check` when frozen) with the checkout as working folder and an environment made only of `PASSED_VARS` (PATH, locale, temp and the Windows system variables) plus a scratch `HOME`, `USERPROFILE`, `APPDATA`, `XDG_*` and npm cache in a temporary folder removed afterwards. The worker calls the same functions as before and writes its answer to a file; standard output and error go to a second file, so programs the script starts are kept too (last `OUTPUT_LIMIT` bytes). The child gets its own session (a new process group on Windows); past `FORMEXT_REGISTRY_CHECK_TIMEOUT` (default 300 s) the group is killed (`taskkill /T` on Windows) and the submit answers 400 with a sentence. This supersedes the in-process owner decision in `#pr-lock`, and with it the shared `redirect_stdout` race. The self check adds `registry_check_isolated`: a stand-in script must answer from another process id and must not see a variable set in the engine. +- On Windows `taskkill /T` runs only while the worker is still running, and a `taskkill` that cannot start or does not return is passed over: the worker is then killed on its own, and the submit still answers with the check's result or the time limit sentence. - Not run: the frozen engine's `registry-check` entry and the Windows paths (process group, `taskkill`). ## v0.11.0: one runner for the tests, by layer {#test-runner} diff --git a/backend/app/services/registry_check.py b/backend/app/services/registry_check.py index b11023e..1637784 100644 --- a/backend/app/services/registry_check.py +++ b/backend/app/services/registry_check.py @@ -58,8 +58,12 @@ def command(script: Path, checkout: Path, folder: Path, url: str, answer: Path) def _stop(proc: subprocess.Popen) -> None: if WINDOWS: - subprocess.run(["taskkill", "/PID", str(proc.pid), "/T", "/F"], stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, - stderr=subprocess.DEVNULL, creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0), timeout=STOP_WAIT * 2, check=False) + if proc.poll() is None: + try: + subprocess.run(["taskkill", "/PID", str(proc.pid), "/T", "/F"], stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0), timeout=STOP_WAIT * 2, check=False) + except (OSError, subprocess.SubprocessError): + pass else: try: os.killpg(proc.pid, signal.SIGKILL) diff --git a/docs/MANUAL.md b/docs/MANUAL.md index fe13f2f..25c1191 100644 --- a/docs/MANUAL.md +++ b/docs/MANUAL.md @@ -196,7 +196,7 @@ Publish turns a build into what the catalogue needs. - **The index entry**: the package's row for formai.studio's extensions index (`formai-extensions`, format 1): id, name, product, version, description, permissions, the package address (by default `https://formai.studio/extensions/packages/-.formpkg`), SHA-256, size, and the signature when signed. It is checked against the contract's `extensions.schema.json` before anything is written. - **Prepare Submission** builds the package if needed, signs it with your publisher key (Settings chooses the default key), and writes a submission folder in the data folder (`submissions/-/`): the `.formpkg`, `entry.json`, a one-package `extensions.json` with your publisher entry, a `README.md` for the reviewer, and `submission.json`. Reveal opens the folder. - **Send to FormPortal** installs the package through FormPortal's command line (`formportal cli extension-install --path `) when it is found, otherwise opens the package with FormPortal or with the system's handler for `.formpkg`. FormPortal applies its own checks and signature policy, and its answer is shown. -- **Submit to Registry** is how an extension becomes official. It writes the project into a folder in form.ext-registry's layout, `submissions/registry/extensions//` in the data folder: `package/` (exactly what goes in the `.formpkg`), the source beside it (`src/`, `package.json` and its lock file when the project has them, `docs/`), and `README.md`, `LICENSE` and `CHANGELOG.md` (form.ext writes the ones the project lacks, for you to finish). The screenshot slot is `docs/screenshot.png`, shown in the README. Then it runs the registry's checks on the folder. There is no clone to set up: form.ext keeps its own copy of `nodemode-dev/form.ext-registry` (the `registry` host source, see [Host sources](#host-sources)), fetches it before each submit, and runs that copy's `tools/check.py`, exactly the checks CI runs on a pull request (contract, version and immutability against the published index, reproducible build, code bans, permissions declared and used, README, licence, changelog and screenshot, block list). If you set **Registry checkout** to your own clone of the registry (the setting `registry.checkout`), that clone is used instead. If the copy cannot be fetched, form.ext runs its own Check and the metadata checks, and says which ran. The registry's script runs as a separate program, never inside form.ext itself: it gets none of form.ext's environment variables (so no tokens or keys), a temporary home folder that is deleted afterwards (so it does not see your GitHub or npm sign-ins), and five minutes to finish. Everything it prints, and everything the programs it starts print, is shown in the report. If it takes longer, form.ext stops it and every program it started, and says so. The time limit, in seconds, can be changed with the environment variable `FORMEXT_REGISTRY_CHECK_TIMEOUT`. +- **Submit to Registry** is how an extension becomes official. It writes the project into a folder in form.ext-registry's layout, `submissions/registry/extensions//` in the data folder: `package/` (exactly what goes in the `.formpkg`), the source beside it (`src/`, `package.json` and its lock file when the project has them, `docs/`), and `README.md`, `LICENSE` and `CHANGELOG.md` (form.ext writes the ones the project lacks, for you to finish). The screenshot slot is `docs/screenshot.png`, shown in the README. Then it runs the registry's checks on the folder. There is no clone to set up: form.ext keeps its own copy of `nodemode-dev/form.ext-registry` (the `registry` host source, see [Host sources](#host-sources)), fetches it before each submit, and runs that copy's `tools/check.py`, exactly the checks CI runs on a pull request (contract, version and immutability against the published index, reproducible build, code bans, permissions declared and used, README, licence, changelog and screenshot, block list). If you set **Registry checkout** to your own clone of the registry (the setting `registry.checkout`), that clone is used instead. If the copy cannot be fetched, form.ext runs its own Check and the metadata checks, and says which ran. The registry's script runs as a separate program, never inside form.ext itself: it gets only the program search path, the language, time zone and temporary folder settings and, on Windows, the system folder settings, and none of form.ext's other environment variables (so no tokens, keys or proxy settings), a temporary home folder that is deleted afterwards (so it does not see your GitHub or npm sign-ins), and five minutes to finish. Everything it prints, and everything the programs it starts print, is shown in the report. If it takes longer, form.ext stops it and every program it started, and says so. The time limit, in seconds, can be changed with the environment variable `FORMEXT_REGISTRY_CHECK_TIMEOUT`. A new project's README already has a `## Permissions` section, one line per permission ending in the placeholder "Why: say here what the extension does with it.", and a `## Screenshot` section for `docs/screenshot.png`. Write the reasons, save the screenshot, and the project is ready. A missing LICENSE is written with the full text when the manifest's licence is Apache-2.0 or MIT. diff --git a/tests/publish/test_registry_check_process.py b/tests/publish/test_registry_check_process.py index 16be10c..599a4cb 100644 --- a/tests/publish/test_registry_check_process.py +++ b/tests/publish/test_registry_check_process.py @@ -157,6 +157,31 @@ def test_a_registry_check_over_its_time_limit_is_stopped_with_the_programs_it_st assert all(gone(n) for n in pids) +def test_on_windows_a_finished_registry_check_answers_even_where_taskkill_cannot_run(client, make_project, remotes, monkeypatch): + from app.services import registry_check + + monkeypatch.setattr(registry_check, "WINDOWS", True) + registry_with(remotes, 'r.notes.append("finished=yes")') + p = make_project(files=SHOT) + res = submit(client, p["id"]) + assert res.status_code == 200, res.text + assert notes(res.json())["finished"] == "yes" + + +def test_on_windows_a_registry_check_over_its_time_limit_is_still_stopped_where_taskkill_cannot_run(client, make_project, remotes, monkeypatch): + from app.services import registry_check + + monkeypatch.setattr(registry_check, "WINDOWS", True) + monkeypatch.setenv("FORMEXT_REGISTRY_CHECK_TIMEOUT", "1") + registry_with(remotes, "time.sleep(20)") + p = make_project(files=SHOT) + started = time.monotonic() + res = submit(client, p["id"]) + assert time.monotonic() - started < 15 + assert res.status_code == 400, res.text + assert "did not finish within 1 second, so it was stopped" in res.json()["detail"] + + def test_a_registry_check_missing_a_function_it_needs_is_refused_with_a_sentence(client, make_project, remotes): make_remote(remotes, "form.ext-registry", {"tools/check.py": "def published_index(url, probe):\n return {}\n"}) p = make_project(files=SHOT)