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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,11 @@
`build-local`, a MonkeyTester build plugin: it implements `BUILD_PLUGIN_API.md` (contract
`monkeytester-build-plugin`, kept in the MonkeyTester repo) and builds an app repo's branch on
its own host (Android and iOS on a Mac, Android only on Linux), then uploads the result to the
viewer. See README.md (setup, configuration, API) and SECURITY.md (threat model).
viewer. It also implements the optional capability `write_tests`
(`POST /repos/<owner>/<repo>/tests`): it opens a pull request adding a test recorded on the
viewer's Devices page, through the code host API only (no local clone), for both Gitea and
GitHub. Everything else only reads the repo. See README.md (setup, configuration, API) and
SECURITY.md (threat model).

## Setup (do this first)
README.md → **Install** is the single source for dependencies. The code is Python 3.10+,
Expand All @@ -15,6 +19,7 @@ runs the tests.
`nix run .#tests`, or `python3 -m unittest discover -s tests -v`. They use a fake Gitea, a fake
GitHub and a fake viewer in-process, so no real forge or viewer is contacted. Gitea and GitHub
here are product features (the code hosts the plugin builds from), not where this repo is hosted.
The fakes also accept the writes `POST /repos/<o>/<r>/tests` makes (tests/test_write_tests.py).

## Hosting and review workflow
This repo isn't tied to one code host: it can live on GitHub, Gitea/Forgejo, GitLab, Bitbucket or a
Expand Down
72 changes: 71 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@ cases and to build a branch; the plugin fetches the code from Gitea or GitHub wi
a read-only token, runs the app repo's `.monkeytester/build-<platform>.sh` scripts
here (Android and iOS on a Mac, Android only on Linux) and uploads the built apps
to the viewer with the viewer's `submit.py`, so the run attaches to the build.
It can also open a pull request that adds a test recorded on the viewer's Devices
page (`POST /repos/<owner>/<repo>/tests`, optional capability `write_tests`; that
one route needs a token that can write, see below).

The code-host URL and token live only in this plugin; the viewer never sees the
token. A build that fails is not an HTTP error: `GET /builds/<ref>` is `200` with
Expand Down Expand Up @@ -95,6 +98,12 @@ to any repo's `.git/config`, and passed to git only per command via environment.
Settings → Applications → Access tokens,
- GitHub: a fine-grained token with Contents: read + Metadata: read, or a
classic token with the `repo` scope for private repos,

To let the viewer's **Record test** open pull requests
(`POST /repos/<owner>/<repo>/tests`), the token must also write: Gitea
`write:repository`; GitHub fine-grained Contents: read and write + Pull
requests: read and write (a classic `repo` token already can). With a
read-only token builds work as before and that route answers 403 `forbidden`.
- the **viewer URL** (prefilled with the address the browser is using) — the
plugin uploads to it.
The plugin checks the token against the code host (who it belongs to) before
Expand Down Expand Up @@ -135,6 +144,7 @@ except `GET /health` needs the pairing token when `PLUGIN_TOKEN` is set.
| `GET /repos/<owner>/<repo>[?branch=]` | check a repo (and branch) |
| `GET /repos/<owner>/<repo>/branches` | the repo's branches |
| `GET /repos/<owner>/<repo>/cases?ref=` | test cases on a ref, the build scripts present, and each case's `DEVICE` lines (`devices`, see below) |
| `POST /repos/<owner>/<repo>/tests` | capability `write_tests`: open a pull request adding a recorded test file (see below) |
| `POST /builds` | queue a build; `GET /builds/<ref>` its status |
| `GET /builds/<ref>/log?offset=` | the build log from `offset` |
| `POST /builds/<ref>/cancel` | stop a queued or running build |
Expand Down Expand Up @@ -173,6 +183,64 @@ needed. If any file can't be read, `devices` is left out of the answer, which
the contract reads as "unknown" (the cases list still comes back).
`POST /builds` does not read these files.

### Recorded tests: `POST /repos/<owner>/<repo>/tests`

