Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions backend/HASHOUT_LOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,15 @@ 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.
- 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}

Expand Down
41 changes: 8 additions & 33 deletions backend/app/services/publish.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand Down
130 changes: 130 additions & 0 deletions backend/app/services/registry_check.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
"""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:
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)
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
62 changes: 62 additions & 0 deletions backend/app/services/registry_check_worker.py
Original file line number Diff line number Diff line change
@@ -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())
37 changes: 37 additions & 0 deletions backend/formext_engine.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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:
Expand Down
Loading
Loading