diff --git a/.claude/skills/formcut-skillset/sub-skills/engine-architect/references/engine-map.md b/.claude/skills/formcut-skillset/sub-skills/engine-architect/references/engine-map.md index 7bff3365..e2993ea2 100644 --- a/.claude/skills/formcut-skillset/sub-skills/engine-architect/references/engine-map.md +++ b/.claude/skills/formcut-skillset/sub-skills/engine-architect/references/engine-map.md @@ -22,7 +22,7 @@ The rest is written by hand. | Module | Prefix | Routes | | --- | --- | --- | | addons.py | /api/addons | 3 | -| agent_access.py | /api/agent-access | 6 | +| agent_access.py | /api/agent-access | 7 | | agent_connect.py | /api/agents | 2 | | assets.py | /api/assets | 3 | | automation.py | /api/rpc | 3 | @@ -130,6 +130,7 @@ the automation transports. - `openh264.py` - `package_registry.py` - `paths.py` +- `peer_process.py` - `pixel_effects.py` - `planar.py` - `planar_bench.py` diff --git a/.docs/wiki/Automation.md b/.docs/wiki/Automation.md index 45858555..4b682707 100644 --- a/.docs/wiki/Automation.md +++ b/.docs/wiki/Automation.md @@ -1,6 +1,6 @@ # Automation -Use the running desktop engine's loopback URL, or the development engine at `http://127.0.0.1:8040`. The desktop port is assigned by the OS and appears in the engine startup log. POST JSON-RPC 2.0 with `Content-Type: application/json` and `x-formcut-local: 1`. Methods that change nothing answer at `/api/rpc/read` for any local program. Everything else at `/api/rpc` and every other write needs the per-launch window key, which only the formcut window holds; the header alone is not enough. A program outside the window asks first: `POST /api/agent-access/request` with `{"tool": "...", "agent": "..."}` follows the choice in Settings, Connections, Outside agents (Ask each time, the default, puts Deny, Allow once and Always allow in the window and waits up to two minutes, refusing at once when no window is open; Allowed answers at once; Blocked refuses) and answers with a pass for that task, sent as `x-formcut-agent-pass` and ended with `DELETE /api/agent-access/pass`. A pass cannot change that choice, answer the window's questions or open a terminal. The MCP server does all of this for each tool that is not read-only. The `/api/rpc/ws` websocket is the window's. +Use the running desktop engine's loopback URL, or the development engine at `http://127.0.0.1:8040`. The desktop port is assigned by the OS and appears in the engine startup log. POST JSON-RPC 2.0 with `Content-Type: application/json` and `x-formcut-local: 1`. Methods that change nothing answer at `/api/rpc/read` for any local program. Everything else at `/api/rpc` and every other write needs the per-launch window key, which only the formcut window holds; the header alone is not enough. A program outside the window asks first: `POST /api/agent-access/request` with `{"tool": "...", "agent": "..."}` follows the choice in Settings, Connections, Outside agents (Ask each time, the default, puts Deny, Allow once and Always allow in the window and waits up to two minutes, refusing at once when no window is open; Allowed answers at once; Blocked refuses) and answers with a pass for that task, sent as `x-formcut-agent-pass` and ended with `DELETE /api/agent-access/pass`. A pass cannot change that choice, answer the window's questions or open a terminal. A pass lasts fifteen minutes, and time the computer spends asleep counts toward them. A job started with it in those fifteen minutes (a render, a transcription, a download) keeps it after them until that job finishes, fails or is cancelled, six hours at most, but only for that job: `job.status`, `job.result` and `job.cancel` over `/api/rpc` and `DELETE /api/jobs/{id}`. Every other write is refused, starting another job included, so ask again for those. A program that keeps one pass for its whole connection can say so with `"session": true` and its process id as `"pid"`. When that id is the process at the other end of the request's connection, formcut finds it from the system's own list of connections, the question also offers `session`, Allow for this session, and that answer gives a pass with no fifteen-minute limit (`"session": true` and `"seconds": null` in the reply). A request from any other process, or one whose process formcut cannot find, is not offered it. The pass lasts until the program ends it with `DELETE /api/agent-access/pass`, that process is gone (a new process given the same id later does not count), or formcut quits; `GET /api/agent-access/pass` with the pass says whether it is still good. Choosing Blocked ends every pass at once. The MCP server asks this way and keeps a session pass until its client disconnects. The window's dialog, the family's shared dock (module 2.2.1), shows Deny, Allow once and Always allow only, so Allow for this session cannot yet be chosen there. The MCP server does all of this for each tool that is not read-only. The `/api/rpc/ws` websocket is the window's. ```json {"jsonrpc":"2.0","id":1,"method":"capabilities"} diff --git a/README.md b/README.md index 8a4331bd..9823f0b1 100644 --- a/README.md +++ b/README.md @@ -93,7 +93,7 @@ ## Built for agents -FormCut ships an MCP server with 34 workflow tools; the interface, the JSON-RPC surface and the MCP server edit the same project. Tools that only read run at once; before any other tool FormCut asks in its window (Deny, Allow once, Always allow), and Settings, Connections, Outside agents can make that Allowed or Blocked. Only the FormCut window can change that choice or make other changes without asking. +FormCut ships an MCP server with 34 workflow tools; the interface, the JSON-RPC surface and the MCP server edit the same project. Tools that only read run at once; before any other tool FormCut asks in its window (Deny, Allow once, Always allow), and Settings, Connections, Outside agents can make that Allowed or Blocked. An allowed agent's pass lasts fifteen minutes, time asleep included. A render or other job it started keeps it longer, until the job is finished and six hours at most, but then only to check or cancel that job. Only the FormCut window can change that choice or make other changes without asking. ```sh ./formcut mcp # MCP server on stdio, starts the engine if nothing answers diff --git a/backend/HASHOUT_LOG.md b/backend/HASHOUT_LOG.md index 5302bf14..38cfa758 100644 --- a/backend/HASHOUT_LOG.md +++ b/backend/HASHOUT_LOG.md @@ -2,6 +2,19 @@ Reasoning behind engine changes, newest first. +## Unreleased · a job keeps its pass, and a pass for the agent's session (`app/agent_access.py`, `app/jobs.py`, `app/security.py`, `app/agent_mcp.py`) + +- **The owner's choice.** Keep the fifteen-minute pass, but a tool call started under a pass that runs longer (a render) keeps it until the job ends. And the person can allow an agent for its session: until the agent disconnects or formcut quits. +- **Jobs.** `LocalOnly` puts the pass a request came in with in `agent_access.ADMITTED` for the length of that request; `jobs.submit` hands the new job id to `agent_access.hold`, which ties it to that pass when the pass is live, and the job's last step calls `job_ended`. A pass is good for any write while it is under fifteen minutes old, and for its jobs alone while a job is tied to it (below). A job started by the window holds nothing. Ending the pass ends the tie. Only a job started inside the pass's first fifteen minutes is tied to it, so a pass kept alive by one job cannot be stretched further by starting another. +- **Session.** `POST /api/agent-access/request` takes `session` (the agent keeps one pass for its connection) and `pid`. Only then does the question offer `session`, between `once` and `always`; a `session` answer to an agent that did not ask for one is a refusal. A session pass has no age limit and is good while its process is (below). The id must fit a process id (at most 2^31 - 1), and a process that cannot be looked at counts as gone, so one bad id cannot stop later passes being given. `GET /api/agent-access/pass` says whether a pass is good and whether it is a session's. +- **A pass a job keeps reaches only that job.** Past its fifteen minutes a pass held by jobs answers `agent_access.reach` with the ids of those jobs, not `ALL`, so `pass_valid` is false and it admits no ordinary write. `security._job_call` lets it through only for `DELETE /api/jobs/{id}` of one of those jobs and for `POST /api/rpc`, where `LocalOnly` puts the ids in `agent_access.JOBS_ONLY` and `automation.rpc` answers only `job.status`, `job.result` and `job.cancel` for them. A job started then holds nothing, since `hold` takes only a pass that reaches everything. However long its jobs run, a pass ends `PASS_MOST` (six hours) after it was given. Holds are keyed by job id and pass together and counted: `hold` answers the pass it took and the job's last step gives it back to `job_ended(job_id, held)`, so a second job with the same id, or the same job id on another pass, cannot end or take over another hold. +- **One answer per request, and the wall clock.** `LocalOnly` reads what a request's pass covers once (`security._pass_reach`, called from `security._without_key`, which answers both whether the request may go on and the job ids it was let in for) and puts those ids in `JOBS_ONLY`, so a job that ends between the two cannot leave a JSON-RPC request let in for its jobs with nothing limiting it. A request let in on the job route with no job ids in hand is limited to an empty set, which reaches no job, never to no limit. The read happens only when a pass is what decides, so reads and keyed requests do not look up a session's process. A pass also keeps the wall-clock time it was given, and its age is the larger of the steady clock's and the wall clock's: the steady clock stops while the computer sleeps, so fifteen minutes and six hours are counted in time that passed, asleep or not. A wall clock set back changes nothing, since the steady clock still counts; set forward, it ends passes early, which is the safe side. +- **A session is the asking process's.** `peer_process.owner` reads the system's socket table (`/proc/net/tcp` and each process's `fd` folder on Linux, `lsof` on macOS, `netstat -ano` on Windows) for the process at the other end of the request's loopback connection. A session is offered only when that is the `pid` the request names and its start time can be read (`startup.created`); the pass keeps both, and is live while `startup.same` finds that id with that start time, so a reused id is not the same process. A session pass with no id is not live. The lookup runs once, when the pass is asked for; each write with a session pass checks the process (on macOS that reads `ps` for the start time). +- **Blocked.** Storing Blocked now ends every pass, a session's included, rather than letting them run out. +- **MCP server.** Every ask carries `session: true` and the server's process id. A session pass is kept, checked with `GET /api/agent-access/pass` before each tool call that writes (dropped and asked again when the engine no longer takes it, after formcut was reopened), and not ended at the end of each tool call; `main` ends it when the client disconnects. +- **Not done.** The window cannot give the answer yet: the shared dock's dialog (module 2.2.1, never edited here) knows `deny`, `once` and `always` only, and the adapter keeps to those. The button needs a dock module change in FormVis, copied to the family. +- **Not run.** The Linux and Windows lookups have run here only on recorded tables and a stand-in `/proc`; the live connection test ran on macOS. +- **Tests.** `tests/test_agent_passes.py`, `tests/test_peer_process.py`. ## 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-...`). diff --git a/backend/app/agent_access.py b/backend/app/agent_access.py index d9bdc12d..8068c348 100644 --- a/backend/app/agent_access.py +++ b/backend/app/agent_access.py @@ -11,6 +11,16 @@ environment; a request with a live tab token gets a pass without a question, except under blocked, which refuses every agent, formcut's own tabs included. +A pass lasts fifteen minutes, time asleep included. A job started with it +inside those minutes (a render, a transcription) keeps it past them while the +job is queued or running, six hours at most, but then only for that job's +status and cancel: no other write, and no new job. An agent that says it keeps +one pass for its whole connection (session: true, with its process id) is also offered Allow +for this session when that id is the process at the other end of the +request's connection; that pass lasts until the agent ends it, that process +(the same id and start time) is gone or formcut quits, with no fifteen-minute +limit. Choosing Blocked ends every pass at once. + The choice lives in agent-access.json in formcut's data folder, sealed with a key in the system keychain (seal.py). A choice edited outside the app reads as ask, and the window says so; without a keychain the engine starts, reports the @@ -19,15 +29,16 @@ from __future__ import annotations +import contextvars import hmac import secrets import threading import time from fastapi import APIRouter, HTTPException, Request -from pydantic import BaseModel +from pydantic import BaseModel, Field -from . import seal, window_key +from . import peer_process, seal, startup, window_key from .durable import read_json, write_json from .paths import DATA_DIR @@ -39,13 +50,22 @@ TAB_HEADER = "x-formcut-agent-tab" TAB_ENV = "FORMCUT_AGENT_TAB" PASS_LIFE = 900.0 +PASS_MOST = 6 * 3600.0 # the longest a job keeps a pass for its own status and cancel +ALL = "all" +JOB_METHODS = ("job.status", "job.result", "job.cancel") ASK_SECONDS = 120.0 +PID_MOST = 2**31 - 1 # the largest process id a POSIX or Windows system hands out BROKEN = "Outside agent access was changed outside formcut, so it is back to Ask." NO_WINDOW = ( "formcut asks before an outside agent changes anything, and no formcut window is open: open formcut, or choose Allowed in Settings" ) _lock = threading.Lock() -_passes: dict[str, float] = {} +_passes: dict[str, dict] = {} +# (job id, pass) -> how many submitted jobs with that id hold that pass +_holds: dict[tuple[str, str], int] = {} +ADMITTED: contextvars.ContextVar[str] = contextvars.ContextVar("agent_pass_admitted", default="") +# The jobs a request may reach when only a pass held by those jobs let it in; None when nothing limits it. +JOBS_ONLY: contextvars.ContextVar[frozenset | None] = contextvars.ContextVar("agent_pass_jobs_only", default=None) _tabs: set[str] = set() EVENTS_KEPT = 200 _news = threading.Condition() @@ -62,7 +82,7 @@ def _withdraw(rid: str, reason: str) -> None: _news.notify_all() -def _consent(tool: str, agent: str, client: str, notice: str) -> dict: +def _consent(tool: str, agent: str, client: str, notice: str, session: bool = False) -> dict: """The question as the window gets it; tool, agent and notice are what the page has always read.""" return { "tool": tool, @@ -70,7 +90,7 @@ def _consent(tool: str, agent: str, client: str, notice: str) -> dict: "notice": notice, "client": client, "what": f"run {tool}", - "offers": ["deny", "once", "always"] if seal.available() else ["deny", "once"], + "offers": ["deny", "once", *(["session"] if session else []), *(["always"] if seal.available() else [])], "always": "all", "expires": int((time.time() + ASK_SECONDS) * 1000), "escape": "deny", @@ -105,30 +125,120 @@ def state() -> dict: def _store(choice: str) -> dict: signed = seal.sign({"outsideAgents": choice}) write_json(STORE, signed, private=True) + if choice == "blocked": + with _lock: + _passes.clear() + _holds.clear() return state() -def _grant() -> str: +def _process_live(entry: dict) -> bool: + """A session pass's process is the one that asked: same id and same start time. No id is no process.""" + if entry.get("pid") is None or not entry.get("born"): + return False + try: + return startup.same(entry["pid"], entry["born"]) + except (OSError, OverflowError, ValueError, TypeError): + return False # a process that cannot be looked at is treated as gone + + +def _reach(value: str, entry: dict, now: float): + """What a pass still covers: ALL writes, only the jobs that hold it (a frozenset of their ids), or None. + A session pass covers all while its process lives. Any other covers all for PASS_LIFE; after that only the status + and cancel of the jobs it started, and never past PASS_MOST from when it was given.""" + if entry["session"]: + return ALL if _process_live(entry) else None + # The steady clock stops while the computer sleeps, so the clock on the wall counts too: the larger age wins. + age = max(now - entry["at"], time.time() - entry.get("wall", time.time())) + if age <= PASS_LIFE: + return ALL + with _lock: + held = frozenset(job for job, kept in _holds if kept == value) + return held if held and age <= PASS_MOST else None + + +def _grant(owner: tuple[int, float] | None = None) -> str: + """A new pass; owner is the (pid, start time) of the process a session pass belongs to.""" value = secrets.token_urlsafe(24) now = time.monotonic() with _lock: - for old in [p for p, at in _passes.items() if now - at > PASS_LIFE]: + known = list(_passes.items()) + ended = [p for p, entry in known if _reach(p, entry, now) is None] + with _lock: + for old in ended: _passes.pop(old, None) - _passes[value] = now + for key in [k for k in _holds if k[1] in ended]: + _holds.pop(key, None) + _passes[value] = { + "at": now, + "wall": time.time(), + "session": owner is not None, + "pid": owner[0] if owner else None, + "born": owner[1] if owner else 0.0, + } return value -def pass_valid(value) -> bool: +def _find(value) -> tuple[str, dict] | None: if not isinstance(value, str) or not value: - return False + return None with _lock: - at = next((v for k, v in _passes.items() if hmac.compare_digest(k.encode(), value.encode())), None) - return at is not None and time.monotonic() - at <= PASS_LIFE + return next(((k, e) for k, e in _passes.items() if hmac.compare_digest(k.encode(), value.encode())), None) + + +def reach(value): + """ALL when value is a pass good for any write, the ids of the jobs it may still check and cancel, or None.""" + found = _find(value) + return None if found is None else _reach(found[0], found[1], time.monotonic()) + + +def pass_valid(value) -> bool: + """Whether value is a pass good for any write.""" + return reach(value) == ALL + + +def job_scope(value) -> frozenset[str] | None: + """The job ids a pass past its fifteen minutes still reaches (their status and cancel only), or None.""" + found = reach(value) + return found if isinstance(found, frozenset) else None + + +def session_pass(value) -> bool: + """Whether value is a live pass given for the asking agent's whole session.""" + found = _find(value) + return found is not None and found[1]["session"] and pass_valid(value) + + +def hold(job_id: str) -> str: + """A job submitted on a request that came in with a pass inside its fifteen minutes keeps that pass for the job's + own status and cancel until the job ends, PASS_MOST at the latest. A pass already past its fifteen minutes cannot + start a job, so a job never stretches a pass further. Answers the pass held, for job_ended, or "".""" + found = _find(ADMITTED.get()) + if found is None or found[1]["session"] or _reach(found[0], found[1], time.monotonic()) != ALL: + return "" + with _lock: + if found[0] not in _passes: + return "" + key = (job_id, found[0]) + _holds[key] = _holds.get(key, 0) + 1 + return found[0] + + +def job_ended(job_id: str, held: str) -> None: + """The job that hold tied to the pass held has ended; other jobs with the same id, or other passes, keep theirs.""" + key = (job_id, held) + with _lock: + if _holds.get(key, 0) > 1: + _holds[key] -= 1 + else: + _holds.pop(key, None) def release(value: str) -> None: with _lock: _passes.pop(value, None) + for key in [k for k in _holds if k[1] == value]: + _holds.pop(key, None) def open_tab() -> str: @@ -151,19 +261,22 @@ def tab_live(value) -> bool: return any(hmac.compare_digest(t.encode(), value.encode()) for t in _tabs) -def decide(tool: str, agent: str, tab: str | None = None, client: str = "") -> str: - """A pass for one tool call, or ValueError with the sentence to show the agent.""" +def decide(tool: str, agent: str, tab: str | None = None, client: str = "", owner: tuple[int, float] | None = None) -> dict: + """A pass for one tool call, or for the agent's session when the person says so, or ValueError with the sentence + to show the agent. owner is the (pid, start time) of the asking process when it keeps one pass for its connection + and that pid is the one at the other end of the request's socket; only then is a session offered.""" + session = owner is not None current = state() if current["choice"] == "blocked": raise ValueError("Outside agents are blocked in formcut's Settings, so nothing was changed") if tab_live(tab) or current["choice"] == "allowed": - return _grant() + return {"pass": _grant(), "session": False} from .extensions import ENDED, WindowAbsentError, ask_window ENDED["consent"] = _withdraw try: - answer = ask_window("consent", _consent(tool, agent, client, current["notice"]), ASK_SECONDS) + answer = ask_window("consent", _consent(tool, agent, client, current["notice"], session), ASK_SECONDS) except WindowAbsentError as exc: if "did not answer" in str(exc): raise ValueError(f"Nobody answered in the formcut window within {ASK_SECONDS:.0f} s, so nothing was changed") from exc @@ -171,8 +284,10 @@ def decide(tool: str, agent: str, tab: str | None = None, client: str = "") -> s result = answer.get("result") if result == "always" and seal.available(): _store("allowed") + if result == "session" and session: + return {"pass": _grant(owner), "session": True} if result in ("always", "once"): - return _grant() + return {"pass": _grant(), "session": False} raise ValueError("The person said no in the formcut window, so nothing was changed") @@ -184,6 +299,8 @@ class AgentRequest(BaseModel): tool: str = "" agent: str = "" client: str = "" + session: bool = False + pid: int | None = Field(default=None, gt=0, le=PID_MOST) @router.get("") @@ -201,17 +318,40 @@ def set_choice(body: Choice, request: Request) -> dict: return _store(body.choice) +def _session_owner(body: AgentRequest, scope: dict) -> tuple[int, float] | None: + """(pid, start time) when the request asks for a session and its pid owns the other end of this connection.""" + if not body.session or body.pid is None: + return None + if peer_process.owner(scope.get("client"), scope.get("server")) != body.pid: + return None + born = startup.created(body.pid) + return (body.pid, born) if born > 0 else None + + @router.post("/request") def request_pass(body: AgentRequest, request: Request) -> dict: if request.scope.get("formcut.remote"): raise HTTPException(403, "Outside agents are served on this computer only") try: - value = decide( - body.tool[:120] or "a tool", body.agent[:120] or "an outside agent", request.headers.get(TAB_HEADER), body.client[:120] + given = decide( + body.tool[:120] or "a tool", + body.agent[:120] or "an outside agent", + request.headers.get(TAB_HEADER), + body.client[:120], + _session_owner(body, request.scope), ) except ValueError as exc: raise HTTPException(403, str(exc)) from exc - return {"pass": value, "header": PASS_HEADER, "seconds": PASS_LIFE} + return {"pass": given["pass"], "header": PASS_HEADER, "seconds": None if given["session"] else PASS_LIFE, "session": given["session"]} + + +@router.get("/pass") +def read_pass(request: Request) -> dict: + """Whether the pass this request carries is still good, and whether it is a session's, so an agent can ask again.""" + if request.scope.get("formcut.remote"): + raise HTTPException(403, "Outside agents are served on this computer only") + value = request.headers.get(PASS_HEADER, "") + return {"valid": pass_valid(value), "session": session_pass(value)} @router.get("/waiting") diff --git a/backend/app/agent_mcp.py b/backend/app/agent_mcp.py index dd2f8cf6..aff22574 100644 --- a/backend/app/agent_mcp.py +++ b/backend/app/agent_mcp.py @@ -39,6 +39,7 @@ import functools import json import os +import threading import types import uuid from collections.abc import Mapping @@ -95,11 +96,15 @@ def _headers() -> dict[str, str]: def _ask(tool: str) -> tuple[bool, str]: - """Ask the engine for a pass for one call of a tool that changes something; the engine asks the person.""" + """Ask the engine for a pass for one call of a tool that changes something; the engine asks the person. + + The request says this server keeps one pass for its connection, so the person may allow it for this session; + such a pass is kept in _kept and used by every later tool call until it stops being good or this server ends.""" tab = os.environ.get("FORMCUT_AGENT_TAB", "").strip() + asked = {"tool": tool, "agent": SESSION_NAME, "session": True, "pid": os.getpid()} try: with httpx.Client(timeout=ASK_TIMEOUT, headers={**HEADERS, **({"x-formcut-agent-tab": tab} if tab else {})}) as client: - response = client.post(f"{_engine()}/api/agent-access/request", json={"tool": tool, "agent": SESSION_NAME}) + response = client.post(f"{_engine()}/api/agent-access/request", json=asked) except httpx.HTTPError as error: return False, _explain(error) try: @@ -108,9 +113,43 @@ def _ask(tool: str) -> tuple[bool, str]: body = {} if response.status_code >= 400 or not isinstance(body.get("pass"), str): return False, str(body.get("detail") or f"formcut did not allow {tool} ({response.status_code}); nothing was changed") + if body.get("session") is True: + with _kept_lock: + _kept["pass"] = body["pass"] return True, body["pass"] +_kept: dict[str, str] = {} +_kept_lock = threading.Lock() + + +def _session_pass() -> str: + """The pass the person gave for this session, when the engine still takes it; dropped when it does not.""" + with _kept_lock: + value = _kept.get("pass", "") + if not value: + return "" + try: + with httpx.Client(timeout=5, headers={**HEADERS, "x-formcut-agent-pass": value}) as client: + told = client.get(f"{_engine()}/api/agent-access/pass").json() + except (httpx.HTTPError, ValueError): + told = {} + if isinstance(told, dict) and told.get("valid") is True and told.get("session") is True: + return value + with _kept_lock: + if _kept.get("pass") == value: + _kept.pop("pass", None) + return "" + + +def end_session() -> None: + """End the session pass, if there is one, when this server's connection ends.""" + with _kept_lock: + value = _kept.pop("pass", "") + if value: + _end(value) + + def _need_pass() -> tuple[bool, str]: """The pass for this tool call, asked for at its first write, so a tool's own checks refuse before anything is asked.""" if _pass.get(): @@ -118,6 +157,10 @@ def _need_pass() -> tuple[bool, str]: tool = _tool.get() if not tool: return False, "a read-only tool cannot change anything in formcut" + kept = _session_pass() + if kept: + _pass.set({"x-formcut-agent-pass": kept}) + return True, "" ok, value = _ask(tool) if ok: _pass.set({"x-formcut-agent-pass": value}) @@ -152,7 +195,9 @@ def gated(*call_args: Any, **call_kwargs: Any): given = _pass.get().get("x-formcut-agent-pass") _pass.reset(held) _tool.reset(tool) - if given: + with _kept_lock: + kept = _kept.get("pass") + if given and given != kept: _end(given) return register(gated) @@ -1285,7 +1330,10 @@ def formcut_extension_command( def main() -> None: - mcp.run(transport="stdio") + try: + mcp.run(transport="stdio") + finally: + end_session() if __name__ == "__main__": diff --git a/backend/app/automation.py b/backend/app/automation.py index f494ccda..cdcb6ec2 100644 --- a/backend/app/automation.py +++ b/backend/app/automation.py @@ -9,7 +9,7 @@ from fastapi import APIRouter, HTTPException, Request, WebSocket, WebSocketDisconnect from fastapi.concurrency import run_in_threadpool -from . import jobs, store +from . import agent_access, jobs, store from .catalogue import catalogue from .media import ingest_path, list_media from .orchestration import SessionInput, note_operation, open_session @@ -1018,6 +1018,10 @@ def measure(job_id, report, cancelled): return store.save_project(project, expected_revision=version) +# A pass kept past its fifteen minutes only by jobs it started reaches those jobs and nothing else. +JOBS_ONLY_REFUSAL = "This pass now covers only the status and cancel of the jobs it started; ask again for anything else" + + def rpc(message): if isinstance(message, list): return [reply for item in message for reply in [rpc(item)] if reply is not None] @@ -1031,6 +1035,10 @@ def rpc(message): if "id" in message else None ) + only = agent_access.JOBS_ONLY.get() + asked = params.get("id") or params.get("job_id") + if only is not None and not (message["method"] in agent_access.JOB_METHODS and isinstance(asked, str) and asked in only): + return {"jsonrpc": "2.0", "id": request_id, "error": {"code": -32601, "message": JOBS_ONLY_REFUSAL}} if "id" in message else None try: result = dispatch(message["method"], params) return {"jsonrpc": "2.0", "id": request_id, "result": result} if "id" in message else None diff --git a/backend/app/jobs.py b/backend/app/jobs.py index a07e4ffe..e99b895f 100644 --- a/backend/app/jobs.py +++ b/backend/app/jobs.py @@ -134,6 +134,9 @@ def submit(kind: str, operation, recipe: dict | None = None, job_id: str | None "created": time.time(), **({"recipe": recipe} if recipe else {}), } + from . import agent_access + + held = agent_access.hold(job_id) _write_ledger() def run(): @@ -184,6 +187,7 @@ def report(value, message=None, **fields): _jobs[job_id].update(status="error", error=str(exc)) publish("job", job=job_id, job_kind=kind, status="error", error=str(exc)) finally: + agent_access.job_ended(job_id, held) _write_ledger() _pool.submit(run) diff --git a/backend/app/peer_process.py b/backend/app/peer_process.py new file mode 100644 index 00000000..1aca4453 --- /dev/null +++ b/backend/app/peer_process.py @@ -0,0 +1,143 @@ +"""Which local process holds the other end of a loopback TCP connection. + +The engine asks this of a request that says which process it comes from, so a +pass given for a process's session is tied to the process that asked, not to +any id the request names. The answer comes from the system's own socket table: +/proc on Linux, lsof on macOS, netstat on Windows. Anything that cannot be read +answers None, and a caller treats None as no process. +""" + +from __future__ import annotations + +import ipaddress +import os +import subprocess +import sys + +PROC = "/proc" +WAIT = 5.0 +NO_WINDOW = 0x08000000 +ESTABLISHED = "01" + + +def _address(host: str) -> ipaddress.IPv4Address | ipaddress.IPv6Address | None: + try: + found = ipaddress.ip_address(host.strip("[]").split("%")[0]) + except (ValueError, AttributeError): + return None + mapped = getattr(found, "ipv4_mapped", None) + return mapped or found + + +def _end(value) -> tuple | None: + """(address, port) of one end, from an ASGI scope's client or server pair.""" + if not isinstance(value, (tuple, list)) or len(value) != 2: + return None + host, port = value + found = _address(host) if isinstance(host, str) else None + if found is None or not isinstance(port, int) or not 0 < port < 65536: + return None + return (found, port) + + +def _run(command: list[str]) -> str: + try: + done = subprocess.run( + command, + stdin=subprocess.DEVNULL, + stdout=subprocess.PIPE, + stderr=subprocess.DEVNULL, + timeout=WAIT, + check=False, + creationflags=NO_WINDOW if sys.platform == "win32" else 0, + ) + except (OSError, subprocess.SubprocessError): + return "" + return done.stdout.decode("utf-8", "replace") + + +def _split(text: str) -> tuple | None: + """'127.0.0.1:5000' or '[::1]:5000' as (address, port).""" + host, _, port = text.strip().rpartition(":") + return _end((host, int(port))) if port.isdigit() else None + + +def lsof_owner(text: str, near: tuple, far: tuple) -> int | None: + """The pid in lsof -Fpn output whose socket runs from near to far.""" + pid = None + for line in text.splitlines(): + if line.startswith("p") and line[1:].isdigit(): + pid = int(line[1:]) + elif line.startswith("n") and "->" in line: + here, _, there = line[1:].partition("->") + if pid is not None and _split(here) == near and _split(there) == far: + return pid + return None + + +def netstat_owner(text: str, near: tuple, far: tuple) -> int | None: + """The pid in netstat -ano output whose TCP socket runs from near to far.""" + for line in text.splitlines(): + parts = line.split() + tcp = len(parts) >= 4 and parts[0].upper() == "TCP" and parts[-1].isdigit() + if tcp and _split(parts[1]) == near and _split(parts[2]) == far: + return int(parts[-1]) + return None + + +def _proc_address(text: str) -> tuple | None: + """A /proc/net/tcp address: the address as 32-bit words in host order, then the port, both in hex.""" + raw, _, port = text.partition(":") + try: + words = bytes.fromhex(raw) + packed = b"".join(words[i : i + 4][::-1] for i in range(0, len(words), 4)) if sys.byteorder == "little" else words + return _end((str(ipaddress.ip_address(packed)), int(port, 16))) + except ValueError: + return None + + +def proc_inode(text: str, near: tuple, far: tuple) -> str | None: + """The socket inode in a /proc/net/tcp table for the connection from near to far.""" + for line in text.splitlines()[1:]: + parts = line.split() + if len(parts) > 9 and parts[3] == ESTABLISHED and _proc_address(parts[1]) == near and _proc_address(parts[2]) == far: + return parts[9] + return None + + +def _proc_owner(near: tuple, far: tuple) -> int | None: + inode = None + for table in ("tcp", "tcp6"): + try: + with open(os.path.join(PROC, "net", table)) as source: + inode = proc_inode(source.read(), near, far) + except OSError: + continue + if inode: + break + if not inode: + return None + wanted = f"socket:[{inode}]" + for name in os.listdir(PROC): + if not name.isdigit(): + continue + folder = os.path.join(PROC, name, "fd") + try: + if any(os.readlink(os.path.join(folder, fd)) == wanted for fd in os.listdir(folder)): + return int(name) + except OSError: + continue + return None + + +def owner(client, server) -> int | None: + """The pid of the process whose socket runs from client to server, both ends on this computer, or None.""" + near, far = _end(client), _end(server) + if near is None or far is None or not near[0].is_loopback or not far[0].is_loopback: + return None + if sys.platform == "win32": + return netstat_owner(_run(["netstat", "-ano", "-p", "TCP"]) + _run(["netstat", "-ano", "-p", "TCPv6"]), near, far) + if os.path.isdir(os.path.join(PROC, "net")): + return _proc_owner(near, far) + host = f"[{near[0]}]" if near[0].version == 6 else str(near[0]) + return lsof_owner(_run(["lsof", "-nP", "-a", f"-iTCP@{host}:{near[1]}", "-sTCP:ESTABLISHED", "-Fpn"]), near, far) diff --git a/backend/app/security.py b/backend/app/security.py index cb564882..522b5533 100644 --- a/backend/app/security.py +++ b/backend/app/security.py @@ -64,23 +64,57 @@ def window_origin(origin: str, host: str) -> bool: ) -def _without_key(scope, headers: dict, through_network: bool) -> bool: - """Whether a request that carries no window key may still go on.""" +def _without_key(scope, headers: dict, through_network: bool) -> tuple[bool, frozenset | None]: + """Whether a request that carries no window key may still go on, and the jobs it is then limited to. + + The pass it carries is read once (_pass_reach), only when a pass is what decides, and that one answer both lets + the request in and limits it. The second value is None unless the request came in on a pass that only its + running jobs keep; then it is those job ids, and an empty set (no job at all) when none came with the answer. + """ path = scope.get("path", "") if scope["type"] == "websocket": ticket = parse_qs(scope.get("query_string", b"").decode("latin-1")).get("ticket", [""])[0] - return window_key.spend(ticket) + return window_key.spend(ticket), None if path in KEYED_READS: - return False + return False, None if scope.get("method") in READS or path in OPEN: - return True + return True, None if through_network and path == "/api/remote/pair": - return True + return True, None if path.startswith(WINDOW_ONLY): + return False, None + if through_network or _token_sent(headers): + return True, None + covered = _pass_reach(headers, through_network) + if covered == agent_access.ALL: + return True, None + jobs = covered if isinstance(covered, frozenset) else None + if not _job_call(scope, jobs): + return False, None + return True, jobs or frozenset() + + +def _token_sent(headers: dict) -> bool: + return bool(remote_token()) and hmac.compare_digest(headers.get("x-formcut-token", "").encode(), remote_token().encode()) + + +def _pass_reach(headers: dict, through_network: bool): + """What the pass a request carries covers: agent_access.ALL, the ids of the running jobs that keep it, or None.""" + if through_network or _token_sent(headers): + return None + value = headers.get(agent_access.PASS_HEADER) + return agent_access.reach(value) if value else None + + +def _job_call(scope, jobs: frozenset | None) -> bool: + """A write such a pass still reaches: cancelling one of its jobs, or JSON-RPC, which then answers only + job.status, job.result and job.cancel for those jobs (automation.rpc reads agent_access.JOBS_ONLY).""" + if not jobs or scope["type"] != "http": return False - if through_network or (remote_token() and hmac.compare_digest(headers.get("x-formcut-token", "").encode(), remote_token().encode())): - return True - return agent_access.pass_valid(headers.get(agent_access.PASS_HEADER)) + path, method = scope.get("path", ""), scope.get("method") + if method == "DELETE" and path.startswith("/api/jobs/"): + return path.removeprefix("/api/jobs/") in jobs + return method == "POST" and path == "/api/rpc" def remote_token() -> str: @@ -132,9 +166,10 @@ async def __call__(self, scope, receive, send): and scope.get("path", "").startswith("/api/") ): allowed = allowed and headers.get("x-formcut-local") == "1" - keyless = False - if allowed and not window_key.valid(headers.get(window_key.HEADER)) and not _without_key(scope, headers, through_network): - allowed, keyless = False, True + keyless, jobs_only = False, None + if allowed and not window_key.valid(headers.get(window_key.HEADER)): + allowed, jobs_only = _without_key(scope, headers, through_network) + keyless = not allowed if not allowed: if scope["type"] == "websocket": return await send({"type": "websocket.close", "code": 1008}) @@ -148,4 +183,12 @@ async def safe_send(message): message.setdefault("headers", []).append((b"x-content-type-options", b"nosniff")) await send(message) - await self.app(scope, receive, safe_send) + # The pass this request came in with, so a job it starts can keep that pass alive until the job ends. + admitted = agent_access.ADMITTED.set(headers.get(agent_access.PASS_HEADER, "")) + # A request let in for a pass's jobs (_job_call) reaches those jobs alone over JSON-RPC; any other is not limited. + only = agent_access.JOBS_ONLY.set(jobs_only) + try: + await self.app(scope, receive, safe_send) + finally: + agent_access.JOBS_ONLY.reset(only) + agent_access.ADMITTED.reset(admitted) diff --git a/tests/test_agent_passes.py b/tests/test_agent_passes.py new file mode 100644 index 00000000..1c21d279 --- /dev/null +++ b/tests/test_agent_passes.py @@ -0,0 +1,449 @@ +"""How long an outside agent's pass lasts. + +A pass lasts fifteen minutes. Past that, a job started with it keeps it for that +job's status and cancel only, while the job is queued or running and six hours +at most. An agent that keeps one pass for its connection, and is the process at +the other end of the request's connection, may be allowed for the session: that +pass has no fifteen-minute limit and ends when the agent ends it, when its +process (the same id and start time) is gone, or when the person chooses Blocked. +""" + +import os +import sys +import threading +import time +import types + +import pytest +from app import agent_access, agent_mcp, model_manager, seal +from app.main import app +from conftest import bare as as_any_program +from conftest import window_headers +from fastapi.testclient import TestClient + +OWN = "http://127.0.0.1:8123" +LOCAL = {"x-formcut-local": "1"} +RPC = {"jsonrpc": "2.0", "id": 1, "method": "project.list"} + + +@pytest.fixture(scope="module") +def bare(): + return as_any_program(TestClient(app, base_url=OWN)) + + +@pytest.fixture(scope="module") +def window(): + return TestClient(app, base_url=OWN, headers=window_headers()) + + +@pytest.fixture +def keychain(monkeypatch): + store: dict = {} + fake = types.SimpleNamespace(get_password=lambda s, a: store.get((s, a)), set_password=lambda s, a, v: store.__setitem__((s, a), v)) + monkeypatch.setitem(sys.modules, "keyring", fake) + seal.reset() + agent_access.STORE.unlink(missing_ok=True) + yield store + agent_access.STORE.unlink(missing_ok=True) + seal.reset() + + +@pytest.fixture +def clock(monkeypatch): + """agent_access's monotonic clock, moved on by hand.""" + now = {"t": time.monotonic()} + monkeypatch.setattr(agent_access.time, "monotonic", lambda: now["t"]) + return now + + +def answered(monkeypatch, answer): + from app import extensions + + seen = {} + + def window_answer(action, payload, seconds): + seen.update(payload) + return {"result": answer} + + monkeypatch.setattr(extensions, "ask_window", window_answer) + return seen + + +def ask(client, **body): + return client.post("/api/agent-access/request", headers=LOCAL, json={"tool": "formcut_render", "agent": "test", **body}) + + +def call(client, value, method, **params): + return client.post("/api/rpc", headers={**LOCAL, agent_access.PASS_HEADER: value}, json={**RPC, "method": method, "params": params}) + + +def writes(client, value): + sent = call(client, value, "project.list") + return sent.status_code == 200 and "error" not in sent.json() + + +@pytest.fixture +def agent(monkeypatch): + """The asking process as the engine sees it: who owns the request's connection, and each process's start time.""" + seen = {"peer": os.getpid(), "born": {}, "gone": set()} + monkeypatch.setattr(agent_access.peer_process, "owner", lambda client, server: seen["peer"]) + monkeypatch.setattr(agent_access.startup, "created", lambda pid: seen["born"].get(pid, 1000.0)) + monkeypatch.setattr(agent_access.startup, "alive", lambda pid: pid not in seen["gone"]) + return seen + + +def test_a_pass_ends_after_fifteen_minutes_with_no_job(bare, keychain, clock, monkeypatch): + answered(monkeypatch, "once") + given = ask(bare).json()["pass"] + assert writes(bare, given) + clock["t"] += agent_access.PASS_LIFE + 1 + assert not writes(bare, given) + + +def started_job(bare, given, monkeypatch): + """A download started on the pass given, still running until the returned event is set.""" + started, finish = threading.Event(), threading.Event() + + def long_download(model, report, cancelled): + started.set() + finish.wait(10) + return {} + + monkeypatch.setattr(model_manager, "download", long_download) + job = bare.post("/api/models/krea-2/filter", headers={**LOCAL, agent_access.PASS_HEADER: given}).json()["job_id"] + assert started.wait(5) + return job, finish + + +def settled(bare, job): + for _ in range(100): + if bare.get(f"/api/jobs/{job}").json()["status"] in ("done", "cancelled"): + break + time.sleep(0.05) + time.sleep(0.1) + + +def holding(value, job_id): + carried = agent_access.ADMITTED.set(value) + try: + return agent_access.hold(job_id) + finally: + agent_access.ADMITTED.reset(carried) + + +def test_a_job_started_with_a_pass_keeps_it_for_that_job_until_the_job_ends(bare, keychain, clock, monkeypatch): + answered(monkeypatch, "once") + given = ask(bare).json()["pass"] + job, finish = started_job(bare, given, monkeypatch) + clock["t"] += agent_access.PASS_LIFE * 3 + status = call(bare, given, "job.status", id=job).json() + assert status["result"]["id"] == job + finish.set() + settled(bare, job) + assert call(bare, given, "job.status", id=job).status_code == 403 + + +def test_a_pass_kept_by_its_job_reaches_only_that_job(bare, keychain, clock, monkeypatch): + answered(monkeypatch, "once") + given = ask(bare).json()["pass"] + other = ask(bare).json()["pass"] + job, finish = started_job(bare, given, monkeypatch) + another, finish_other = started_job(bare, other, monkeypatch) + clock["t"] += agent_access.PASS_LIFE + 1 + carrying = {**LOCAL, agent_access.PASS_HEADER: given} + try: + assert not writes(bare, given) + assert "error" in call(bare, given, "job.cancel", id=another).json() + assert bare.delete(f"/api/jobs/{another}", headers=carrying).status_code == 403 + assert bare.post("/api/models/krea-2/filter", headers=carrying).status_code == 403 + assert bare.get("/api/agent-access/pass", headers=carrying).json()["valid"] is False + assert bare.delete(f"/api/jobs/{job}", headers=carrying).json() == {"cancel_requested": True} + finally: + finish.set() + finish_other.set() + settled(bare, job) + settled(bare, another) + + +def test_a_job_kept_pass_does_not_narrow_the_reads_any_program_may_make(bare, keychain, clock, monkeypatch): + answered(monkeypatch, "once") + given = ask(bare).json()["pass"] + job, finish = started_job(bare, given, monkeypatch) + clock["t"] += agent_access.PASS_LIFE + 1 + try: + read = bare.post("/api/rpc/read", headers={**LOCAL, agent_access.PASS_HEADER: given}, json=RPC).json() + assert "result" in read + finally: + finish.set() + settled(bare, job) + + +def test_a_job_kept_pass_can_cancel_its_job_over_json_rpc(bare, keychain, clock, monkeypatch): + answered(monkeypatch, "once") + given = ask(bare).json()["pass"] + job, finish = started_job(bare, given, monkeypatch) + clock["t"] += agent_access.PASS_LIFE + 1 + try: + assert call(bare, given, "job.cancel", job_id=job).json()["result"] == {"cancel_requested": True} + finally: + finish.set() + settled(bare, job) + + +def test_a_job_started_after_fifteen_minutes_does_not_keep_the_pass_longer(bare, keychain, clock, monkeypatch): + answered(monkeypatch, "once") + given = ask(bare).json()["pass"] + assert holding(given, "first") == given + clock["t"] += agent_access.PASS_LIFE + 1 + assert holding(given, "second") == "" + assert agent_access.job_scope(given) == frozenset({"first"}) + agent_access.job_ended("first", given) + assert agent_access.reach(given) is None + + +def test_a_job_keeps_its_pass_six_hours_at_most(bare, keychain, clock, monkeypatch): + answered(monkeypatch, "once") + given = ask(bare).json()["pass"] + holding(given, "long") + clock["t"] += agent_access.PASS_MOST - 1 + assert agent_access.job_scope(given) == frozenset({"long"}) + clock["t"] += 2 + assert agent_access.reach(given) is None + agent_access.job_ended("long", given) + + +def test_a_hold_belongs_to_its_job_and_its_pass_together(bare, keychain, clock, monkeypatch): + answered(monkeypatch, "once") + first, second = ask(bare).json()["pass"], ask(bare).json()["pass"] + holding(first, "same") + holding(second, "same") + clock["t"] += agent_access.PASS_LIFE + 1 + agent_access.job_ended("same", first) + assert agent_access.reach(first) is None + assert agent_access.job_scope(second) == frozenset({"same"}) + agent_access.job_ended("same", second) + assert agent_access.reach(second) is None + + +def test_a_request_let_in_for_its_jobs_stays_limited_to_them_when_they_end_meanwhile(bare, keychain, monkeypatch): + """The answer that lets a request in is the one that limits it, even when its jobs end in between.""" + answers = iter([frozenset({"ending"}), frozenset({"ending"})]) + monkeypatch.setattr(agent_access, "reach", lambda value: next(answers, None)) + sent = call(bare, "a pass kept by a job", "project.list").json() + assert sent["error"]["code"] == -32601 + + +def test_a_pass_is_read_once_per_request(bare, keychain, monkeypatch): + """One read of the pass both lets the request in and sets what it may reach.""" + read = [] + monkeypatch.setattr(agent_access, "reach", lambda value: read.append(value) or frozenset({"kept"})) + assert call(bare, "a pass kept by a job", "job.status", id="other").json()["error"]["code"] == -32601 + assert read == ["a pass kept by a job"] + + +def test_the_key_check_answers_the_jobs_a_request_is_let_in_for(monkeypatch): + from app import security + + monkeypatch.setattr(agent_access, "reach", lambda value: frozenset({"kept"})) + scope = {"type": "http", "method": "POST", "path": "/api/rpc"} + headers = {agent_access.PASS_HEADER: "a pass kept by a job"} + assert security._without_key(scope, headers, False) == (True, frozenset({"kept"})) + monkeypatch.setattr(agent_access, "reach", lambda value: agent_access.ALL) + assert security._without_key(scope, headers, False) == (True, None) + monkeypatch.setattr(agent_access, "reach", lambda value: None) + assert security._without_key(scope, headers, False) == (False, None) + + +def test_a_request_let_in_for_jobs_with_no_job_list_reaches_nothing(bare, keychain, monkeypatch): + """Let in on the job route, a request is limited even when no job list came with it: to no job at all.""" + from app import security + + monkeypatch.setattr(agent_access, "reach", lambda value: None) + monkeypatch.setattr(security, "_job_call", lambda scope, jobs: True) + sent = call(bare, "a pass kept by a job", "project.list").json() + assert sent["error"]["code"] == -32601 + + +def test_a_pass_ends_by_the_wall_clock_when_the_computer_slept(keychain, clock, monkeypatch): + """The steady clock stands still while the computer sleeps; the time on the wall still ends a pass.""" + once, kept = agent_access._grant(), agent_access._grant() + holding(kept, "asleep") + awake = time.time() + monkeypatch.setattr(agent_access.time, "time", lambda: awake + agent_access.PASS_LIFE + 1) + assert not agent_access.pass_valid(once) + assert agent_access.job_scope(kept) == frozenset({"asleep"}) + monkeypatch.setattr(agent_access.time, "time", lambda: awake + agent_access.PASS_MOST + 1) + assert agent_access.reach(kept) is None + agent_access.job_ended("asleep", kept) + + +def test_an_agent_process_id_out_of_range_is_refused_and_later_passes_still_come(bare, keychain, agent, monkeypatch): + answered(monkeypatch, "session") + assert ask(bare, session=True, pid=2**40).status_code == 422 + answered(monkeypatch, "once") + assert writes(bare, ask(bare).json()["pass"]) + + +def test_a_session_pass_whose_process_cannot_be_checked_counts_as_ended(bare, keychain, agent, monkeypatch): + answered(monkeypatch, "session") + agent["peer"] = 424242 + given = ask(bare, session=True, pid=424242).json()["pass"] + + def unreadable(pid): + raise OverflowError("pid out of range") + + monkeypatch.setattr(agent_access.startup, "alive", unreadable) + assert not writes(bare, given) + answered(monkeypatch, "once") + assert writes(bare, ask(bare).json()["pass"]) + + +def test_a_job_started_by_the_window_holds_no_pass(window, keychain, clock, monkeypatch): + answered(monkeypatch, "once") + given = ask(window).json()["pass"] + finish = threading.Event() + monkeypatch.setattr(model_manager, "download", lambda model, report, cancelled: (finish.wait(10), {})[1]) + window.post("/api/models/krea-2/filter") + clock["t"] += agent_access.PASS_LIFE + 1 + assert agent_access.reach(given) is None + finish.set() + + +def test_allow_for_this_session_is_offered_only_to_an_agent_that_keeps_its_pass(bare, keychain, agent, monkeypatch): + seen = answered(monkeypatch, "deny") + ask(bare) + assert "session" not in seen["offers"] + ask(bare, session=True, pid=os.getpid()) + assert seen["offers"] == ["deny", "once", "session", "always"] + + +def test_a_session_is_offered_only_to_the_process_on_the_other_end_of_the_connection(bare, keychain, agent, monkeypatch): + seen = answered(monkeypatch, "deny") + agent["peer"] = os.getpid() + 1 + ask(bare, session=True, pid=os.getpid()) + assert "session" not in seen["offers"] + agent["peer"] = None + ask(bare, session=True, pid=os.getpid()) + assert "session" not in seen["offers"] + answered(monkeypatch, "session") + assert ask(bare, session=True, pid=os.getpid()).status_code == 403 + + +def test_a_session_is_not_offered_when_the_process_start_time_is_unknown(bare, keychain, agent, monkeypatch): + seen = answered(monkeypatch, "deny") + agent["born"][os.getpid()] = 0.0 + ask(bare, session=True, pid=os.getpid()) + assert "session" not in seen["offers"] + + +def test_a_session_pass_outlasts_fifteen_minutes_and_ends_when_asked(bare, keychain, agent, clock, monkeypatch): + answered(monkeypatch, "session") + told = ask(bare, session=True, pid=os.getpid()).json() + assert told["session"] is True and told["seconds"] is None + clock["t"] += agent_access.PASS_LIFE * 10 + carrying = {**LOCAL, agent_access.PASS_HEADER: told["pass"]} + assert writes(bare, told["pass"]) + assert bare.get("/api/agent-access/pass", headers=carrying).json() == {"valid": True, "session": True} + bare.delete("/api/agent-access/pass", headers=carrying) + assert not writes(bare, told["pass"]) + assert bare.get("/api/agent-access/pass", headers=carrying).json() == {"valid": False, "session": False} + + +def test_a_session_answer_to_an_agent_that_did_not_ask_for_one_gives_nothing(bare, keychain, monkeypatch): + answered(monkeypatch, "session") + assert ask(bare).status_code == 403 + + +def test_a_session_pass_ends_when_its_agent_process_is_gone(bare, keychain, agent, monkeypatch): + answered(monkeypatch, "session") + agent["peer"] = 424242 + given = ask(bare, session=True, pid=424242).json()["pass"] + assert writes(bare, given) + agent["gone"].add(424242) + assert not writes(bare, given) + + +def test_a_session_pass_ends_when_its_process_id_is_taken_by_a_new_process(bare, keychain, agent, monkeypatch): + answered(monkeypatch, "session") + agent["peer"] = 424242 + agent["born"][424242] = 1000.0 + given = ask(bare, session=True, pid=424242).json()["pass"] + assert writes(bare, given) + agent["born"][424242] = 5000.0 + assert not writes(bare, given) + + +def test_a_session_pass_with_no_process_id_is_not_live(keychain): + value = "session-with-no-process" + agent_access._passes[value] = {"at": time.monotonic(), "session": True, "pid": None} + try: + assert not agent_access.pass_valid(value) + finally: + agent_access.release(value) + + +def test_blocked_ends_every_pass_at_once(bare, window, keychain, agent, monkeypatch): + answered(monkeypatch, "session") + kept = ask(bare, session=True, pid=os.getpid()).json()["pass"] + answered(monkeypatch, "once") + once = ask(bare).json()["pass"] + assert window.put("/api/agent-access", json={"choice": "blocked"}).status_code == 200 + assert not writes(bare, kept) and not writes(bare, once) + + +def test_the_mcp_server_keeps_a_session_pass_across_tool_calls_and_ends_it_on_exit(monkeypatch): + asked, ended = [], [] + given = "kept-pass" + monkeypatch.setattr(agent_mcp, "_kept", {}) + + def engine_ask(tool): + asked.append(tool) + agent_mcp._kept.update(dict.fromkeys(["pass"], given)) + return True, given + + monkeypatch.setattr(agent_mcp, "_ask", engine_ask) + monkeypatch.setattr(agent_mcp, "_end", ended.append) + good = {"yes": True} + monkeypatch.setattr(agent_mcp, "_session_pass", lambda: agent_mcp._kept.get("pass", "") if good["yes"] else "") + sent = [] + + def engine_rpc(method, params=None, identify=True, timeout=agent_mcp.TIMEOUT): + ok, why = agent_mcp._need_pass() + sent.append(agent_mcp._pass.get().get("x-formcut-agent-pass")) + return (True, {"job_id": "j"}) if ok else (False, why) + + monkeypatch.setattr(agent_mcp, "_rpc", engine_rpc) + agent_mcp.formcut_cancel_render(job_id="a") + agent_mcp.formcut_cancel_render(job_id="b") + assert asked == ["formcut_cancel_render"] and sent == ["kept-pass", "kept-pass"] and ended == [] + agent_mcp.end_session() + assert ended == ["kept-pass"] and agent_mcp._kept == {} + + +def test_the_mcp_server_says_it_keeps_its_pass_and_gives_its_process(monkeypatch): + sent = {} + + class Reply: + status_code = 200 + + def json(self): + return {"pass": "p", "session": False} + + class Client: + def __init__(self, **kwargs): + pass + + def __enter__(self): + return self + + def __exit__(self, *exc): + return False + + def post(self, url, json): + sent.update(json) + return Reply() + + monkeypatch.setattr(agent_mcp.httpx, "Client", Client) + monkeypatch.setattr(agent_mcp, "_kept", {}) + assert agent_mcp._ask("formcut_edit") == (True, "p") + assert sent["session"] is True and sent["pid"] == os.getpid() and agent_mcp._kept == {} diff --git a/tests/test_peer_process.py b/tests/test_peer_process.py new file mode 100644 index 00000000..cd4af0f7 --- /dev/null +++ b/tests/test_peer_process.py @@ -0,0 +1,121 @@ +"""Which process holds the other end of a loopback connection, read from the system's socket table.""" + +import ipaddress +import os +import socket +import sys +import threading +import time + +import httpx +import pytest +import uvicorn +from app import agent_access, extensions, peer_process, seal +from app.main import app + +HERE = (ipaddress.ip_address("127.0.0.1"), 50123) +THERE = (ipaddress.ip_address("127.0.0.1"), 8040) + + +def test_the_process_on_the_other_end_of_a_real_connection_is_this_one(): + server = socket.create_server(("127.0.0.1", 0)) + client = socket.create_connection(server.getsockname()) + accepted, _ = server.accept() + try: + assert peer_process.owner(client.getsockname(), server.getsockname()) == os.getpid() + finally: + for end in (accepted, client, server): + end.close() + + +def test_a_connection_that_is_not_there_has_no_process(): + server = socket.create_server(("127.0.0.1", 0)) + try: + assert peer_process.owner(("127.0.0.1", 1), server.getsockname()) is None + finally: + server.close() + + +def test_an_end_off_this_computer_or_malformed_has_no_process(): + assert peer_process.owner(("192.0.2.4", 5000), ("127.0.0.1", 8040)) is None + assert peer_process.owner(("testclient", 50000), ("127.0.0.1", 8040)) is None + assert peer_process.owner(None, ("127.0.0.1", 8040)) is None + assert peer_process.owner(("127.0.0.1", 0), ("127.0.0.1", 8040)) is None + + +def test_lsof_output_gives_the_process_whose_socket_runs_from_this_end(): + text = "p111\nf4\nn127.0.0.1:8040->127.0.0.1:50123\np222\nf9\nn127.0.0.1:50123->127.0.0.1:8040\n" + assert peer_process.lsof_owner(text, HERE, THERE) == 222 + assert peer_process.lsof_owner(text, (HERE[0], 50124), THERE) is None + + +def test_netstat_output_gives_the_process_whose_socket_runs_from_this_end(): + text = ( + "Active Connections\n\n Proto Local Address Foreign Address State PID\n" + " TCP 127.0.0.1:8040 127.0.0.1:50123 ESTABLISHED 111\n" + " TCP 127.0.0.1:50123 127.0.0.1:8040 ESTABLISHED 222\n" + " TCP [::1]:50123 [::1]:8040 ESTABLISHED 333\n" + ) + assert peer_process.netstat_owner(text, HERE, THERE) == 222 + six = (ipaddress.ip_address("::1"), 50123), (ipaddress.ip_address("::1"), 8040) + assert peer_process.netstat_owner(text, *six) == 333 + + +@pytest.mark.skipif(sys.byteorder != "little", reason="the sample table is written as a little-endian machine writes it") +def test_a_proc_net_tcp_table_gives_the_socket_of_the_connection(): + text = ( + " sl local_address rem_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode\n" + " 0: 0100007F:1F68 0100007F:C3CB 01 00000000:00000000 00:00000000 00000000 1000 0 7001 1\n" + " 1: 0100007F:C3CB 0100007F:1F68 01 00000000:00000000 00:00000000 00000000 1000 0 7002 1\n" + " 2: 0100007F:C3CB 0100007F:1F68 06 00000000:00000000 00:00000000 00000000 1000 0 7003 1\n" + ) + assert peer_process.proc_inode(text, HERE, THERE) == "7002" + + +def test_a_real_request_for_a_session_is_offered_one_only_from_its_own_process(monkeypatch, tmp_path): + """Through a real listener, so the connection's ends come from the server as they do in the app.""" + monkeypatch.setattr(agent_access, "STORE", tmp_path / "agent-access.json") + monkeypatch.setattr(seal, "available", lambda: False) + seen = {} + + def window_answer(action, payload, seconds): + seen.update(payload) + return {"result": "deny"} + + monkeypatch.setattr(extensions, "ask_window", window_answer) + listener = socket.create_server(("127.0.0.1", 0)) + server = uvicorn.Server(uvicorn.Config(app, log_level="warning", lifespan="off")) + running = threading.Thread(target=server.run, kwargs={"sockets": [listener]}, daemon=True) + running.start() + try: + for _ in range(100): + if server.started: + break + time.sleep(0.05) + url = f"http://127.0.0.1:{listener.getsockname()[1]}/api/agent-access/request" + body = {"tool": "formcut_render", "agent": "test", "session": True} + with httpx.Client(headers={"x-formcut-local": "1"}, timeout=10) as client: + client.post(url, json={**body, "pid": os.getpid()}) + assert "session" in seen["offers"] + client.post(url, json={**body, "pid": os.getppid()}) + assert "session" not in seen["offers"] + finally: + server.should_exit = True + running.join(10) + listener.close() + + +@pytest.mark.skipif(sys.platform == "win32" or sys.byteorder != "little", reason="a stand-in /proc needs symbolic links") +def test_the_proc_table_and_a_process_folder_give_the_owner(monkeypatch, tmp_path): + (tmp_path / "net").mkdir() + (tmp_path / "net" / "tcp").write_text( + " sl local_address rem_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode\n" + " 1: 0100007F:C3CB 0100007F:1F68 01 00000000:00000000 00:00000000 00000000 1000 0 7002 1\n" + ) + for pid, inode in (("41", "7001"), ("42", "7002")): + (tmp_path / pid / "fd").mkdir(parents=True) + os.symlink(f"socket:[{inode}]", tmp_path / pid / "fd" / "3") + monkeypatch.setattr(peer_process, "PROC", str(tmp_path)) + monkeypatch.setattr(peer_process.sys, "platform", "linux") + assert peer_process.owner(("127.0.0.1", 50123), ("127.0.0.1", 8040)) == 42 + assert peer_process.owner(("127.0.0.1", 50124), ("127.0.0.1", 8040)) is None