Optional capability `write_tests` (listed in `/health` `capabilities`; the
contract stays version 1). The viewer's Devices page **Record test** calls it to
add a recorded steps file to a case. Same pairing token as every other route.

```json
{"base": "master",
"case": "onboarding",
"new_case": false,
"file": "login_recorded.txt",
"content": "AI: CLICK Login button\nWAIT: 2.5\nAI: INPUT Email field \"a@b.c\"\n",
"instruction": "MODE: everytime\n",
"title": "Add recorded test onboarding/login_recorded.txt",
"body": "Recorded on the MonkeyTester Devices page (device <name>, AI plugin <NAME>)."}
```

The plugin checks everything itself before contacting the code host:

- `case` matches `^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$`; `file` matches
`^[A-Za-z0-9][A-Za-z0-9_.-]{0,99}\.txt$` and is not `INSTRUCTION.txt`. The file
is written to `mt-tests/<case>/<file>`.
- `content` is a non-empty UTF-8 string of at most 256 KiB (413 `too_large`
above). `title` is the commit message and pull request title (default
`Add recorded test <case>/<file>`); `body` is the pull request text.
- `new_case: false`: `mt-tests/<case>/INSTRUCTION.txt` must exist on `base`.
`new_case: true`: `mt-tests/<case>` must not exist, and `instruction`
(required, non-empty) is written as `mt-tests/<case>/INSTRUCTION.txt` in the
same commit.

It then creates the branch `mt-record/<case>-<file stem>-<yyyymmddHHMMSS>` (UTC)
from `base` with ONE commit holding the file(s) and opens a pull request into
`base`:

```json
{"ok": true, "branch": "mt-record/onboarding-login_recorded-20261202153000",
"pr_url": "https://github.com/o/r/pull/12", "pr_number": 12}
```

| Status | `code` | When |
|---|---|---|
| 400 | `bad_request` | a bad name, type or empty field |
| 401 | `unauthorized` | missing or wrong pairing token |
| 403 | `forbidden` | the code host token can't write (the code host's message is in `error`) |
| 404 | `unknown_branch` | `base` doesn't exist |
| 404 | `unknown_case` | `new_case: false` and the case has no `INSTRUCTION.txt` on `base` |
| 409 | `case_exists` | `new_case: true` and `mt-tests/<case>` exists on `base` |
| 409 | `file_exists` | `mt-tests/<case>/<file>` exists on `base` (never overwritten) |
| 409 | `not_configured` | no code host token saved |
| 413 | `too_large` | `content` over 256 KiB |

Errors use the usual `{"error": ..., "code": ...}` body (plus `forge_status`
when the code host answered). On GitHub the commit is made with the git data API
(tree with `base_tree`, commit, ref) and `POST /repos/{o}/{r}/pulls`; on Gitea
with one `POST /repos/{o}/{r}/contents` call carrying `new_branch` (Gitea 1.20 or
later) and `POST /repos/{o}/{r}/pulls`. If opening the pull request fails, the
new branch is deleted again. No local clone is used.

