diff --git a/backend/HASHOUT_LOG.md b/backend/HASHOUT_LOG.md index 24b53dc..f9d02a9 100644 --- a/backend/HASHOUT_LOG.md +++ b/backend/HASHOUT_LOG.md @@ -8,6 +8,7 @@ ## Contents +- [Unreleased · Google sign-in return, Windows shims, one service per data folder, panel turn tools, model import size](#unreleased--google-sign-in-return-windows-shims-one-service-per-data-folder-panel-turn-tools-model-import-size) - [Unreleased · The window key, and the agent access fixes](#unreleased--the-window-key-and-the-agent-access-fixes) - [Unreleased · agents sync copies the skills to .agents/skills](#unreleased--agents-sync-copies-the-skills-to-agentsskills) - [Unreleased · agents/manifest.json says what the app offers agents](#unreleased--agentsmanifestjson-says-what-the-app-offers-agents) @@ -62,6 +63,22 @@ - [v0.1.0 · Local board service and SDK MCP](#v010--local-board-service-and-sdk-mcp) - [boot_backend.bat](#boot_backendbat) +## Unreleased · Google sign-in return, Windows shims, one service per data folder, panel turn tools, model import size + +- refers-to: `app/main.py` :: SIGN_IN_RETURNS, MODEL_IMPORT, local_access, lifespan; `app/routers/cloud.py` :: google_callback; `app/agent/agent_lookup.py` (the family's file, now 1.1.0) :: start_argv, _shim_target, _cmd_safe; `app/agent_manifest.py` :: LOOKUP_HASHES; `app/core/startup.py` :: hold, let_go; `app/agent/service.py` :: _agent_folder, Agents.allows, confirm, _cli; `app/core/config.py` :: max_model_bytes; `app/routers/boards.py` :: read_upload, models_import + +The Google return. Google sends the browser back to `GET /api/cloud/google/callback` as a cross-site navigation with no Origin, which the no-Origin cross-site refusal blocked. That one read is let through; it does nothing without the single-use sign-in state. The page escapes the message it shows. + +Windows shims. A panel turn passes the message, with line breaks and quotes, as one argument, and the command interpreter cannot carry that through a `.cmd`. The finder reads an npm shim and starts what it wraps directly with an argv list: its node script with the node beside it or on PATH, or the `.exe` it names, so no interpreter is involved. Any other `.cmd` or `.bat` still goes through `cmd.exe /c`, which reads `& | < > ^ ( ) ! %` and `"` even inside quotes, so every word, the program's own path included, must hold none of them and no control character, with or without a space. A name ending in dots or spaces after `.cmd` or `.bat` counts as one. Anything else is refused with a sentence that points at the `.exe`, the node script, or standard input or a file for long text. The finder moved to 1.1.0 and its hash is recorded; the other family copies need the same version. + +One service per data folder. Only the frozen engine took `engine.lock`, so a service the MCP server, `./formref serve` or `./formref dev` started let the desktop engine run beside it over the same folder. The service now takes the lock in its lifespan, unless its own process already holds it (the frozen engine), with its parent as the shell, refuses to start while another holds it, and removes the lock when it stops. + +Panel turn tools. Codex and Cursor panel turns ran in the app folder and depended on the checkout's MCP files at a fixed port. They now run in the `AgentTabs` folder that program tabs use, whose files point at the running service and send the turn's token from `FORMREF_AGENT_TOKEN`. With a token of their own, the rule that let any tokenless caller act as the running Codex or Cursor turn is gone. + +Model import size. The person cutout and sharp cutout files are near 180 MB. Model imports have their own 256 MiB limit, in the request check and in `read_upload`, and are still checked against the pinned hash. + +Run: the suite with the release board engine; the new tests fail on the previous code. + ## Unreleased · The window key, and the agent access fixes - refers-to: `app/core/window_key.py` (new) :: WindowKeyGuard, OPEN, BRIDGE, claim, ticket, spend; `app/core/seal.py` (new) :: effective, sign; `app/routers/window.py` (new); `app/main.py` :: app.add_middleware; `app/routers/terminal.py` :: _window_only, chat_events, attach; `app/routers/agent.py` :: save_agent_settings; `app/routers/commands.py` :: _window_only; `app/routers/cloud.py` :: from_agent; `app/routers/clip.py` :: get_token, reset_token; `app/agent/service.py` :: loopback_url, Agents.settings, save, allows, tokenless_turn, token_file, revoke, _cli; `app/agent/claude_code.py` :: issue, revoke, argv; `app/agent/chat.py` :: _run; `app/agent/runners.py` :: argv; `app/agent/terminal.py` :: Session.on_close, base_env; `app/cli.py` :: call; `formref_engine.py` :: main; `freeze_engine`; `requirements.txt`, `requirements_macos.txt` diff --git a/backend/app/agent/agent_lookup.py b/backend/app/agent/agent_lookup.py index ea34eba..3f56dad 100644 --- a/backend/app/agent/agent_lookup.py +++ b/backend/app/agent/agent_lookup.py @@ -26,7 +26,7 @@ from dataclasses import dataclass, field from pathlib import Path -VERSION = "1.0.1" +VERSION = "1.1.0" PROGRAMS: dict = { "claude": {"title": "Claude Code", "names": ("claude",), "setting": "claudeBin", "install": "curl -fsSL https://claude.ai/install.sh | bash", "install_windows": "irm https://claude.ai/install.ps1 | iex", @@ -359,13 +359,59 @@ def _quote(word: str, fish: bool) -> str: return "'" + word.replace("'", "'\"'\"'") + "'" +SHIM_TARGET = re.compile(r'"%~?dp0%?\\([^"%]+\.(?:js|cjs|mjs|exe))"\s+%\*', re.IGNORECASE) +CMD_REFUSED = re.compile(r'[\x00-\x1f\x7f&|<>^()!%"]') + + +def _shim_target(shim: str, env: dict) -> list[str] | None: + """The program an npm-style .cmd shim wraps, as an argv prefix: the .exe itself, or node and the script.""" + try: + text = Path(shim).read_text(encoding="utf-8", errors="replace") + except OSError: + return None + match = SHIM_TARGET.search(text) + if not match: + return None + folder = Path(shim).parent + target = folder.joinpath(*match.group(1).replace("/", "\\").split("\\")) + if not target.is_file(): + return None + if target.suffix.lower() == ".exe": + return [str(target)] + beside = folder / "node.exe" + node = str(beside) if beside.is_file() else shutil.which("node", path=env.get("PATH")) + return [node, str(target)] if node else None + + +def _batch(program: str) -> bool: + return program.rstrip(" .").lower().endswith((".cmd", ".bat")) + + +def _cmd_safe(words: list[str]) -> None: + """The command interpreter reads & | < > ^ ( ) ! % and " even inside quotes, and a .cmd re-reads its arguments, so + every word given to it, the program's own path included, must hold none of them and no control character.""" + for word in words: + if CMD_REFUSED.search(word): + raise ValueError("This text cannot be passed to a .cmd or .bat program on Windows: it holds a line break, a " + "control character or one of & | < > ^ ( ) ! % \". Point FormRef at the program's .exe or node " + "script instead, or pass long text through standard input or a file if the program supports it.") + + def start_argv(cmd: list, env: dict | None = None, platform: str | None = None) -> list[str]: """How a program is started, the same for a tab, Chat and a check: through the person's login shell on macOS and Linux - (exec, so the process is the program), directly on Windows with the command interpreter in front of a .cmd or .bat.""" + (exec, so the process is the program), directly on Windows. A .cmd or .bat that only starts a node script is replaced + by node and that script, and one that only starts an .exe by that .exe, each with the words as an argv list; any other + runs under the command interpreter, and only when no word holds a character the interpreter would read.""" words = [str(c) for c in cmd] env = os.environ if env is None else env if windows(platform): - return [env.get("COMSPEC") or "cmd.exe", "/c", *words] if words[0].lower().endswith((".cmd", ".bat")) else words + if not _batch(words[0]): + return words + target = _shim_target(words[0], env) + if target: + return [*target, *words[1:]] + _cmd_safe(words) + return [env.get("COMSPEC") or "cmd.exe", "/c", *words] shell = login_shell(env, platform) fish = Path(shell).name == "fish" return [shell, "-l", "-c", "exec " + " ".join(_quote(w, fish) for w in words)] diff --git a/backend/app/agent/service.py b/backend/app/agent/service.py index 19e5c96..13fbc98 100644 --- a/backend/app/agent/service.py +++ b/backend/app/agent/service.py @@ -22,7 +22,6 @@ BULK = 10 CONFIRM_SECONDS = 300 MOVES = {"transform": "Move or resize", "pack": "Pack", "sort": "Sort and lay out", "distribute": "Distribute", "align": "Align", "snap": "Snap", "normalize": "Resize"} -TOKENLESS = ("codex", "cursor") TOKEN_FOLDER = "AgentTokens" ASKED = tuple((method, re.compile(pattern), words) for method, pattern, words in ( ("POST", r"/api/boards", "create a board"), @@ -63,6 +62,12 @@ def loopback_url(value) -> bool: return False +def _agent_folder() -> Path: + from .programs import workdir + + return workdir() + + class Agents: def __init__(self): self.tokens: set[str] = set() @@ -145,8 +150,6 @@ def save(self, patch: dict) -> dict: def allows(self, client: str) -> bool: if client in self.tokens: return True - if client == "outside" and self.tokenless_turn() is not None: - return True return bool(self.settings()["outside_agents"]) def refuse(self, agent: str | None, method: str, path: str) -> None: @@ -154,9 +157,6 @@ def refuse(self, agent: str | None, method: str, path: str) -> None: self.refusal = {"id": uuid.uuid4().hex, "agent": name, "what": asked(method, path), "answers": list(ANSWERS), "always": "all", "expires": None, "held": False} self.refusals += 1 - def tokenless_turn(self) -> str | None: - return next((t for t in reversed(self.cli_active) if self.turns.get(t, {}).get("runner") in TOKENLESS), None) - async def available(self) -> list[dict]: rows = [] for key, spec in runners.CLI.items(): @@ -234,7 +234,7 @@ def _risky(self, command, items: dict) -> str | None: async def confirm(self, client: str, summary: str) -> bool: """Hold a risky write from a panel turn until the person answers in the Agent panel.""" - turn_id = self.token_turn.get(client) or (self.tokenless_turn() if client == "outside" else None) + turn_id = self.token_turn.get(client) queue = self.queues.get(turn_id or "") if queue is None or turn_id in self.approved or not self.settings()["confirm_changes"]: return True @@ -311,11 +311,12 @@ async def _cli(self, turn_id, runner, prompt, token, config): base = {k: v for k, v in os.environ.items() if k != "FORMREF_WINDOW_KEY_STDOUT"} env = agent_lookup.child_env(binary, base=base, extra={"FORMREF_API_URL": API_URL, "FORMREF_AGENT_TOKEN": token}, shell_timeout=10.0) mcp_file = self.token_file(token, {"mcpServers": {"formref": runners.mcp_server(token, API_URL)}}) if runner == "claude" else "" + folder = ROOT if runner == "claude" else await asyncio.to_thread(_agent_folder) self.cli_turns += 1 self.cli_active.append(turn_id) try: - process = await asyncio.create_subprocess_exec(*agent_lookup.start_argv(runners.argv(runner, binary, prompt, token, API_URL, config["model"], mcp_file)), - cwd=str(ROOT), env=env, stdin=asyncio.subprocess.DEVNULL, + process = await asyncio.create_subprocess_exec(*agent_lookup.start_argv(runners.argv(runner, binary, prompt, token, API_URL, config["model"], mcp_file), env), + cwd=str(folder), env=env, stdin=asyncio.subprocess.DEVNULL, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, limit=8 * 1024 * 1024) self.processes[turn_id] = process async for raw in process.stdout: diff --git a/backend/app/agent_manifest.py b/backend/app/agent_manifest.py index 640dd69..414c049 100644 --- a/backend/app/agent_manifest.py +++ b/backend/app/agent_manifest.py @@ -18,6 +18,7 @@ LOOKUP_HASHES = { "1.0.0": "252ea9bb9419d4990f174f91914f09800497bc69e98f849f5643bbf4217cc3f3", "1.0.1": "62667f9b68b7d101e1896ce617240424e33b7e498c560bc79d45f0ab26c77d51", + "1.1.0": "a1ac03220d5e73c27f7a38e5e6b6dea53d0c45ab1e3a03869ac2e69fdb9af207", } diff --git a/backend/app/core/config.py b/backend/app/core/config.py index 4360058..855d98d 100644 --- a/backend/app/core/config.py +++ b/backend/app/core/config.py @@ -12,6 +12,7 @@ class Settings: engine_path: Path max_upload_bytes: int = 64 * 1024 * 1024 max_archive_bytes: int = 256 * 1024 * 1024 + max_model_bytes: int = 256 * 1024 * 1024 max_image_pixels: int = 64_000_000 max_export_pixels: int = 32_000_000 max_export_edge: int = 8192 diff --git a/backend/app/core/startup.py b/backend/app/core/startup.py index 3e2cac6..4b51eea 100644 --- a/backend/app/core/startup.py +++ b/backend/app/core/startup.py @@ -284,6 +284,23 @@ def claim(data: Path, shell: int) -> tuple[Path, int]: return path, held if state == LEFTOVER else 0 +def hold(data: Path) -> bool: + if number(read_lock(data / LOCK_NAME).get("pid")) == os.getpid(): + return False + data.mkdir(parents=True, exist_ok=True) + claim(data, shell_pid() or os.getppid()) + return True + + +def let_go(data: Path) -> None: + path = data / LOCK_NAME + if number(read_lock(path).get("pid")) == os.getpid(): + try: + path.unlink() + except OSError: + pass + + def shell_pid() -> int: raw = os.environ.get(SHELL_ENV, "").strip() return int(raw) if raw.isascii() and raw.isdigit() else 0 diff --git a/backend/app/main.py b/backend/app/main.py index 3a8eddd..2bb996a 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -3,11 +3,12 @@ import ipaddress import logging import mimetypes +import re from urllib.parse import urlparse from fastapi import FastAPI, Request from fastapi.responses import JSONResponse, FileResponse from starlette.middleware.cors import CORSMiddleware -from .core import engine_log, origins +from .core import engine_log, origins, startup from .core.window_key import WindowKeyGuard from .core.config import ROOT, VERSION, settings from .core.engine import broker, EngineError @@ -41,16 +42,28 @@ @asynccontextmanager async def lifespan(app): engine_log.join() + try: + held = startup.hold(settings.data_dir) + except startup.Busy as err: + log.error("%s", err) + raise log.info("FormRef %s using %s", VERSION, settings.data_dir) - terminal.start(asyncio.get_running_loop()) - async with mcp_server.session_manager.run(): - yield - terminal.close_all() - broker.close() + try: + terminal.start(asyncio.get_running_loop()) + async with mcp_server.session_manager.run(): + yield + terminal.close_all() + broker.close() + finally: + if held: + startup.let_go(settings.data_dir) app = FastAPI(title="FormRef", version=VERSION, lifespan=lifespan) app.add_middleware(CORSMiddleware, allow_origin_regex=r"^(https?://(localhost|127\.0\.0\.1|\[::1\])(?::\d+)?|(chrome|moz)-extension://[a-z0-9-]+)$", allow_credentials=False, allow_methods=["GET", "POST", "DELETE", "OPTIONS"], allow_headers=["Content-Type", "X-FormRef-Clip-Token"], expose_headers=["Content-Disposition", "X-FormRef-Scale", "X-FormRef-Width", "X-FormRef-Height"]) +SIGN_IN_RETURNS = {("GET", "/api/cloud/google/callback")} +MODEL_IMPORT = re.compile(r"/api/models/[^/]+/import") + @app.middleware("http") async def local_access(request: Request, call_next): host = urlparse("http://" + request.headers.get("host", "")).hostname @@ -64,15 +77,16 @@ async def local_access(request: Request, call_next): if not local: return JSONResponse(status_code=403, content={"detail": "FormRef accepts local clients only."}) origin = request.headers.get("origin") - if not origin and request.headers.get("sec-fetch-site", "").strip().lower() == "cross-site": + if not origin and request.headers.get("sec-fetch-site", "").strip().lower() == "cross-site" and (request.method, request.url.path) not in SIGN_IN_RETURNS: return JSONResponse(status_code=403, content={"detail": "Origin is not an allowed local application."}) if origin and not origins.allowed(origin, request.headers.get("host", ""), request.url.path): return JSONResponse(status_code=403, content={"detail": "Origin is not an allowed local application."}) length = request.headers.get("content-length") if length: + limit = settings.max_model_bytes if request.method == "POST" and MODEL_IMPORT.fullmatch(request.url.path) else settings.max_upload_bytes try: - if int(length) > settings.max_upload_bytes + 1024 * 1024: - return JSONResponse(status_code=413, content={"detail": "Request exceeds the 64 MiB upload limit."}) + if int(length) > limit + 1024 * 1024: + return JSONResponse(status_code=413, content={"detail": f"Request exceeds the {limit // (1024 * 1024)} MiB upload limit."}) except ValueError: return JSONResponse(status_code=400, content={"detail": "Invalid request content length."}) client = request.headers.get("x-formref-client") diff --git a/backend/app/routers/boards.py b/backend/app/routers/boards.py index ec80f98..a586178 100644 --- a/backend/app/routers/boards.py +++ b/backend/app/routers/boards.py @@ -27,7 +27,8 @@ router = APIRouter(prefix="/api") -async def read_upload(file: UploadFile): +async def read_upload(file: UploadFile, limit: int = 0): + limit = limit or settings.max_upload_bytes chunks = [] size = 0 while True: @@ -35,9 +36,9 @@ async def read_upload(file: UploadFile): if not chunk: break size += len(chunk) - if size > settings.max_upload_bytes: + if size > limit: await file.close() - raise HTTPException(status_code=413, detail="Uploads are limited to 64 MiB.") + raise HTTPException(status_code=413, detail=f"Uploads are limited to {limit // (1024 * 1024)} MiB.") chunks.append(chunk) await file.close() return b"".join(chunks) @@ -227,7 +228,7 @@ def models_download(model: str): @router.post("/models/{model}/import") async def models_import(model: str, file: UploadFile = File(...)): - data = await read_upload(file) + data = await read_upload(file, settings.max_model_bytes) return await asyncio.to_thread(cutout_models.import_file, model, file.filename or "", data) @router.delete("/models/{model}") diff --git a/backend/app/routers/cloud.py b/backend/app/routers/cloud.py index 9197def..659a029 100644 --- a/backend/app/routers/cloud.py +++ b/backend/app/routers/cloud.py @@ -1,4 +1,5 @@ import asyncio +import html import re import uuid @@ -44,7 +45,7 @@ def start(name: str, request: Request): @router.get("/google/callback", response_class=HTMLResponse) def google_callback(state: str = "", code: str = "", error: str = ""): status, message = cloud.google_callback(state, code, error) - page = f"FormRef

