diff --git a/.github/workflows/checks.yml b/.github/workflows/checks.yml index 259fb8e1..02074a76 100644 --- a/.github/workflows/checks.yml +++ b/.github/workflows/checks.yml @@ -172,6 +172,7 @@ jobs: shell: bash env: FORMCUT_NO_WARM: "1" + FORMCUT_DATA_DIR: ${{ runner.temp }}/formcut-bench-data run: | cd backend python -c "from app.bench import _demo_project" 2>/dev/null || true @@ -188,6 +189,8 @@ jobs: # cannot read the heredoc. - name: the engine imports and its routes mount once shell: bash + env: + FORMCUT_DATA_DIR: ${{ runner.temp }}/formcut-routes-data run: | python - <<'PY' import sys, collections diff --git a/backend/HASHOUT_LOG.md b/backend/HASHOUT_LOG.md index c59a6060..5302bf14 100644 --- a/backend/HASHOUT_LOG.md +++ b/backend/HASHOUT_LOG.md @@ -2,6 +2,12 @@ Reasoning behind engine changes, newest first. +## Unreleased · the suite's data folder on Windows is checked against the person's data folder (`tests/test_stand_in_home.py`) + +- **What was there.** `test_the_data_folder_read_at_import_is_the_suites_own_and_not_under_the_persons_home` asserted that the suite's data folder is not anywhere under the person's home. On Windows the system temporary folder is `%LOCALAPPDATA%\Temp`, inside the home, so the folder `tempfile.mkdtemp` makes there always failed it (CI: `C:\Users\runneradmin\AppData\Local\Temp\formcut-tests-...`). +- **The change.** The whole-home check stays where the temporary folder is outside the home (macOS, Linux). Everywhere the data folder must not be the person's own formcut data folder, worked out as `paths.data_root` would from the variables as they were before the stand-in home (`conftest._HOME_BEFORE`): `~/Library/Application Support/formcut`, `%LOCALAPPDATA%\formcut`, or `$XDG_DATA_HOME/formcut`. +- **Seen.** The file passes on Linux; the Windows paths from the failed run checked by hand: the home check is skipped, the data-folder check passes, and a folder inside `%LOCALAPPDATA%\formcut` would fail it. Not run on Windows. + ## 2.20.2 · the MCP tools give the clip ids that per-clip edits need (`app/agent_mcp.py`) - **What was there.** `formcut_edit` takes a clip id for its per-clip operations (crossfade, trim, move, remove), but no tool gave one: `formcut_add_clip` answered with the clip's name and place, and `formcut_get_project` listed clips by label. An agent could place clips and then not change them. diff --git a/backend/app/agent_lookup.py b/backend/app/agent_lookup.py index ea34eba1..9cb01312 100644 --- a/backend/app/agent_lookup.py +++ b/backend/app/agent_lookup.py @@ -15,6 +15,7 @@ from __future__ import annotations +import errno import os import re import shutil @@ -26,7 +27,7 @@ from dataclasses import dataclass, field from pathlib import Path -VERSION = "1.0.1" +VERSION = "1.0.2" 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 +360,57 @@ def _quote(word: str, fish: bool) -> str: return "'" + word.replace("'", "'\"'\"'") + "'" +_SHIM_TARGET = re.compile(r'"%~?dp0%?\\?([^"%]+)"\s+%\*') +_CMD_NEVER = re.compile(r'[\x00-\x1f\x7f&|<>^()!%"]') + + +def shim_target(shim: str | os.PathLike, env: dict | None = None) -> list[str] | None: + """What a package manager's .cmd shim runs (the program, or node and its script), read from the shim, so it can be + started directly instead of through the command interpreter; None when the shim says nothing this can follow.""" + shim = Path(shim) + try: + text = shim.read_text(encoding="utf-8", errors="replace") + except OSError: + return None + found = _SHIM_TARGET.findall(text) + if not found: + return None + target = shim.parent / found[-1].strip().replace("\\", os.sep).lstrip(os.sep) + kind = target.suffix.lower() + if not target.is_file() or kind not in (".exe", ".js", ".cjs", ".mjs"): + return None + if kind == ".exe": + return [str(target)] + beside = shim.parent / "node.exe" + node = str(beside) if beside.is_file() else shutil.which("node", path=(env or os.environ).get("PATH")) + return [node, str(target)] if node else None + + +def cmd_words(words: list[str]) -> list[str]: + """Words for the command interpreter's /c line. A .cmd file reads its arguments again through %*, and the interpreter + acts on & | < > ^ ( ) ! % and quotes even inside quotes, so any word holding one of them, or a control character, is + refused whether or not it has spaces. Long or free text belongs on the program's standard input or in a file.""" + for word in words: + if _CMD_NEVER.search(word): + raise OSError(errno.EINVAL, "an argument holds a character the Windows command interpreter would act on " + "(& | < > ^ ( ) ! % \" or a control character), so it cannot be passed on the command line; " + "pass long text through standard input or a file if the program supports it") + return words + + 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 runs what it points at directly when it is + a package manager's shim, else through the command interpreter with only words it passes on as text.""" 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 words[0].lower().rstrip(". ").endswith((".cmd", ".bat")): + return words + direct = shim_target(words[0], env) + if direct: + return [*direct, *words[1:]] + return [env.get("COMSPEC") or "cmd.exe", "/c", *cmd_words(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/automation.py b/backend/app/automation.py index f87919f9..f494ccda 100644 --- a/backend/app/automation.py +++ b/backend/app/automation.py @@ -1073,7 +1073,9 @@ async def http_rpc_read(request: Request): @router.websocket("/ws") async def websocket_rpc(socket: WebSocket): - if socket.client and socket.client.host not in ("127.0.0.1", "::1", "testclient"): + from . import security + + if not socket.client or not security.loopback(socket.client.host): await socket.close(code=1008) return await socket.accept() diff --git a/backend/app/project_files.py b/backend/app/project_files.py index 4e248fe9..05f1689f 100644 --- a/backend/app/project_files.py +++ b/backend/app/project_files.py @@ -137,6 +137,8 @@ def open_file(path: Path) -> dict: project = document["project"] if not project.get("id"): raise HTTPException(400, f"{path.name} holds no project id") + if not isinstance(project["id"], str) or not store.safe_id(project["id"]): + raise HTTPException(400, f"{path.name} holds a project id formcut cannot keep") existing = store.get_project(project["id"]) project = {**project, "revision": int(existing.get("revision", 0)) if existing else 0} saved = store._save_project(project) # the file is the word on it; the file itself is not written back yet @@ -185,14 +187,23 @@ def collect(project_id: str, folder: Path, report=lambda *_: None, cancelled=lam """Collect Files, as After Effects does: //<title>.fmc with a copy of every file its clips use in Footage/ beside it, the .fmc pointing at those copies (by path and relative to it), so the folder can be moved, zipped or handed over whole. The project itself stays kept where it was; the collected .fmc is a copy of it. - Two files of the same name are told apart (a number added); a file missing now is listed, not copied.""" + Two files of the same name are told apart (a number added), and so is a folder of that name already there, which is + never written into; a file missing now is listed, not copied.""" project = store.get_project(project_id) if project is None: raise HTTPException(404, "project not found") title = "".join(ch for ch in str(project.get("title") or "Untitled") if ch not in '/\\:*?"<>|').strip() or "Untitled" - root = Path(folder).expanduser() / title + parent = Path(folder).expanduser() + parent.mkdir(parents=True, exist_ok=True) + root, number = parent / title, 2 + while True: + try: + root.mkdir() + break + except FileExistsError: + root, number = parent / f"{title} {number}", number + 1 footage = root / "Footage" - footage.mkdir(parents=True, exist_ok=True) + footage.mkdir() where = root / f"{title}{SUFFIX}" table = media_table(project, where) used: set[str] = set() diff --git a/backend/app/projects.py b/backend/app/projects.py index 7e8bf1f3..c353c7dc 100644 --- a/backend/app/projects.py +++ b/backend/app/projects.py @@ -83,9 +83,8 @@ def _ensure_cover(record: dict) -> None: Four cards showing the same film icon tell a person nothing, which is what the home screen looked like while covers were only made on request. """ - project_id = str(record.get("id") or "") - path = COVERS / f"{project_id}.jpg" - if not project_id or path.is_file(): + path = store.id_path(COVERS, record.get("id"), ".jpg") + if path is None or path.is_file(): return document = record.get("document") or {} if not document.get("timelines"): @@ -119,8 +118,8 @@ def project_summaries() -> list[dict]: @router.get("/{project_id}/cover") def project_cover(project_id: str): - path = COVERS / f"{project_id}.jpg" - if not path.is_file(): + path = store.id_path(COVERS, project_id, ".jpg") + if path is None or not path.is_file(): raise HTTPException(status_code=404, detail="no cover") return FileResponse(path, media_type="image/jpeg") @@ -133,14 +132,17 @@ def set_project_cover(project_id: str, body: dict) -> None: from .render_api import FrameRenderer from .render_document import validate_document - document = validate_document(body.get("project") or {}) COVERS.mkdir(parents=True, exist_ok=True) + path = store.id_path(COVERS, project_id, ".jpg") + if path is None: + raise HTTPException(status_code=400, detail="bad project id") + document = validate_document(body.get("project") or {}) renderer = FrameRenderer(document, 480) try: pixels = renderer.frame(max(0.0, float(body.get("time") or 0))) finally: renderer.close() - Image.fromarray(pixels[:, :, :3]).save(COVERS / f"{project_id}.jpg", quality=80) + Image.fromarray(pixels[:, :, :3]).save(path, quality=80) @router.patch("/{project_id}", status_code=200) diff --git a/backend/app/recovery.py b/backend/app/recovery.py index 83ea3d6f..f3b39d1a 100644 --- a/backend/app/recovery.py +++ b/backend/app/recovery.py @@ -19,11 +19,11 @@ router = APIRouter(prefix="/api/recovery", tags=["recovery"]) RECOVERY_DIR = DATA_DIR / "recovery" -_KEY = re.compile(r"^[A-Za-z0-9_-]{1,64}$") +_KEY = re.compile(r"[A-Za-z0-9_-]{1,64}") def _path(key: str): - if not _KEY.match(key): + if not isinstance(key, str) or not _KEY.fullmatch(key): raise HTTPException(status_code=400, detail="bad key") return RECOVERY_DIR / f"{key}.json" diff --git a/backend/app/security.py b/backend/app/security.py index d09d901e..cb564882 100644 --- a/backend/app/security.py +++ b/backend/app/security.py @@ -9,7 +9,7 @@ def loopback(value: str) -> bool: - if value in ("localhost", "testclient", "testserver"): + if value == "localhost": return True try: return ipaddress.ip_address(value).is_loopback diff --git a/backend/app/store.py b/backend/app/store.py index 195b5a61..fdfe93bc 100644 --- a/backend/app/store.py +++ b/backend/app/store.py @@ -1,7 +1,9 @@ import contextlib import json +import re import threading import time +from pathlib import Path from .durable import read_json, set_aside, write_json from .paths import DATA_DIR @@ -15,6 +17,27 @@ _record_texts: dict[str, str] = {} +_PLAIN_ID = re.compile(r"[A-Za-z0-9_-]{1,64}") +_DEVICE_NAMES = re.compile(r"(?i)(con|prn|aux|nul|com[0-9]|lpt[0-9])") + + +def safe_id(project_id) -> bool: + """An id of the kind formcut issues (letters, digits, - and _, as a uuid's hex is), so it names one file of its own + inside formcut's folders on every system: no separator, drive, dot or device name.""" + return type(project_id) is str and bool(_PLAIN_ID.fullmatch(project_id)) and not _DEVICE_NAMES.fullmatch(project_id) + + +def id_path(folder: Path, project_id, suffix: str) -> Path | None: + """The file kept for a project id in folder, or None when the id is not a plain one or the file is not in folder.""" + if not safe_id(project_id): + return None + path = Path(folder) / f"{project_id}{suffix}" + try: + return path if path.resolve().parent == Path(folder).resolve() else None + except (OSError, RuntimeError): + return None + + def _read() -> list[dict]: """projects.json; when it is missing or damaged, the projects' own records (the latest word on each, a deleted project's gone with it), else its backup (one save behind), else none.""" @@ -43,12 +66,13 @@ def _write(projects: list[dict]) -> None: write_json(PROJECTS_FILE, projects) RECORDS_DIR.mkdir(parents=True, exist_ok=True) for project in projects: - project_id = str(project.get("id") or "") - if not project_id or "/" in project_id or "\\" in project_id or project_id.startswith("."): + project_id = project.get("id") + record = id_path(RECORDS_DIR, project_id, ".json") + if record is None: continue text = json.dumps(project) if _record_texts.get(project_id) != text: - write_json(RECORDS_DIR / f"{project_id}.json", project, indent=None, keep_backup=False) + write_json(record, project, indent=None, keep_backup=False) _record_texts[project_id] = text @@ -110,6 +134,8 @@ def delete_project(project_id: str) -> bool: if len(remaining) == len(projects): return False _write(remaining) - (RECORDS_DIR / f"{project_id}.json").unlink(missing_ok=True) # deleted: not to be rebuilt + record = id_path(RECORDS_DIR, project_id, ".json") + if record is not None: + record.unlink(missing_ok=True) # deleted: not to be rebuilt _record_texts.pop(project_id, None) return True diff --git a/frontend/src/ui/settings-popout.ts b/frontend/src/ui/settings-popout.ts index d533d2cb..7ad71015 100644 --- a/frontend/src/ui/settings-popout.ts +++ b/frontend/src/ui/settings-popout.ts @@ -6,6 +6,7 @@ import { t } from "../i18n"; import { localizeElement, text } from "../i18n/text"; import { icon } from "./icons"; +import { escapeHtml } from "./safe-text"; import type { ProjectEngine } from "../engine/project"; import type { MediaBin } from "../engine/media"; import { ACCENTS, PROFILES, apply, read, setAccent, setTheme } from "./appearance"; @@ -446,7 +447,7 @@ export function installSettingsPopout(engine: ProjectEngine, bin: MediaBin, open const row = document.createElement("div"); row.className = "panel-row"; const last = session.operations.at(-1)?.method ?? ""; - row.innerHTML = `<span>${session.name}${session.agent ? ` · ${session.agent}` : ""}</span><span>${session.operations.length} ${t("conn.calls")}${last ? ` · ${last}` : ""}</span>`; + row.innerHTML = `<span>${escapeHtml(String(session.name))}${session.agent ? ` · ${escapeHtml(String(session.agent))}` : ""}</span><span>${session.operations.length} ${t("conn.calls")}${last ? ` · ${escapeHtml(String(last))}` : ""}</span>`; sessionList.append(row); } } catch { @@ -467,7 +468,7 @@ export function installSettingsPopout(engine: ProjectEngine, bin: MediaBin, open const row = document.createElement("div"); row.className = "panel-row"; const percent = Math.round(job.progress * 100); - row.innerHTML = `<span>${job.kind} · ${t("conn.status." + job.status) || job.status}${job.status === "running" ? ` ${percent}%` : ""}</span>`; + row.innerHTML = `<span>${escapeHtml(String(job.kind))} · ${escapeHtml(String(t("conn.status." + job.status) || job.status))}${job.status === "running" ? ` ${percent}%` : ""}</span>`; if (job.status === "running") { const stop = document.createElement("button"); stop.className = "tool-chip"; diff --git a/frontend/src/ui/start-screen.ts b/frontend/src/ui/start-screen.ts index 11c713e1..f4f3db51 100644 --- a/frontend/src/ui/start-screen.ts +++ b/frontend/src/ui/start-screen.ts @@ -266,7 +266,7 @@ export function buildStartScreen(engine: ProjectEngine, bin: MediaBin): HTMLElem fresh.className = "restore-bar"; fresh.dataset.ref = "restore"; fresh.dataset.key = newest.key; - fresh.innerHTML = `<span>${t("save.recover")}: ${newest.title || t("start.new")}</span><button class="tool-chip is-primary" data-restore="${newest.key}">${t("save.restore")}</button><button class="tool-chip" data-discard="${newest.key}">${t("save.discard")}</button>`; + fresh.innerHTML = `<span>${t("save.recover")}: ${escapeHtml(String(newest.title || t("start.new")))}</span><button class="tool-chip is-primary" data-restore="${newest.key}">${t("save.restore")}</button><button class="tool-chip" data-discard="${newest.key}">${t("save.discard")}</button>`; fresh.querySelector("[data-restore]")!.addEventListener("click", () => void (async () => { if (await restoreJournal(engine, newest.key)) { void clearJournal(newest.key); diff --git a/frontend/tests/window/test_window.py b/frontend/tests/window/test_window.py index 851f47f3..38746032 100644 --- a/frontend/tests/window/test_window.py +++ b/frontend/tests/window/test_window.py @@ -23,6 +23,12 @@ "FORMCUT_FFMPEG_AUTO": "0", "FORMCUT_MODELS_AUTO": "0", "USERPROFILE": "{home}", + "LOCALAPPDATA": "{home}/AppData/Local", + "APPDATA": "{home}/AppData/Roaming", + "XDG_DATA_HOME": "{home}/.local/share", + "XDG_CONFIG_HOME": "{home}/.config", + "XDG_CACHE_HOME": "{home}/.cache", + "XDG_STATE_HOME": "{home}/.local/state", } CLEAR_ENV_PREFIX = "FORMCUT_" DIST = REPO / "frontend" / "dist" diff --git a/setup/agents.py b/setup/agents.py index 79003354..66634a66 100755 --- a/setup/agents.py +++ b/setup/agents.py @@ -73,6 +73,7 @@ def dock_problems(folder: Path = DOCK_DIR) -> list[str]: LOOKUP_HASHES = { "1.0.0": "252ea9bb9419d4990f174f91914f09800497bc69e98f849f5643bbf4217cc3f3", "1.0.1": "62667f9b68b7d101e1896ce617240424e33b7e498c560bc79d45f0ab26c77d51", + "1.0.2": "c3e2a64f16a4f592b28d091bbe7bdceaf07d027738324e8ac6b44c905c5bea7e", } diff --git a/setup/golden_frames.py b/setup/golden_frames.py index cbc35922..47a08a02 100755 --- a/setup/golden_frames.py +++ b/setup/golden_frames.py @@ -32,6 +32,8 @@ import sys from pathlib import Path +import scratch_home + ROOT = Path(__file__).resolve().parent.parent sys.path.insert(0, str(ROOT / "backend")) @@ -206,6 +208,7 @@ def main() -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--update", action="store_true", help="write the current output as the golden") args = parser.parse_args() + scratch_home.use("formcut-golden-") current = render_all() diff --git a/setup/output_checks.py b/setup/output_checks.py index b23c0d12..9b818dc0 100755 --- a/setup/output_checks.py +++ b/setup/output_checks.py @@ -23,6 +23,8 @@ import time from pathlib import Path +import scratch_home + ROOT = Path(__file__).resolve().parent.parent sys.path.insert(0, str(ROOT / "backend")) @@ -199,6 +201,7 @@ def rpc_checks() -> None: def main() -> int: + scratch_home.use("formcut-output-checks-") export_checks() rpc_checks() print() diff --git a/setup/scratch_home.py b/setup/scratch_home.py new file mode 100644 index 00000000..9a506ff9 --- /dev/null +++ b/setup/scratch_home.py @@ -0,0 +1,47 @@ +"""A home folder and a data folder of their own for a check script that runs the engine in process. + +Call use() before the first engine module is imported: app.paths reads the data folder once, at import. The home +folder, the per-user folders of macOS, Windows and Linux and FORMCUT_DATA_DIR all point inside one temporary folder, +which is removed and the variables put back when the script ends, so a check never adds renders, jobs or downloads to +the person's own formcut folder. +""" + +from __future__ import annotations + +import atexit +import os +import shutil +import tempfile +from pathlib import Path + +HOME_VARIABLES = ("HOME", "USERPROFILE", "LOCALAPPDATA", "APPDATA", "XDG_DATA_HOME", "XDG_CONFIG_HOME", "XDG_CACHE_HOME", "XDG_STATE_HOME") + + +def use(prefix: str) -> Path: + """Points the home folders and the data folder inside a new temporary folder and returns it.""" + home = Path(tempfile.mkdtemp(prefix=prefix)).resolve() + places = { + "HOME": home, + "USERPROFILE": home, + "LOCALAPPDATA": home / "AppData" / "Local", + "APPDATA": home / "AppData" / "Roaming", + "XDG_DATA_HOME": home / ".local" / "share", + "XDG_CONFIG_HOME": home / ".config", + "XDG_CACHE_HOME": home / ".cache", + "XDG_STATE_HOME": home / ".local" / "state", + "FORMCUT_DATA_DIR": home / "formcut-data", + } + before = {name: os.environ.get(name) for name in places} + os.environ.update({name: str(place) for name, place in places.items()}) + os.environ.setdefault("FORMCUT_NO_WARM", "1") + atexit.register(_put_back, home, before) + return home + + +def _put_back(home: Path, before: dict) -> None: + for name, value in before.items(): + if value is None: + os.environ.pop(name, None) + else: + os.environ[name] = value + shutil.rmtree(home, ignore_errors=True) diff --git a/tests/conftest.py b/tests/conftest.py index c7717e53..a227844e 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -19,6 +19,44 @@ ROOT = Path(__file__).resolve().parent.parent sys.path.insert(0, str(ROOT / "backend")) +_REAL_HOME = Path.home() +HOME_VARIABLES = ("HOME", "USERPROFILE", "LOCALAPPDATA", "APPDATA", "XDG_DATA_HOME", "XDG_CONFIG_HOME", "XDG_CACHE_HOME", "XDG_STATE_HOME") + + +def _stand_in_home() -> tuple[Path, dict]: + """Points the home folder and the per-user folders of macOS, Windows and Linux at a temporary folder before any + engine module is imported, so the default data folder (read once at import by app.paths), the per-user ffmpeg + folder and anything else reached through the home folder never land in the person's own folders.""" + home = Path(tempfile.mkdtemp(prefix="formcut-tests-home-")).resolve() + places = { + "HOME": home, + "USERPROFILE": home, + "LOCALAPPDATA": home / "AppData" / "Local", + "APPDATA": home / "AppData" / "Roaming", + "XDG_DATA_HOME": home / ".local" / "share", + "XDG_CONFIG_HOME": home / ".config", + "XDG_CACHE_HOME": home / ".cache", + "XDG_STATE_HOME": home / ".local" / "state", + } + before = {name: os.environ.get(name) for name in HOME_VARIABLES} + os.environ.update({name: str(places[name]) for name in HOME_VARIABLES}) + return home, before + + +STAND_IN_HOME, _HOME_BEFORE = _stand_in_home() + + +def pytest_unconfigure(config): + import shutil + + for name, value in _HOME_BEFORE.items(): + if value is None: + os.environ.pop(name, None) + else: + os.environ[name] = value + shutil.rmtree(STAND_IN_HOME, ignore_errors=True) + + # The suite's own data folder, removed when the run ends (a full run leaves up to # 150 MB of media, proxies and renders). A folder given in FORMCUT_DATA_DIR is kept. _OWN_DATA_DIR = None if "FORMCUT_DATA_DIR" in os.environ else tempfile.mkdtemp(prefix="formcut-tests-") @@ -28,7 +66,6 @@ AGENT_STAND_INS = ("claude", "codex", "cursor-agent", "agy") _AGENT_SANDBOX = Path(tempfile.mkdtemp(prefix="formcut-agents-")) AGENT_CALLS = _AGENT_SANDBOX / "calls.log" -_REAL_HOME = Path.home() _agent_calls: list[str] = [] if os.name == "posix": (_AGENT_SANDBOX / "bin").mkdir() @@ -42,14 +79,15 @@ ) (_AGENT_SANDBOX / "sh").chmod(0o755) os.environ["SHELL"] = str(_AGENT_SANDBOX / "sh") - os.environ["PATH"] = os.pathsep.join( - [str(_AGENT_SANDBOX / "bin")] - + [ - folder - for folder in os.environ.get("PATH", "").split(os.pathsep) - if folder and not any((Path(folder) / name).exists() for name in (*AGENT_STAND_INS, "agent")) - ] - ) + _folders = [folder for folder in os.environ.get("PATH", "").split(os.pathsep) if folder] + _with_agents = [folder for folder in _folders if any((Path(folder) / name).exists() for name in (*AGENT_STAND_INS, "agent"))] + # A folder left off PATH for holding an agent program can also hold the person's ffmpeg (Homebrew's bin, say); + # the tests run ffmpeg by name, and the per-user ffmpeg folder is now inside the stand-in home, so link it in. + for _tool in ("ffmpeg", "ffprobe"): + _found = next((Path(folder) / _tool for folder in _folders if (Path(folder) / _tool).is_file()), None) + if _found and str(_found.parent) in _with_agents: + (_AGENT_SANDBOX / "bin" / _tool).symlink_to(_found) + os.environ["PATH"] = os.pathsep.join([str(_AGENT_SANDBOX / "bin")] + [folder for folder in _folders if folder not in _with_agents]) for _name in ("NPM_CONFIG_PREFIX", "npm_config_prefix", "PNPM_HOME", "VOLTA_HOME", "BUN_INSTALL", "NVM_SYMLINK"): os.environ.pop(_name, None) for _name in ("CLAUDE", "CODEX", "CURSOR", "ANTIGRAVITY"): @@ -115,6 +153,25 @@ def bare(client): _clients_made_as_the_window_carry_the_key() +def _test_clients_count_as_this_computer() -> None: + """The test client sends from "testclient" to "testserver" unless told otherwise; the engine itself knows only + real loopback names, so the suite adds those two here. The engine's own check stays as security.loopback.__wrapped__.""" + import functools + + from app import security + + real = security.loopback + + @functools.wraps(real) + def loopback(value: str) -> bool: + return value in ("testclient", "testserver") or real(value) + + security.loopback = loopback + + +_test_clients_count_as_this_computer() + + def pytest_sessionfinish(session, exitstatus): import shutil diff --git a/tests/test_family_guard.py b/tests/test_family_guard.py index 23e8b401..9da9ad99 100644 --- a/tests/test_family_guard.py +++ b/tests/test_family_guard.py @@ -125,3 +125,12 @@ def test_websocket_from_the_own_origin_is_accepted(client): with client.websocket_connect(f"{WS}?ticket={ticket}", headers={"host": f"127.0.0.1:{PORT}", "origin": OWN}) as ws: ws.send_json({"jsonrpc": "2.0", "id": 1, "method": "no.such.method"}) assert ws.receive_json()["id"] == 1 + + +@pytest.mark.parametrize("name", ["testserver", "testclient", "testserver.", "intranet"]) +def test_only_real_loopback_names_count_as_this_computer(name): + from app import security + + engine_check = security.loopback.__wrapped__ + assert not engine_check(name) + assert engine_check("localhost") and engine_check("127.0.0.1") and engine_check("::1") diff --git a/tests/test_interface_mount.py b/tests/test_interface_mount.py index 4f99a040..cfb247b9 100644 --- a/tests/test_interface_mount.py +++ b/tests/test_interface_mount.py @@ -28,7 +28,7 @@ def test_with_the_interface_mounted_the_apps_own_routes_answer(tmp_path): script = """ from fastapi.testclient import TestClient from app.main import app -client = TestClient(app) +client = TestClient(app, base_url="http://127.0.0.1:8123", client=("127.0.0.1", 50000)) print(client.get("/api/packages").status_code, client.get("/api/locales").status_code, client.get("/api/diagnostics").status_code, client.get("/").status_code) """ diff --git a/tests/test_project_files.py b/tests/test_project_files.py index 6fc88344..17d3b251 100644 --- a/tests/test_project_files.py +++ b/tests/test_project_files.py @@ -189,3 +189,57 @@ def test_save_and_the_start_screen_offer_project_files(): assert '["collect", "file.collect"]' in menu and "/api/project-files/collect" in bar assert "ev.shiftKey ? saveAs() : doSave(true)" in bar and "offered.has(result.id)" in bar assert 'fromFile.dataset.act = "open-file"' in home and "project.file ?" in home + + +def test_collecting_again_to_the_same_place_keeps_the_first_collection(tmp_path): + one = linking.link_path(_clip(tmp_path / "Card A", "C0001.mp4")) + two = linking.link_path(_clip(tmp_path / "Card B", "C0001.mp4", source="mandelbrot")) + store.save_project(_project(one["id"], "C0001.mp4", "p-first")) + store.save_project(_project(two["id"], "C0001.mp4", "p-second")) + first = project_files.collect("p-first", tmp_path / "Desktop") + kept = (tmp_path / "Desktop" / "Launch" / "Footage" / "C0001.mp4").read_bytes() + second = project_files.collect("p-second", tmp_path / "Desktop") + assert first["folder"] == str(tmp_path / "Desktop" / "Launch") + assert second["folder"] == str(tmp_path / "Desktop" / "Launch 2") + assert (tmp_path / "Desktop" / "Launch" / "Footage" / "C0001.mp4").read_bytes() == kept + assert json.loads((tmp_path / "Desktop" / "Launch" / "Launch.fmc").read_text())["project"]["id"] == "p-first" + assert json.loads((tmp_path / "Desktop" / "Launch 2" / "Launch.fmc").read_text())["project"]["id"] == "p-second" + + +@pytest.mark.parametrize("project_id", ["../../outside", "..\\..\\outside", ".hidden", "a/b", "C:outside", "CON", "two words", 7]) +def test_a_project_file_whose_id_is_not_a_plain_name_is_not_opened(tmp_path, project_id): + from fastapi import HTTPException + + path = tmp_path / "shared.fmc" + document = {"format": project_files.FORMAT, "version": project_files.VERSION, "project": {**_project("0" * 32, "x", project_id)}} + path.write_text(json.dumps(document), encoding="utf-8") + with pytest.raises(HTTPException) as refused: + project_files.open_file(path) + assert refused.value.status_code == 400 + assert store.get_project(project_id) is None + + +def test_cover_paths_stay_in_the_covers_folder(client): + from app import projects + + assert not store.safe_id("..\\outside") and not store.safe_id("../outside") and store.safe_id("p-collect") + assert client.put("/api/projects/..%5Coutside/cover", json={"project": {}, "time": 0}).status_code == 400 + projects._ensure_cover({"id": "../outside", "document": {"timelines": [{}]}}) + assert not (projects.COVERS.parent / "outside.jpg").exists() + + +def test_collecting_where_a_link_or_a_file_has_the_title_goes_to_a_new_folder(tmp_path): + clip = linking.link_path(_clip(tmp_path / "Card", "C0001.mp4")) + store.save_project(_project(clip["id"], "C0001.mp4", "p-linked")) + desk = tmp_path / "Desktop" + desk.mkdir() + elsewhere = tmp_path / "elsewhere" + elsewhere.mkdir() + (desk / "Launch").symlink_to(elsewhere) + (desk / "Launch 2").write_text("kept", encoding="utf-8") + (desk / "Launch 3").symlink_to(tmp_path / "not-there") + collected = project_files.collect("p-linked", desk) + assert collected["folder"] == str(desk / "Launch 4") + assert list(elsewhere.iterdir()) == [] + assert (desk / "Launch 2").read_text(encoding="utf-8") == "kept" + assert not (tmp_path / "not-there").exists() diff --git a/tests/test_project_ids.py b/tests/test_project_ids.py new file mode 100644 index 00000000..ade4d7b6 --- /dev/null +++ b/tests/test_project_ids.py @@ -0,0 +1,72 @@ +"""Project ids name files inside formcut's own folders only when they are ids of the kind formcut issues.""" + +import os +import uuid + +import pytest +from app import recovery, store +from fastapi import HTTPException + + +@pytest.mark.parametrize("project_id", [uuid.uuid4().hex, "p-first", "bare_2", "a" * 64]) +def test_ids_formcut_issues_are_plain(project_id): + assert store.safe_id(project_id) + + +class _Named(str): + def __str__(self): + return "../outside" + + +@pytest.mark.parametrize( + "project_id", + [ + "", + "C:x", + "c:..", + "CON", + "nul", + "Com1", + "lpt9", + "a b", + "a.b", + "a" * 65, + "ok\n", + "ok\x00", + "caf\u00e9", + "../x", + "a\\b", + None, + 7, + ["x"], + _Named("ok"), + ], +) +def test_other_ids_are_not(project_id): + assert not store.safe_id(project_id) + + +def test_the_file_for_an_id_is_in_its_folder(tmp_path): + folder = tmp_path / "covers" + folder.mkdir() + assert store.id_path(folder, "p-one", ".jpg") == folder / "p-one.jpg" + assert store.id_path(folder, "C:outside", ".jpg") is None + assert store.id_path(folder, "CON", ".json") is None + + +@pytest.mark.skipif(os.name != "posix", reason="links need developer mode on Windows") +def test_a_linked_file_that_leads_out_of_the_folder_is_not_used(tmp_path): + folder = tmp_path / "covers" + folder.mkdir() + outside = tmp_path / "elsewhere.jpg" + outside.write_bytes(b"kept") + (folder / "linked.jpg").symlink_to(outside) + assert store.id_path(folder, "linked", ".jpg") is None + assert outside.read_bytes() == b"kept" + + +@pytest.mark.parametrize("key", ["ok\n", "ok\x00", "../x", ""]) +def test_a_recovery_key_is_a_plain_id_with_nothing_after_it(key): + with pytest.raises(HTTPException): + recovery._path(key) + assert recovery._path("unsaved") == recovery.RECOVERY_DIR / "unsaved.json" diff --git a/tests/test_shown_text_escaped.py b/tests/test_shown_text_escaped.py new file mode 100644 index 00000000..98b2430e --- /dev/null +++ b/tests/test_shown_text_escaped.py @@ -0,0 +1,35 @@ +"""Text that reaches the window from a saved file or another program is escaped before it is shown as markup.""" + +import os +import re + +UI = os.path.join(os.path.dirname(__file__), "..", "frontend", "src", "ui") + + +def _read(name): + with open(os.path.join(UI, name), encoding="utf-8") as handle: + return handle.read() + + +def _markup_lines(source, marker): + return [line for line in source.splitlines() if "innerHTML" in line and marker in line] + + +def test_the_restore_bar_escapes_the_recovered_project_title(): + source = _read("start-screen.ts") + lines = _markup_lines(source, "newest.title") + assert lines, "the restore bar line moved; update this test" + for line in lines: + assert not re.search(r"\$\{\s*newest\.title", line), line + assert "escapeHtml(String(newest.title" in line, line + + +def test_connections_escape_session_names_agents_and_job_kinds(): + source = _read("settings-popout.ts") + assert 'import { escapeHtml } from "./safe-text";' in source + for field in ("session.name", "session.agent", "last", "job.kind"): + lines = [line for line in source.splitlines() if "innerHTML" in line and re.search(rf"\b{re.escape(field)}\b", line)] + assert lines, field + for line in lines: + assert not re.search(rf"\$\{{\s*{re.escape(field)}\s*\}}", line), (field, line) + assert f"escapeHtml(String({field}))" in line, (field, line) diff --git a/tests/test_stand_in_home.py b/tests/test_stand_in_home.py new file mode 100644 index 00000000..575fe916 --- /dev/null +++ b/tests/test_stand_in_home.py @@ -0,0 +1,43 @@ +"""The tests run with a home folder of their own (conftest.py), so nothing they write lands in the person's folders.""" + +import sys +import tempfile +from pathlib import Path + +import pytest +from conftest import _HOME_BEFORE, _OWN_DATA_DIR, _REAL_HOME, STAND_IN_HOME + + +def _inside(path: Path) -> bool: + resolved = Path(path).resolve() + return resolved == STAND_IN_HOME or STAND_IN_HOME in resolved.parents + + +def test_the_home_folder_and_the_per_user_folders_are_the_stand_in(): + from app import tools + + assert _inside(Path.home()) + assert _inside(tools.user_ffmpeg_dir()) + + +def test_the_default_data_folder_is_inside_the_stand_in(monkeypatch): + from app import paths + + monkeypatch.delenv("FORMCUT_DATA_DIR", raising=False) + assert _inside(paths.data_root()) + + +@pytest.mark.skipif(not _OWN_DATA_DIR, reason="FORMCUT_DATA_DIR was given for this run, and a given folder is used as given") +def test_the_data_folder_read_at_import_is_the_suites_own_and_not_under_the_persons_home(): + from app import paths + + assert Path(_OWN_DATA_DIR).resolve() == paths.DATA_DIR + if _REAL_HOME.resolve() not in Path(tempfile.gettempdir()).resolve().parents: + assert _REAL_HOME.resolve() not in paths.DATA_DIR.parents + if sys.platform == "darwin": + persons = _REAL_HOME / "Library" / "Application Support" / "formcut" + elif sys.platform == "win32": + persons = Path(_HOME_BEFORE.get("LOCALAPPDATA") or _REAL_HOME) / "formcut" + else: + persons = Path(_HOME_BEFORE.get("XDG_DATA_HOME") or _REAL_HOME / ".local" / "share") / "formcut" + assert persons.resolve() != paths.DATA_DIR and persons.resolve() not in paths.DATA_DIR.parents diff --git a/tests/test_windows_start.py b/tests/test_windows_start.py new file mode 100644 index 00000000..b1db2de2 --- /dev/null +++ b/tests/test_windows_start.py @@ -0,0 +1,129 @@ +"""How an agent program installed as a .cmd shim is started on Windows: what the shim points at, run directly, or the +command interpreter with only words it passes on as text.""" + +import pytest +from app import agent_lookup + +NPM_SHIM = r"""@ECHO off +GOTO start +:find_dp0 +SET dp0=%~dp0 +EXIT /b +:start +SETLOCAL +CALL :find_dp0 + +IF EXIST "%dp0%\node.exe" ( + SET "_prog=%dp0%\node.exe" +) ELSE ( + SET "_prog=node" + SET PATHEXT=%PATHEXT:;.JS;=;% +) + +endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\node_modules\@anthropic-ai\claude-code\cli.js" %* +""" + +ENV = {"COMSPEC": "C:\\Windows\\system32\\cmd.exe", "PATH": ""} + + +def _npm(tmp_path, node_beside=True): + script = tmp_path / "node_modules" / "@anthropic-ai" / "claude-code" / "cli.js" + script.parent.mkdir(parents=True) + script.write_text("", encoding="utf-8") + if node_beside: + (tmp_path / "node.exe").write_bytes(b"") + shim = tmp_path / "claude.cmd" + shim.write_text(NPM_SHIM, encoding="utf-8") + return shim, script + + +def test_an_npm_shim_runs_node_and_its_script_directly(tmp_path): + shim, script = _npm(tmp_path) + prompt = 'fix the "title" & 100% of it!\nthen stop' + assert agent_lookup.start_argv([shim, prompt], ENV, "win32") == [str(tmp_path / "node.exe"), str(script), prompt] + + +@pytest.mark.parametrize("name", ["agent.cmd.", "agent.CMD", "agent.bat .", "agent.Bat"]) +def test_a_batch_file_name_in_any_case_or_with_a_trailing_dot_is_still_a_batch_file(name): + assert agent_lookup.start_argv([f"C:\\tools\\{name}", "--version"], ENV, "win32")[:2] == [ENV["COMSPEC"], "/c"] + with pytest.raises(OSError): + agent_lookup.start_argv([f"C:\\tools\\{name}", "a&b"], ENV, "win32") + + +def test_a_shim_that_points_at_a_program_runs_it(tmp_path): + program = tmp_path / "bin" / "agent.exe" + program.parent.mkdir() + program.write_bytes(b"") + shim = tmp_path / "agent.cmd" + shim.write_text('@"%~dp0\\bin\\agent.exe" %*\n', encoding="utf-8") + assert agent_lookup.start_argv([shim, "-p", "a&b"], ENV, "win32") == [str(program), "-p", "a&b"] + + +def _plain(tmp_path): + batch = tmp_path / "agent.bat" + batch.write_text("@echo off\nrem started some other way\n", encoding="utf-8") + return str(batch) + + +def test_a_batch_file_it_cannot_follow_goes_through_the_interpreter_with_plain_words(tmp_path): + batch = _plain(tmp_path) + words = [batch, "--version", "say hello and wave", "C:\\work\\a file.txt", "--model=x-1", ""] + assert agent_lookup.start_argv(words, ENV, "win32") == [ENV["COMSPEC"], "/c", *words] + + +@pytest.mark.parametrize( + "word", + [ + "a&b", + "say hello & wave", + "(in quotes) ^ <fine>", + "two words | more", + "a (b)", + "wow !", + "a|b", + "a>b", + "a<b", + "a^b", + "(a)", + "50%", + "%PATH%", + "two words 50%", + 'say "hi"', + "hi!", + "one\ntwo", + "tab\x1b", + "nul\x00", + "del\x7f", + ], +) +def test_words_the_interpreter_would_read_as_more_than_text_are_refused(tmp_path, word): + with pytest.raises(OSError) as refused: + agent_lookup.start_argv([_plain(tmp_path), word], ENV, "win32") + assert "command interpreter" in str(refused.value) + assert "standard input or a file" in str(refused.value) + + +@pytest.mark.parametrize("word", ["a&b", "a (b)", "50% of it", 'say "hi"', "line\nbreak"]) +def test_the_program_path_is_held_to_the_same_rule(tmp_path, word): + batch = tmp_path / "agent.bat" + batch.write_text("@echo off\n", encoding="utf-8") + with pytest.raises(OSError): + agent_lookup.cmd_words([str(batch) + word, "--version"]) + + +def test_a_followed_shim_passes_every_character_through_unchanged(tmp_path): + shim, script = _npm(tmp_path) + words = ["a & b", "(x) ^ <y>", "100% !", 'say "hi"', "one\ttwo"] + assert agent_lookup.start_argv([shim, *words], ENV, "win32") == [str(tmp_path / "node.exe"), str(script), *words] + assert ENV["COMSPEC"] not in agent_lookup.start_argv([shim, *words], ENV, "win32") + + +def test_a_shim_without_node_falls_back_to_the_checked_interpreter_line(tmp_path): + shim, _script = _npm(tmp_path, node_beside=False) + assert agent_lookup.start_argv([shim, "--version"], ENV, "win32") == [ENV["COMSPEC"], "/c", str(shim), "--version"] + with pytest.raises(OSError): + agent_lookup.start_argv([shim, "a&b"], ENV, "win32") + + +def test_a_program_that_is_not_a_batch_file_is_started_as_it_is(tmp_path): + assert agent_lookup.start_argv(["C:\\tools\\agent.exe", "a&b"], ENV, "win32") == ["C:\\tools\\agent.exe", "a&b"]