`/docs` reads `README.md` next to `build_plugin.py` at request time. The
launchd/systemd units run from the checkout and the Nix flake copies every
git-tracked file, so README.md is present in all three; an install without it
Expand All @@ -189,7 +257,9 @@ secret or configuration.
The plugin **runs the scripts of the branch it builds** — run it as a dedicated,
never-root user, and only add trusted repos as projects: a repo's build script
runs with that user's environment, keychain and SDKs. The forge token is read-only
and stays out of every log and git config. Builds are one-at-a-time; use
unless you want `POST /repos/<owner>/<repo>/tests` (it then needs write access, and
can only add files on a new `mt-record/...` branch plus a pull request; the plugin
never pushes to an existing branch) and stays out of every log and git config. Builds are one-at-a-time; use
`POST /builds/<ref>/cancel` to stop a queued or running build (the script's whole
process group is terminated), and `GET /builds/<ref>/log` to watch what it is
doing.
Expand Down
2 changes: 1 addition & 1 deletion SECURITY.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ port, bind and auth, and the hardening tiers) lives in the MonkeyTester repo's
| Access | `PLUGIN_TOKEN` pairing token on every request except `GET /health`, as `X-Plugin-Token` or `Authorization: Bearer`; compared with `hmac.compare_digest`. |
| Bind | `PLUGIN_HOST` defaults to `0.0.0.0` (the viewer reaches the Mac over the LAN). **On any non-loopback bind the token is mandatory**: without `PLUGIN_TOKEN` the plugin exits with status 2 and says how to set it. On `127.0.0.1` / `::1` / `localhost` the token is optional. |
| `/health` | Unauthenticated, never contains a secret. Without the token it only answers the contract, plugin name/version, code host kind, platforms, recipes and capabilities (`auth_required: true`); the code host URL/user, viewer URL and queue need the token. It may add `"docs": "/docs"` (README.md is readable); `GET /docs` itself needs the token and is served as HTML under `default-src 'none'` with no scripts, raw HTML in the README escaped. |
| Code host token | Stored in `config.json` (mode 0600, dir 0700); `GET /config` returns only `{configured, last4, saved_at}`. Given to git per command via `GIT_CONFIG_*` environment — never in argv, the remote URL, `.git/config` or a log. |
| Code host token | Read-only is enough for builds. `POST /repos/<o>/<r>/tests` (capability `write_tests`) needs write access; it only creates a new `mt-record/<case>-<stem>-<timestamp>` branch with one commit adding `mt-tests/<case>/<file>` (and a new case's `INSTRUCTION.txt`) and opens a pull request — names are checked against strict patterns, existing files are never overwritten and no existing branch is pushed to. Stored in `config.json` (mode 0600, dir 0700); `GET /config` returns only `{configured, last4, saved_at}`. Given to git per command via `GIT_CONFIG_*` environment — never in argv, the remote URL, `.git/config` or a log. |
| Subprocesses | argv lists only, never `shell=True`. Repo `owner/name`, branch/ref, case names, request ids and build refs are validated against allowlist regexes (no leading `-`, no `..`, no control chars). git commands put `--` before positional values; request/log values passed to `submit.py` use `--flag=value` so they can never become another option. |
| git transports | `GIT_ALLOW_PROTOCOL=http:https:ssh` and `protocol.allow=never` (plus per-protocol allows) for the fetch **and submodules**: no `ext::` (runs a command), no `file://`/local paths. The clone URL's scheme is checked before any git command runs. |
| Build environment | The plugin's own secrets (`PLUGIN_TOKEN`, `BUILD_LOCAL_IMPORT`, and any `GIT_CONFIG_*` it was started with) are removed from the environment of git, the build scripts and `submit.py`. |
Expand Down
71 changes: 69 additions & 2 deletions build_plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@
(BUILD_PLUGIN_API.md, contract_version 1).

The viewer's Build & Test page asks this plugin for a repo's branches and test
cases and to build a branch. The plugin reads the repo from Gitea or GitHub with
cases and to build a branch; the Devices page's Record test asks it to open a
pull request adding a recorded test (POST /repos/<o>/<r>/tests, capability
write_tests). The plugin reads the repo from Gitea or GitHub with
a read-only token, fetches the branch with git, runs the app repo's
`.monkeytester/build-<platform>.sh` here (Android and iOS on a Mac, Android
only on Linux) and uploads the apps to the viewer with the viewer's submit.py.
Expand Down Expand Up @@ -68,7 +70,7 @@
DEFAULT_PORT = 8094
CONTRACT = "monkeytester-build-plugin"
CONTRACT_VERSION = 1
CAPABILITIES = ["logs", "cancel"]
CAPABILITIES = ["logs", "cancel", "write_tests"]
DEFAULT_KIND = "gitea"
MAX_BODY = 1024 * 1024
REQUEST_TIMEOUT = 60 # seconds a client may take per socket read
Expand All @@ -85,10 +87,15 @@
BRANCH_RE = re.compile(r"^(?!.*\.\.)(?!/)(?!-)(?!.*//)(?!.*@\{)[^\s~^:?*\[\\\x00-\x1f\x7f]{1,250}(?<![/.])$")
CASE_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_.-]{0,99}$")
REQUEST_ID_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_.-]{0,99}$")
# POST /repos/<o>/<r>/tests (capability write_tests)
TEST_CASE_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$")
TEST_FILE_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_.-]{0,99}\.txt$")
MAX_TEST_CONTENT = 256 * 1024 # bytes of UTF-8