{message}

" + page = f"FormRef

{html.escape(message)}

" return HTMLResponse(page, status_code=status) diff --git a/backend/tests/test_agent_guards.py b/backend/tests/test_agent_guards.py index 7fa1621..c0fcbd7 100644 --- a/backend/tests/test_agent_guards.py +++ b/backend/tests/test_agent_guards.py @@ -127,3 +127,13 @@ def test_a_plain_terminal_does_not_inherit_the_key_variable(monkeypatch): env = terminal.base_env() assert "FORMREF_WINDOW_KEY_STDOUT" not in env assert not any(re.search(r"window.?key", k, re.I) for k in env) + + +@pytest.mark.parametrize("runner", ["codex", "cursor"]) +def test_a_running_codex_or_cursor_turn_does_not_let_in_an_outside_caller(bare, reset_agents, runner): + reset_agents.cli_turns = 1 + reset_agents.cli_active.append("t2") + reset_agents.turns["t2"] = {"runner": runner} + assert reset_agents.allows("outside") is False + r = bare.post("/api/boards", json={"title": "x"}, headers={"x-formref-client": "outside"}) + assert r.status_code == 403 and r.json()["code"] == "outside_agents_off" diff --git a/backend/tests/test_agent_programs.py b/backend/tests/test_agent_programs.py index e01c32b..1a28e6e 100644 --- a/backend/tests/test_agent_programs.py +++ b/backend/tests/test_agent_programs.py @@ -1,4 +1,5 @@ import json +import re import os import stat from pathlib import Path @@ -234,3 +235,21 @@ def test_a_missing_program_or_an_unknown_kind_is_refused(client, nothing_install def test_starting_a_program_tab_needs_the_window_key(bare, stand_ins): r = bare.post("/api/terminal/agent", json={"kind": "codex"}) assert r.status_code == 403 and r.json() == REFUSED + + +@pytest.mark.parametrize("runner, name", [("codex", "codex"), ("cursor", "cursor-agent")]) +def test_a_codex_or_cursor_panel_turn_runs_in_the_folder_that_gives_it_the_board_tools(client, stand_ins, own_shell, runner, name): + from app.agent import programs + + seen = own_shell / f"{runner}-seen" + (stand_ins / name).write_text(f'#!/bin/sh\nif [ "$1" = "--version" ]; then echo "{name} 0.99.1"; exit 0; fi\npwd -P > "{seen}"\necho "$FORMREF_AGENT_TOKEN" >> "{seen}"\n') + board = client.post("/api/boards", json={"title": f"{runner} turn"}).json()["board"]["id"] + with client.stream("POST", "/api/agent/turns", json={"board_id": board, "message": "tidy", "runner": runner}) as r: + assert r.status_code == 200 + "".join(r.iter_text()) + where, token = seen.read_text().splitlines() + folder = programs.workdir() + assert Path(where) == folder.resolve() + assert re.fullmatch(r"[0-9a-f]{32}", token) + assert programs.TOKEN_VAR in (folder / ".codex" / "config.toml").read_text() + assert programs.TOKEN_VAR in (folder / ".cursor" / "mcp.json").read_text() diff --git a/backend/tests/test_boards_and_clipper.py b/backend/tests/test_boards_and_clipper.py index a486849..4b70787 100644 --- a/backend/tests/test_boards_and_clipper.py +++ b/backend/tests/test_boards_and_clipper.py @@ -146,3 +146,18 @@ def test_resetting_the_token_unpairs_the_old_one(client): assert new != old assert client.get("/api/clip/boards", headers={**EXTENSION, "x-formref-clip-token": old}).status_code == 401 assert client.get("/api/clip/boards", headers={**EXTENSION, "x-formref-clip-token": new}).status_code == 200 + + +def test_a_model_file_larger_than_an_asset_can_be_imported_and_is_still_checked(client): + big = b"\0" * (70 * 1024 * 1024) + r = client.post("/api/models/person-cutout/import", files={"file": ("u2net_human_seg.onnx", big, "application/octet-stream")}) + assert r.status_code == 422 and "SHA-256" in r.json()["detail"] + r = client.post("/api/assets", files={"file": ("big.png", big, "image/png")}) + assert r.status_code == 413 + + +def test_a_model_import_above_its_own_limit_is_refused_before_it_is_read(client): + from app.core.config import settings + + r = client.post("/api/models/person-cutout/import", content=b"x", headers={"content-length": str(settings.max_model_bytes + 2 * 1024 * 1024), "content-type": "application/octet-stream"}) + assert r.status_code == 413 diff --git a/backend/tests/test_f1_guard.py b/backend/tests/test_f1_guard.py index f0b1fe2..de842c5 100644 --- a/backend/tests/test_f1_guard.py +++ b/backend/tests/test_f1_guard.py @@ -80,3 +80,30 @@ def test_foreign_websocket_closes_4403(client, headers): with client.websocket_connect(WS_PATH, headers=headers) as ws: ws.receive() assert refused.value.code == 4403 + + +GOOGLE_RETURN = "/api/cloud/google/callback" + + +@pytest.mark.parametrize("value", ["cross-site", "CROSS-SITE"]) +def test_the_google_sign_in_return_reaches_its_page(bare, value): + r = bare.get(GOOGLE_RETURN, params={"state": "unknown", "code": "c"}, headers={"sec-fetch-site": value}) + assert r.status_code == 400 + assert "unknown or expired" in r.text + + +def test_the_google_sign_in_return_only_opens_for_a_read(bare): + assert bare.post(GOOGLE_RETURN, headers={"sec-fetch-site": "cross-site"}).status_code == 403 + + +def test_other_cloud_paths_stay_closed_to_cross_site_requests(bare): + assert bare.get("/api/cloud", headers={"sec-fetch-site": "cross-site"}).status_code == 403 + assert bare.get(GOOGLE_RETURN + "/x", headers={"sec-fetch-site": "cross-site"}).status_code == 403 + + +def test_the_google_sign_in_page_escapes_the_message(bare, monkeypatch): + from app.core import cloud + + monkeypatch.setattr(cloud, "google_callback", lambda state, code, error: (502, "Sign-in failed: x")) + r = bare.get(GOOGLE_RETURN, params={"state": "s", "code": "c"}) + assert "x" not in r.text and "<b>x</b>" in r.text diff --git a/backend/tests/test_startup.py b/backend/tests/test_startup.py index d80ae5c..c116b5f 100644 --- a/backend/tests/test_startup.py +++ b/backend/tests/test_startup.py @@ -220,3 +220,34 @@ def test_a_frozen_engine_started_alone_with_no_app_near_it_says_so_and_serves_no assert done.returncode == 4 assert "formref-engine is a part of FormRef and serves nothing on its own. Open FormRef instead." in done.stderr assert not (data / "engine.lock").exists() + + +def test_a_service_started_without_the_app_holds_the_folder_so_the_app_engine_waits(tmp_path): + env = engine_env(tmp_path) + port = env["FORMREF_PORT"] + shell = stand_in() + served = subprocess.Popen([sys.executable, "-m", "uvicorn", "app.main:app", "--host", "127.0.0.1", "--port", port], cwd=BACKEND, env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + try: + assert wait_for(lambda: (tmp_path / "engine.lock").is_file() and json.loads((tmp_path / "engine.lock").read_text()).get("pid") == served.pid) + assert json.loads((tmp_path / "engine.lock").read_text())["shell"] == os.getpid() + second = subprocess.run([sys.executable, "formref_engine.py"], cwd=BACKEND, env=engine_env(tmp_path, FORMREF_SHELL_PID=str(shell.pid)), capture_output=True, text=True, timeout=60) + assert second.returncode == 2 and f"formref is already running on {tmp_path} (engine process {served.pid})." in second.stderr + again = subprocess.run([sys.executable, "-m", "uvicorn", "app.main:app", "--host", "127.0.0.1", "--port", str(free_port())], cwd=BACKEND, env=engine_env(tmp_path), capture_output=True, text=True, timeout=60) + assert again.returncode != 0 and "already running" in again.stderr + assert served.poll() is None + assert wait_for(lambda: _answers(port)) + served.terminate() + assert served.wait(timeout=10) is not None + assert not (tmp_path / "engine.lock").exists() + finally: + stop(shell, served) + + +def _answers(port): + import urllib.request + + try: + with urllib.request.urlopen(f"http://127.0.0.1:{port}/api/health", timeout=1) as r: + return r.status == 200 + except OSError: + return False diff --git a/backend/tests/test_window_key.py b/backend/tests/test_window_key.py index 70a6e7c..4ca967f 100644 --- a/backend/tests/test_window_key.py +++ b/backend/tests/test_window_key.py @@ -2,6 +2,7 @@ import os import subprocess import sys +import tempfile import time import urllib.request @@ -55,7 +56,7 @@ def test_an_expired_ticket_is_refused(bare, monkeypatch): def _launch(env_extra): port = free_port() - env = dict(os.environ, FORMREF_PORT=str(port), **env_extra) + env = dict(os.environ, FORMREF_PORT=str(port), FORMREF_DATA_DIR=tempfile.mkdtemp(prefix="key-", dir=os.path.dirname(os.environ["FORMREF_DATA_DIR"])), **env_extra) env.pop("FORMREF_WINDOW_KEY_STDOUT", None) if "FORMREF_WINDOW_KEY_STDOUT" not in env_extra else None proc = subprocess.Popen([sys.executable, "formref_engine.py"], cwd=BACKEND, env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) base = f"http://127.0.0.1:{port}" diff --git a/backend/tests/test_windows_start.py b/backend/tests/test_windows_start.py new file mode 100644 index 0000000..2467c9f --- /dev/null +++ b/backend/tests/test_windows_start.py @@ -0,0 +1,128 @@ +import pytest + +from app.agent import agent_lookup + +NPM_SHIM = ( + '@ECHO off\r\nGOTO start\r\n:find_dp0\r\nSET dp0=%~dp0\r\nEXIT /b\r\n:start\r\nSETLOCAL\r\nCALL :find_dp0\r\n\r\n' + 'IF EXIST "%dp0%\\node.exe" (\r\n SET "_prog=%dp0%\\node.exe"\r\n) ELSE (\r\n SET "_prog=node"\r\n' + ' SET PATHEXT=%PATHEXT:;.JS;=;%\r\n)\r\n\r\nendLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & ' + '"%_prog%" "%dp0%\\node_modules\\@openai\\codex\\bin\\codex.js" %*\r\n' +) +ENV = {"COMSPEC": "C:\\Windows\\system32\\cmd.exe", "PATH": ""} +PROMPT = 'Rules\n\nmake a "hero" & tidy notes' + + +@pytest.fixture +def shim(tmp_path): + script = tmp_path / "node_modules" / "@openai" / "codex" / "bin" / "codex.js" + script.parent.mkdir(parents=True) + script.write_text("") + path = tmp_path / "codex.cmd" + path.write_text(NPM_SHIM) + return path, script + + +def test_an_npm_shim_runs_its_script_with_the_node_beside_it(shim): + path, script = shim + node = path.parent / "node.exe" + node.write_text("") + argv = agent_lookup.start_argv([str(path), "exec", "--json", PROMPT], ENV, "win32") + assert argv == [str(node), str(script), "exec", "--json", PROMPT] + + +def test_an_npm_shim_runs_its_script_with_the_node_on_the_path(shim, tmp_path): + path, script = shim + bin_dir = tmp_path / "nodejs" + bin_dir.mkdir() + node = bin_dir / "node" + node.write_text("") + node.chmod(0o755) + argv = agent_lookup.start_argv([str(path), "exec", PROMPT], {**ENV, "PATH": str(bin_dir)}, "win32") + assert argv == [str(node), str(script), "exec", PROMPT] + + +@pytest.fixture +def plain_cmd(tmp_path): + path = tmp_path / "tool.cmd" + path.write_text("@echo off\r\nsomething.exe %*\r\n") + return str(path) + + +REFUSED_WORDS = [PROMPT, "two\nlines", "tab\there", "nul\x00", "bell\x07", "del\x7f", "100%", 'say "hi"', "wow!", + "a&b", "a|b", "ab", "a^b", "(a)", "a)", "a & b", "x (y)", "p | q", "C:\\Program Files (x86)\\x"] + + +@pytest.mark.parametrize("word", REFUSED_WORDS) +def test_a_plain_cmd_refuses_every_word_with_a_character_the_interpreter_reads(plain_cmd, word): + with pytest.raises(ValueError, match="standard input or a file"): + agent_lookup.start_argv([plain_cmd, "-p", word], ENV, "win32") + + +@pytest.mark.parametrize("word", ["--version", "status", "two words", "--model=gpt,fast;x", "C:\\Program Files\\x", ""]) +def test_a_plain_cmd_takes_plain_words(plain_cmd, word): + assert agent_lookup.start_argv([plain_cmd, word], ENV, "win32") == [ENV["COMSPEC"], "/c", plain_cmd, word] + + +def test_a_plain_cmd_whose_own_path_holds_a_command_character_is_refused(tmp_path): + folder = tmp_path / "tools (x86)" + folder.mkdir() + path = folder / "tool.cmd" + path.write_text("@echo off\r\nsomething.exe %*\r\n") + with pytest.raises(ValueError): + agent_lookup.start_argv([str(path), "--version"], ENV, "win32") + + +def test_an_exe_shim_runs_the_exe_it_wraps_with_an_argv_list(tmp_path): + exe = tmp_path / "node_modules" / "tool" / "bin" / "tool.exe" + exe.parent.mkdir(parents=True) + exe.write_text("") + path = tmp_path / "tool.cmd" + path.write_text('@ECHO off\r\nGOTO start\r\n:start\r\n"%dp0%\\node_modules\\tool\\bin\\tool.exe" %*\r\n') + argv = agent_lookup.start_argv([str(path), "-p", PROMPT], ENV, "win32") + assert argv == [str(exe), "-p", PROMPT] + assert ENV["COMSPEC"] not in argv + + +def test_an_npm_shim_never_goes_through_the_interpreter(shim): + path, script = shim + (path.parent / "node.exe").write_text("") + argv = agent_lookup.start_argv([str(path), "exec", "100% & (done) ^ | !"], ENV, "win32") + assert ENV["COMSPEC"] not in argv and argv[1] == str(script) + + +def test_a_shim_whose_script_is_missing_falls_back_to_the_checked_interpreter(shim): + path, script = shim + script.unlink() + with pytest.raises(ValueError): + agent_lookup.start_argv([str(path), "exec", PROMPT], ENV, "win32") + + +def test_an_exe_is_started_directly(tmp_path): + exe = str(tmp_path / "codex.exe") + assert agent_lookup.start_argv([exe, "exec", PROMPT], ENV, "win32") == [exe, "exec", PROMPT] + + +@pytest.fixture +def spaced_cmd(tmp_path): + folder = tmp_path / "Program Files" + folder.mkdir() + path = folder / "tool.cmd" + path.write_text("@echo off\r\nsomething.exe %*\r\n") + return str(path) + + +@pytest.mark.parametrize("word", ["a & b", "x (y)", "p | q", "plain^"]) +def test_a_cmd_in_a_folder_with_a_space_refuses_command_characters_in_any_word(spaced_cmd, word): + with pytest.raises(ValueError): + agent_lookup.start_argv([spaced_cmd, word], ENV, "win32") + + +def test_a_cmd_in_a_folder_with_a_space_takes_plain_words(spaced_cmd): + assert agent_lookup.start_argv([spaced_cmd, "--version", "two words"], ENV, "win32") == [ENV["COMSPEC"], "/c", spaced_cmd, "--version", "two words"] + + +@pytest.mark.parametrize("suffix", [".cmd.", ".CMD ", ".Bat", ".bat. ."]) +def test_a_batch_name_with_any_case_or_trailing_dots_goes_through_the_check(tmp_path, suffix): + program = str(tmp_path / ("tool" + suffix)) + with pytest.raises(ValueError): + agent_lookup.start_argv([program, "-p", PROMPT], ENV, "win32")