STATUS_FOR_CODE = {
"bad_request": 400, "unauthorized": 401, "not_found": 404, "not_configured": 409,
"forge_refused": 400, "forge_unreachable": 502, "internal": 500, "too_large": 413,
"forbidden": 403, "unknown_branch": 404, "unknown_case": 404, "case_exists": 409, "file_exists": 409,
}


Expand Down Expand Up @@ -290,6 +297,54 @@ def check_branch(branch, what="branch"):
return branch


def _utf8_text(value, field, required=True, limit=None):
"""A request string checked to be UTF-8-encodable, non-empty when required
and at most `limit` bytes."""
if value is None and not required:
return ""
if not isinstance(value, str):
raise PluginError(f"{field} must be a string")
try:
size = len(value.encode("utf-8"))
except UnicodeEncodeError:
raise PluginError(f"{field} is not valid UTF-8") from None
if required and not value.strip():
raise PluginError(f"{field} must not be empty")
if limit is not None and size > limit:
raise PluginError(f"{field} is too large (max {limit} bytes)", "too_large")
return value


def check_write_tests(data, now=None):
"""The checked POST /repos/<o>/<r>/tests request, plus the branch to push
(`branch`). Never trusts the viewer: names, sizes and types are all checked
here before the code host is contacted."""
if not isinstance(data, dict):
raise PluginError("expected a JSON object")
base = check_branch(data.get("base"), "base branch")
case = data.get("case")
if not isinstance(case, str) or not TEST_CASE_RE.match(case):
raise PluginError("case must match ^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$")
file = data.get("file")
if not isinstance(file, str) or not TEST_FILE_RE.match(file):
raise PluginError("file must match ^[A-Za-z0-9][A-Za-z0-9_.-]{0,99}\\.txt$")
if file.lower() == "instruction.txt":
raise PluginError("file must not be INSTRUCTION.txt")
new_case = data.get("new_case", False)
if not isinstance(new_case, bool):
raise PluginError("new_case must be true or false")
content = _utf8_text(data.get("content"), "content", limit=MAX_TEST_CONTENT)
instruction = ""
if new_case:
instruction = _utf8_text(data.get("instruction"), "instruction", limit=MAX_TEST_CONTENT)
title = _utf8_text(data.get("title"), "title", required=False, limit=1024).strip()
title = " ".join(title.split()) or f"Add recorded test {case}/{file}"
body = _utf8_text(data.get("body"), "body", required=False, limit=65536)
return {"base": base, "case": case, "new_case": new_case, "file": file, "content": content,
"instruction": instruction, "title": title, "body": body,
"branch": sources.record_branch(case, file, now)}


class Plugin:
def __init__(self, directory=None, pairing_token=None, platforms=None):
directory = Path(directory) if directory else state_dir()
Expand Down Expand Up @@ -438,6 +493,15 @@ def start_build(self, data):
log(f"build {ref} queued: {repo} {branch} {','.join(platforms)} ({request_id})")
return {"build_ref": ref, "url": ""}

# POST /repos/<owner>/<repo>/tests
def write_tests(self, repo, data):
req = check_write_tests(data)
cfg = self.configured()
src = self.source(cfg)
result = source_call(src.write_tests, cfg, repo, req)
log(f"recorded test {req['case']}/{req['file']} pushed to {repo} {req['branch']}: {result.get('pr_url')}")
return result

def build_status(self, ref):
body = self.runner.body(ref)
if body is None:
Expand Down Expand Up @@ -605,6 +669,9 @@ def route(self, method, parts, query):
return self.send_text(200, data, headers)
elif len(parts) == 3 and parts[0] == "builds" and parts[2] == "cancel" and method == "POST":
return self.send_json(200, p.cancel_build(parts[1]))
elif len(parts) == 4 and parts[0] == "repos" and parts[3] == "tests" and method == "POST":
repo = check_repo_name(parts[1], parts[2])
return self.send_json(200, p.write_tests(repo, self.read_body()))
elif len(parts) in (3, 4) and parts[0] == "repos" and method == "GET":
repo = check_repo_name(parts[1], parts[2])
sub = parts[3] if len(parts) == 4 else None
Expand Down
55 changes: 53 additions & 2 deletions sources/__init__.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
"""Read-only code host access for build-local (BUILD_PLUGIN_API.md).
"""Code host access for build-local (BUILD_PLUGIN_API.md).

One module per code host kind (`gitea`, `github`). Every module offers the
same functions, all READ-ONLY (the token only needs to read the repo):
same functions. All but write_tests are READ-ONLY (a read-only token is enough
to list and build); write_tests needs a token that can push a branch and open
a pull request:

KIND, LABEL, DEFAULT_URL
normalize_url(url) -> the stored forge_url (raises SourceError)
Expand All @@ -16,6 +18,10 @@
git_auth_config(cfg, repo) -> [(git config key, value)] carrying the token,
passed per command via GIT_CONFIG_* env,
never written to .git/config or the URL
write_tests(cfg, repo, req) -> contract POST /repos/<o>/<r>/tests body
({ok, branch, pr_url, pr_number}); `req`
is the request already checked by
build_plugin.check_write_tests
CLONE_URL_OVERRIDE -> tests only: "file:///.../{owner}/{name}.git"

`cfg` is the plugin's config dict ({"forge_url", "token", ...}).
Expand All @@ -27,6 +33,7 @@
import binascii
import re
import threading
import time
from concurrent.futures import ThreadPoolExecutor

PLATFORMS = ("android", "ios")
Expand Down Expand Up @@ -192,6 +199,50 @@ def override_url(template, repo):
return template.format(owner=owner, name=name, repo=repo)


# ─── POST /repos/<o>/<r>/tests (capability write_tests) ───

def record_branch(case, file, now=None):
"""The branch a recorded test is pushed to:
mt-record/<case>-<file stem>-<yyyymmddHHMMSS> (UTC). Runs of dots in the
stem are collapsed to one so the name is always a valid git ref."""
stem = file[:-len(".txt")] if file.endswith(".txt") else file
stem = re.sub(r"\.{2,}", ".", stem)
stamp = time.strftime("%Y%m%d%H%M%S", time.gmtime(now))
return f"mt-record/{case}-{stem}-{stamp}"


def test_files(req):
"""{repo path: text} a write_tests request commits: the test file, plus
INSTRUCTION.txt for a new case."""
folder = f"{CASES_DIR}/{req['case']}"
files = {f"{folder}/{req['file']}": req["content"]}
if req["new_case"]:
files[f"{folder}/INSTRUCTION.txt"] = req["instruction"]
return files


def check_test_paths(req, state):
"""The write_tests preconditions on `base`, shared by every source.

state(path) -> "file", "dir" or None (missing); raises SourceError when the
code host can't answer."""
folder = f"{CASES_DIR}/{req['case']}"
if req["new_case"]:
if state(folder) is not None:
raise SourceError(f"case {req['case']} already exists on {req['base']}", "case_exists", 409)
elif state(f"{folder}/INSTRUCTION.txt") != "file":
raise SourceError(f"no case {req['case']} on {req['base']} ({folder}/INSTRUCTION.txt missing)",
"unknown_case", 404)
if not req["new_case"] and state(f"{folder}/{req['file']}") is not None:
raise SourceError(f"{folder}/{req['file']} already exists on {req['base']}", "file_exists", 409)


def forbidden(label, what, status, message):
"""SourceError for a write the code host refused for lack of permission."""
return SourceError(f"{what}: the {label} token can't write to this repo ({message})",
"forbidden", 403, status)


def get(kind):
"""The source module for a forge_kind, or None."""
if kind == "gitea":
Expand Down
Loading
Loading