diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..f61a8e8 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +# A plugin's content hash covers its exact bytes, on every checkout. +plugins/** -text diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS new file mode 100644 index 0000000..59f8aaf --- /dev/null +++ b/.github/CODEOWNERS @@ -0,0 +1,6 @@ +# Every pull request needs a review from an owner. The last matching line wins. +* @MHohlios + +# An owner for a game joins here as contributors show up, with Michael kept +# on for now: +# /plugins// @MHohlios @their-handle diff --git a/.github/workflows/budget-comment.yml b/.github/workflows/budget-comment.yml new file mode 100644 index 0000000..63c8c44 --- /dev/null +++ b/.github/workflows/budget-comment.yml @@ -0,0 +1,43 @@ +name: Budget comment + +# A pull request from a fork can't write to this repo, so this runs afterwards +# from main, where it can. It never checks out the pull request's code, and it +# treats the report as forgeable: see `render_budget_table` in ci/registry.py. +on: + workflow_run: + workflows: [Registry] + types: [completed] + +permissions: {} + +jobs: + comment: + name: Show the budget on the pull request + if: github.event.workflow_run.event == 'pull_request' + runs-on: ubuntu-24.04 + permissions: + actions: read + contents: read + pull-requests: write + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Fetch the report + id: report + continue-on-error: true + env: + GH_TOKEN: ${{ github.token }} + GH_REPO: ${{ github.repository }} + RUN_ID: ${{ github.event.workflow_run.id }} + run: gh run download "$RUN_ID" --name budget --dir "$RUNNER_TEMP/report" + - name: Post it + if: steps.report.outcome == 'success' + env: + GH_TOKEN: ${{ github.token }} + HEAD_OWNER: ${{ github.event.workflow_run.head_repository.owner.login }} + HEAD_BRANCH: ${{ github.event.workflow_run.head_branch }} + HEAD_SHA: ${{ github.event.workflow_run.head_sha }} + run: | + python3 ci/registry.py comment "$RUNNER_TEMP/report/budget.json" > "$RUNNER_TEMP/comment.md" + ci/post-budget-comment.sh "$RUNNER_TEMP/comment.md" diff --git a/.github/workflows/registry.yml b/.github/workflows/registry.yml new file mode 100644 index 0000000..2941df9 --- /dev/null +++ b/.github/workflows/registry.yml @@ -0,0 +1,85 @@ +name: Registry + +on: + pull_request: + push: + branches: [main] + +permissions: + contents: read + +env: + CARGO_TERM_COLOR: always + +jobs: + # Runs a stranger's plugin, so it holds no secret and can write nothing. + check: + name: Check plugins + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Read the pinned versions + run: ci/load-pins.sh + - name: Check out MUDling at the pinned commit + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + repository: Vyttle-LLC/mudling + ref: ${{ env.MUDLING_COMMIT }} + path: .mudling + persist-credentials: false + - uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable + with: + toolchain: stable + - uses: Swatinem/rust-cache@2201cc584a476d1b508be977bbe4b7d1c7a52e9c # v2.9.3 + with: + workspaces: .mudling + - name: Build mudling + run: cargo build --release --locked -p mudling-cli --manifest-path .mudling/Cargo.toml + - name: Install luau-analyze + run: ci/install-luau.sh "$RUNNER_TEMP/luau" + - name: Test the checks themselves + env: + MUDLING: .mudling/target/release/mudling + LUAU_ANALYZE: ${{ runner.temp }}/luau/luau-analyze + SESSION_LOG: .mudling/crates/mudling-bench/fixtures/session.txt + run: python3 -m unittest discover ci + - name: Check every plugin + run: > + python3 ci/registry.py check + --mudling .mudling/target/release/mudling + --luau-analyze "$RUNNER_TEMP/luau/luau-analyze" + --session-log .mudling/crates/mudling-bench/fixtures/session.txt + --report budget.json + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + if: always() + with: + name: budget + path: budget.json + if-no-files-found: ignore + + # Holds the signing key, so it runs no plugin's code and only runs on main. + publish: + name: Publish the signed index + needs: check + if: github.event_name == 'push' + runs-on: ubuntu-24.04 + permissions: + contents: write + # One at a time, and a newer main replaces any run still waiting. + concurrency: + group: publish-index + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - name: Build and sign the index + env: + INDEX_SIGNING_KEY: ${{ secrets.INDEX_SIGNING_KEY }} + TZ: UTC + run: > + python3 ci/registry.py index + --commit "$GITHUB_SHA" + --published-at "$(git show --no-patch --format=%cd --date=format-local:%Y-%m-%dT%H:%M:%SZ)" + --output "$RUNNER_TEMP/index.json" + - name: Publish it to the index branch + run: ci/publish-index.sh "$RUNNER_TEMP/index.json" diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..c214e8e --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +# Session logs hold other players' chat, so they never go in this repo. +*.log + +__pycache__/ +.mudling/ +budget.json diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..509282e --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,125 @@ +# Adding a plugin + +This takes you from nothing to an open pull request. You need +[Rust](https://rustup.rs), [git](https://git-scm.com), a GitHub account, and a +game you know. You don't need to read MUDling's core. + +## 1. Build the `mudling` command + +```sh +git clone https://github.com/Vyttle-LLC/mudling +cd mudling +cargo build --release -p mudling-cli +``` + +The command is now at `target/release/mudling`. These steps call it `mudling`, so +either put that folder on your `PATH` or use the full path. + +## 2. Fork this repo and make your plugin + +Fork [mudling-plugins](https://github.com/Vyttle-LLC/mudling-plugins) on GitHub, +then: + +```sh +git clone https://github.com//mudling-plugins +cd mudling-plugins +git switch -c add-mygame +mudling plugin new mygame --dir plugins +mudling plugin test plugins/mygame +``` + +The `id`, here `mygame`, is the folder's name too, and they must stay the same. +Use lowercase letters, digits, `.`, `_` and `-`. Other file and folder names may +also use capitals, but no spaces and nothing outside ASCII. Don't add a +`.gitattributes` file: it would change the bytes that the app checks. You now have +a plugin that loads and passes its own test. + +## 3. Teach it your game + +Edit the files in `plugins/mygame/`: + +- `plugin.toml` is the manifest. Set `name`, set `hosts` under `[servers]` to the + game's address, and add `mssp_names` if the game sends its MSSP name. The + directory shows and matches plugins by these. +- `text.toml` reads the game's text. Other extension points get files of their + own. +- `hooks.luau` holds Luau hooks, for what a pattern can't read. If you need none, + delete the file along with `[hooks]` and `permissions` in `plugin.toml` and + every `hook = "…"` line in `text.toml`. Then run the `--update` command from + step 4 once, because the sample's `.expected` still lists what the hook did. + +The [plugin API reference](https://github.com/Vyttle-LLC/mudling/blob/main/docs/plugins/reference.md) +lists everything, and the +[cookbook](https://github.com/Vyttle-LLC/mudling/blob/main/docs/plugins/cookbook.md) +works through a real plugin. + +To try a log from your own play without keeping it: + +```sh +mudling plugin test plugins/mygame --log ~/somewhere/outside/this/repo/session.log +``` + +## 4. Write its tests + +A test is a pair of files in `tests/`: `.txt`, some game text, and +`.expected`, what it should produce. + +**Write the text by hand, and make up every name.** A real session log holds other +players' chat, so never commit one, not even part of one. CI fails any `*.log` +file. + +Once the text covers what your plugin reads: + +```sh +mudling plugin test plugins/mygame --update +``` + +This writes the `.expected` files. Read them, because whatever they hold is what +your plugin will be held to. Then run the test on its own to see it pass: + +```sh +mudling plugin test plugins/mygame +``` + +Each `caught` line shows how many lines a pattern matched. Each `fail` line says +what's wrong. The last line is `passed` or `failed`. + +## 5. Choose a license + +Set `license` in `plugin.toml` to exactly `MIT` or `Apache-2.0`. `mudling plugin +new` starts you on `MIT`. The registry takes nothing else, so that plugins can be +bundled and forked freely. By opening a pull request, you confirm you have the +right to license your plugin that way. + +## 6. Open a pull request + +Add only your plugin's folder, so that review stays quick: + +```sh +git add plugins/mygame +git commit -m "Add the mygame plugin" +git push -u origin add-mygame +``` + +Then open a pull request on GitHub, against `main` of +`Vyttle-LLC/mudling-plugins`. + +If this is your first contribution here, a maintainer may need to approve the +checks before they run. GitHub asks for that on first pull requests. + +## 7. What happens next + +CI runs [these checks](docs/ci.md) and shows your plugin's cost per line in a +comment on the pull request. If a check fails, its log has a `fail :` +line that says why, and [the same page](docs/ci.md#what-a-failure-means) says what +to do. Push a fix to the same branch and CI runs again. + +Once it passes, an owner reviews your plugin. Merged plugins reach players with the +next index, a few minutes later. + +## Updating a plugin + +Open a pull request the same way, and raise `version` in `plugin.toml`, which is +how players learn there's an update. If you'd like to own your game's plugins and +review others' changes to them, say so in the pull request: owners join +`.github/CODEOWNERS` as contributors show up. diff --git a/README.md b/README.md index 20b1ee8..52d9080 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,44 @@ # mudling-plugins -Community plugins for MUDling + +The community plugin registry for [MUDling](https://github.com/Vyttle-LLC/mudling), +a MUD client. Each plugin teaches MUDling about a game: its prompts, its tables, +its map, its gear. MUDling's plugin directory (Settings › Plugins › Browse) lists +what's here. + +To add a plugin, read [CONTRIBUTING.md](CONTRIBUTING.md). It goes from +`mudling plugin new` to an open pull request. + +## What's in this repo + +| Path | What it is | +| --- | --- | +| `plugins//` | One folder per plugin. | +| `.github/CODEOWNERS` | Who reviews what. | +| `ci/` | The checks every pull request goes through, and their tests. | +| `docs/ci.md` | What each check does, and why a failure happened. | +| `docs/index-format.md` | The signed index that the app reads. | +| `docs/signing.md` | The signing key, and how to set or replace it. | + +## The rules + +- **One folder per plugin:** `plugins//`, named for the plugin's `id`. +- **MIT or Apache-2.0 only,** so a plugin can be bundled and forked freely. +- **Every plugin ships tests:** a few lines of made-up game text, and what they + should produce. +- **No session logs.** They hold other players' chat. Write test text by hand. +- **CI runs first.** It checks the manifest, the patterns, the plugin's tests, its + cost per line and its Luau, before anyone reviews the pull request. +- **Then a person reviews it:** an owner from `CODEOWNERS`, Michael to begin with. + Owners for each game join as contributors show up. + +## How a plugin reaches players + +When a pull request merges to `main`, CI checks everything again and builds an +index with one entry per plugin. It signs the index and publishes it to the +`index` branch, and MUDling reads it from there. Nothing in the app trusts an +index that doesn't verify. + +## License + +The repo itself is [MIT](LICENSE). Each plugin carries the license its +`plugin.toml` names: MIT or Apache-2.0. diff --git a/ci/fixtures/fixture/greet.luau b/ci/fixtures/fixture/greet.luau new file mode 100644 index 0000000..f3bf791 --- /dev/null +++ b/ci/fixtures/fixture/greet.luau @@ -0,0 +1,3 @@ +function on_welcome(event) + Shared.remember(event.captures.name) +end diff --git a/ci/fixtures/fixture/plugin.toml b/ci/fixtures/fixture/plugin.toml new file mode 100644 index 0000000..7a0c9c0 --- /dev/null +++ b/ci/fixtures/fixture/plugin.toml @@ -0,0 +1,20 @@ +# CI's own test plugin: it passes every check. ci/test_registry.py copies it and +# breaks one thing at a time. +id = "fixture" +name = "Fixture" +version = "1.0.0" +api = 1 +license = "MIT" +layer = "game" +permissions = ["write_store:character"] + +[servers] +hosts = ["fixture.example"] +mssp_names = ["Fixture"] + +[points] +text = "text.toml" + +[hooks] +# shared.luau first: greet.luau uses the Shared table it defines. +files = ["shared.luau", "greet.luau"] diff --git a/ci/fixtures/fixture/shared.luau b/ci/fixtures/fixture/shared.luau new file mode 100644 index 0000000..43743ff --- /dev/null +++ b/ci/fixtures/fixture/shared.luau @@ -0,0 +1,5 @@ +Shared = {} + +function Shared.remember(name) + mud.store("character", "name", name) +end diff --git a/ci/fixtures/fixture/tests/sample.expected b/ci/fixtures/fixture/tests/sample.expected new file mode 100644 index 0000000..4dead74 --- /dev/null +++ b/ci/fixtures/fixture/tests/sample.expected @@ -0,0 +1,2 @@ +event text character.welcome name="Ana" +store character name "Ana" diff --git a/ci/fixtures/fixture/tests/sample.txt b/ci/fixtures/fixture/tests/sample.txt new file mode 100644 index 0000000..5f083b3 --- /dev/null +++ b/ci/fixtures/fixture/tests/sample.txt @@ -0,0 +1,3 @@ +[connected] +Welcome back, Ana. +Bo says 'nice weather' diff --git a/ci/fixtures/fixture/text.toml b/ci/fixtures/fixture/text.toml new file mode 100644 index 0000000..faa8542 --- /dev/null +++ b/ci/fixtures/fixture/text.toml @@ -0,0 +1,5 @@ +# "Welcome back, Ana." +[[pattern]] +name = "character.welcome" +pattern = '''^Welcome back, (?\w+)\.$''' +hook = "on_welcome" diff --git a/ci/install-luau.sh b/ci/install-luau.sh new file mode 100755 index 0000000..7dba63e --- /dev/null +++ b/ci/install-luau.sh @@ -0,0 +1,12 @@ +#!/bin/sh +# Downloads the pinned luau-analyze into $1 and checks it against its hash. +# Reads LUAU_VERSION and LUAU_UBUNTU_SHA256 from the environment. +set -eu + +folder=$1 +mkdir -p "$folder" +curl --fail --silent --show-error --location --output "$folder/luau.zip" \ + "https://github.com/luau-lang/luau/releases/download/$LUAU_VERSION/luau-ubuntu.zip" +echo "$LUAU_UBUNTU_SHA256 $folder/luau.zip" | sha256sum --check --quiet +unzip -q -o "$folder/luau.zip" luau-analyze -d "$folder" +chmod +x "$folder/luau-analyze" diff --git a/ci/load-pins.sh b/ci/load-pins.sh new file mode 100755 index 0000000..384e52f --- /dev/null +++ b/ci/load-pins.sh @@ -0,0 +1,11 @@ +#!/bin/sh +# Hands ci/pins.env to the rest of the job, and stops it plainly if the MUDling +# commit hasn't been set to a real one. +set -eu + +grep -v '^#' ci/pins.env >>"$GITHUB_ENV" +commit=$(sed -n 's/^MUDLING_COMMIT=//p' ci/pins.env) +if ! printf '%s' "$commit" | grep -Eq '^[0-9a-f]{40}$'; then + echo "::error file=ci/pins.env::MUDLING_COMMIT is '$commit'. Set it to a full commit on Vyttle-LLC/mudling that has mudling plugin test." + exit 1 +fi diff --git a/ci/luaurc b/ci/luaurc new file mode 100644 index 0000000..057c683 --- /dev/null +++ b/ci/luaurc @@ -0,0 +1,7 @@ +{ + "languageMode": "nonstrict", + "lint": { "FunctionUnused": false }, + "lintErrors": true, + "typeErrors": true, + "globals": ["mud"] +} diff --git a/ci/pins.env b/ci/pins.env new file mode 100644 index 0000000..ffaf549 --- /dev/null +++ b/ci/pins.env @@ -0,0 +1,11 @@ +# The versions CI builds and downloads. One line each, because the workflows +# read this file as KEY=value. +# +# The MUDling commit that CI builds `mudling plugin test` from. It must be a +# full commit on Vyttle-LLC/mudling that has those tools. Change it when the +# plugin API or the tools change, and check the reference plugin afterwards: +# docs/ci.md#the-budget. +MUDLING_COMMIT=1282f8a293c3fed12c19d75c28cd849b117ce76f +# luau-analyze, from the release's luau-ubuntu.zip on luau-lang/luau. +LUAU_VERSION=0.745 +LUAU_UBUNTU_SHA256=186e5ddaa2b048ebc7390c11ed1b00c04e7d3beaffed429250329e3575d2ece2 diff --git a/ci/post-budget-comment.sh b/ci/post-budget-comment.sh new file mode 100755 index 0000000..31e17f3 --- /dev/null +++ b/ci/post-budget-comment.sh @@ -0,0 +1,26 @@ +#!/bin/sh +# Puts the budget comment in $1 on the open pull request for the branch that CI +# ran on, replacing the last one. Reads HEAD_OWNER, HEAD_BRANCH and HEAD_SHA, +# which come from GitHub's record of the run, never from the run's own files. +set -eu + +body=$1 +if [ ! -s "$body" ]; then + echo "No budget to show." + exit 0 +fi +number=$(gh api --method GET "repos/$GITHUB_REPOSITORY/pulls" \ + --field "head=$HEAD_OWNER:$HEAD_BRANCH" --field state=open \ + --jq ".[] | select(.head.sha == \"$HEAD_SHA\") | .number") +if [ -z "$number" ]; then + echo "No open pull request for $HEAD_SHA: it has probably moved on." + exit 0 +fi +existing=$(gh api --paginate "repos/$GITHUB_REPOSITORY/issues/$number/comments" \ + --jq '.[] | select(.user.login == "github-actions[bot]" and (.body | startswith(""))) | .id' | + head -n 1) +if [ -n "$existing" ]; then + gh api --method PATCH "repos/$GITHUB_REPOSITORY/issues/comments/$existing" --field "body=@$body" >/dev/null +else + gh api --method POST "repos/$GITHUB_REPOSITORY/issues/$number/comments" --field "body=@$body" >/dev/null +fi diff --git a/ci/publish-index.sh b/ci/publish-index.sh new file mode 100755 index 0000000..d3962e2 --- /dev/null +++ b/ci/publish-index.sh @@ -0,0 +1,21 @@ +#!/bin/sh +# Commits the index at $1 to the `index` branch and pushes it, one commit each +# time. The branch holds nothing else, and the app fetches the file from it. +set -eu + +index=$1 +git config user.name "github-actions[bot]" +git config user.email "41898282+github-actions[bot]@users.noreply.github.com" +if git fetch --depth=1 origin index; then + git switch --create index FETCH_HEAD +else + git switch --orphan index +fi +cp "$index" index.json +git add index.json +if git diff --cached --quiet; then + echo "The index hasn't changed: a re-run of a published commit." + exit 0 +fi +git commit --message "Publish the index for $GITHUB_SHA" +git push origin index diff --git a/ci/reference/plugin.toml b/ci/reference/plugin.toml new file mode 100644 index 0000000..84142e7 --- /dev/null +++ b/ci/reference/plugin.toml @@ -0,0 +1,12 @@ +# Not a plugin for players. CI measures this beside each plugin, on the same +# machine, and judges the plugin against it. It costs about the 5 µs budget on a +# quiet machine: docs/ci.md#the-budget says how to check that. +id = "reference" +name = "Budget reference" +version = "1.0.0" +api = 1 +license = "MIT" +layer = "default" + +[points] +text = "text.toml" diff --git a/ci/reference/text.toml b/ci/reference/text.toml new file mode 100644 index 0000000..30c102b --- /dev/null +++ b/ci/reference/text.toml @@ -0,0 +1,34 @@ +# Each rule matches every line and captures all of it, so it costs on every +# line: about 0.6 µs a rule on the shared log, less on short lines. + +[[pattern]] +name = "reference.one" +pattern = '''(?.*)''' + +[[pattern]] +name = "reference.two" +pattern = '''(?.*)''' + +[[pattern]] +name = "reference.three" +pattern = '''(?.*)''' + +[[pattern]] +name = "reference.four" +pattern = '''(?.*)''' + +[[pattern]] +name = "reference.five" +pattern = '''(?.*)''' + +[[pattern]] +name = "reference.six" +pattern = '''(?.*)''' + +[[pattern]] +name = "reference.seven" +pattern = '''(?.*)''' + +[[pattern]] +name = "reference.eight" +pattern = '''(?.*)''' diff --git a/ci/registry.py b/ci/registry.py new file mode 100755 index 0000000..ff22e70 --- /dev/null +++ b/ci/registry.py @@ -0,0 +1,483 @@ +#!/usr/bin/env python3 +"""The registry's CI: checks plugins, and builds the signed index. + + registry.py check --mudling BIN --luau-analyze BIN --session-log FILE + [--plugins DIR] [--report FILE] + registry.py index --commit SHA --published-at TIME --output FILE + [--plugins DIR] + registry.py comment REPORT + +`check` exits 0 when every plugin passed, 1 when one failed and 2 when it +couldn't run. `mudling plugin test` does the loading and replaying; +docs/plugins/reference.md in the MUDling repo is the contract for its output. +docs/ci.md explains each check, and docs/index-format.md the index. + +Standard library only, plus `openssl` 3 for the signature. `index` never runs +a plugin's code, so the signing key is never near it. +""" + +import argparse +import base64 +import dataclasses +import hashlib +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +import tomllib +from dataclasses import dataclass +from pathlib import Path + +CI_FOLDER = Path(__file__).parent +REFERENCE_PLUGIN = CI_FOLDER / "reference" +LUAU_CONFIG = CI_FOLDER / "luaurc" + +LICENSES = ("MIT", "Apache-2.0") +INDEX_FORMAT = 1 +SIGNING_KEY_VARIABLE = "INDEX_SIGNING_KEY" +BUDGET_DOCS = "https://github.com/Vyttle-LLC/mudling-plugins/blob/main/docs/ci.md#the-budget" + +# The budget is judged as `mudling-bench compare` judges a build: both sides +# run in turns on one machine, each block compares the lowest value each side +# reached, and a plugin is over only if it loses in every block. +MOST_OVER_REFERENCE = 1.10 +ROUNDS_PER_BLOCK = 3 +BLOCKS = 3 + +FAIL_LINE = re.compile(r"fail (\w+): (.*)") +COST_LINE = re.compile( + r"(?:cost |fail budget: )\+(-?[\d.]+) µs a line at p99 " + r"\(([\d.]+) with, [\d.]+ without\), budget [\d.]+ µs" +) +LUAU_FINDING = re.compile(r"\./hooks\.luau\((\d+),(\d+)\): (.*)") +PLUGIN_ID = re.compile(r"[a-z0-9][a-z0-9._-]*") +SAFE_NAME = re.compile(r"[A-Za-z0-9._-]+") +PLUGINS_README = "README.md" + + +class CouldNotRun(Exception): + """A tool failed in a way that says nothing about the plugin.""" + + +@dataclass +class Tools: + mudling: Path + luau_analyze: Path + session_log: Path + reference: Path = REFERENCE_PLUGIN + + +@dataclass +class Failure: + kind: str + detail: str + + +@dataclass +class Cost: + added_us: float + with_us: float + + +@dataclass +class Budget: + """One log's verdict: the plugin's cost against the reference's.""" + + log: str + plugin: Cost + reference: Cost + within: bool + + @property + def ratio(self) -> float: + return self.plugin.with_us / self.reference.with_us + + +@dataclass +class Result: + id: str + failures: list[Failure] + budget: Budget | None = None + + +def read_manifest(folder: Path) -> dict | None: + """The manifest, or None if there's none to read: loading then says why.""" + try: + return tomllib.loads((folder / "plugin.toml").read_text()) + except (OSError, UnicodeDecodeError, tomllib.TOMLDecodeError): + return None + + +def shown(text: str) -> str: + """Text from a plugin as one printable line, whatever it holds.""" + return text if text.isascii() and text.isprintable() else ascii(text) + + +def check_layout(folder: Path, manifest: dict | None) -> list[Failure]: + """Refuses what could mislead a tool. Names are limited because `plugin test` + prints paths and the content hash lists them, one per line.""" + if folder.is_symlink(): + return [Failure("layout", f"{shown(folder.name)} is a symbolic link")] + failures = [] + if manifest is not None and manifest.get("id") != folder.name: + found = f"the folder is {shown(folder.name)} but the id is {shown(str(manifest.get('id')))}" + failures.append(Failure("layout", found)) + for path in [folder, *sorted(folder.rglob("*"))]: + name = shown(str(path.relative_to(folder.parent))) + if not SAFE_NAME.fullmatch(path.name): + failures.append(Failure("layout", f"{name}: a name may use only ASCII letters, digits, ., _ and -")) + if path.is_symlink(): + failures.append(Failure("layout", f"{name} is a symbolic link")) + if path.suffix.lower() == ".log": + failures.append( + Failure("layout", f"{name}: session logs hold other players' chat, so they never go in the registry") + ) + # Lowercased, because a case-insensitive checkout reads any casing. + if path.name.lower() == ".gitattributes": + failures.append( + Failure( + "layout", + f"{name}: a plugin can't carry .gitattributes, because it changes the bytes a checkout" + " holds, so the app's content hash wouldn't match CI's", + ) + ) + return failures + + +def check_stray_files(plugins: Path) -> list[Result]: + """Only folders go directly under `plugins/`, beside its README.""" + return [ + Result(shown(path.name), [Failure("layout", "only plugin folders go directly under plugins/")]) + for path in sorted(plugins.iterdir()) + if not path.is_dir() and path.name != PLUGINS_README + ] + + +def check_license(manifest: dict | None) -> list[Failure]: + if manifest is None or manifest.get("license") in LICENSES: + return [] + wanted = " or ".join(LICENSES) + return [Failure("license", f"the license is {manifest.get('license')}, and must be {wanted}")] + + +def plugin_test(tools: Tools, folder: Path, log: Path | None = None) -> list[str]: + """The lines of `mudling plugin test`. Exit 1 is a verdict, so it's fine. + + Output echoes a log's text, so only `\\n` ends a line. `text=True` and + `splitlines` would end one at characters a log can hold, and a log could + then print a cost of its own. + """ + command = [tools.mudling, "plugin", "test", folder] + if log is not None: + command += ["--log", log] + run = subprocess.run(command, capture_output=True) + lines = run.stdout.decode(errors="replace").removesuffix("\n").split("\n") + if run.returncode not in (0, 1) or lines[-1] not in ("passed", "failed"): + stderr = run.stderr.decode(errors="replace").strip() + raise CouldNotRun(f"mudling plugin test {folder} exited {run.returncode}: {stderr}") + return lines + + +def load_failure_kind(reason: str) -> str: + if "the pattern doesn't compile" in reason: + return "pattern" + if "the Luau doesn't compile" in reason: + return "lint" + return "manifest" + + +def test_failures(lines: list[str]) -> list[Failure]: + """What `plugin test` failed for, leaving out its absolute budget. + + `mudling plugin test` holds a line to 5 µs on whatever machine it's on. A + shared runner can't be trusted with that, so `check_budget` judges the cost + against the reference instead. A hook that overran is no timing of the + machine's, so it still fails here. + """ + failures = [] + for line in lines: + found = FAIL_LINE.fullmatch(line) + if found is None or COST_LINE.fullmatch(line): + continue + kind, reason = found.groups() + failures.append(Failure(load_failure_kind(reason) if kind == "load" else kind, reason)) + return failures + + +def lint_hooks(tools: Tools, folder: Path, hook_files: list[str]) -> list[Failure]: + """Lints the hooks with luau-analyze, under the registry's own config. + + The files load into one VM, so they're linted as one: a global from an + earlier file is known to a later one. Findings name the plugin's own files. + """ + if not hook_files: + return [] + combined, starts = [], [] + for name in hook_files: + lines = (folder / name).read_text().splitlines() + starts.append((len(combined), name)) + combined += lines + with tempfile.TemporaryDirectory() as scratch: + shutil.copy(LUAU_CONFIG, Path(scratch) / ".luaurc") + (Path(scratch) / "hooks.luau").write_text("\n".join(combined) + "\n") + run = subprocess.run( + [tools.luau_analyze, "hooks.luau"], cwd=scratch, capture_output=True, text=True + ) + failures = [] + for line in (run.stdout + run.stderr).splitlines(): + found = LUAU_FINDING.fullmatch(line) + if found is None: + raise CouldNotRun(f"luau-analyze said: {line}") + at, column, message = int(found[1]) - 1, found[2], found[3] + start, name = [entry for entry in starts if entry[0] <= at][-1] + failures.append(Failure("lint", f"{name}:{at - start + 1}:{column}: {message}")) + if run.returncode != 0 and not failures: + raise CouldNotRun(f"luau-analyze exited {run.returncode} and said nothing") + return failures + + +def read_cost(lines: list[str]) -> Cost: + """The last cost line: only text from a log or a path can come before it.""" + for line in reversed(lines): + found = COST_LINE.fullmatch(line) + if found is not None: + return Cost(float(found[1]), float(found[2])) + raise CouldNotRun("mudling plugin test printed no cost") + + +def judge_budget(log: str, measure_plugin, measure_reference) -> Budget: + """Both sides in turns: `plugin` is over only if it loses in every block.""" + for _ in range(BLOCKS): + plugin_costs, reference_costs = [], [] + for round_number in range(ROUNDS_PER_BLOCK): + # In turns, so neither always runs first. + if round_number % 2 == 0: + plugin_costs.append(measure_plugin()) + reference_costs.append(measure_reference()) + else: + reference_costs.append(measure_reference()) + plugin_costs.append(measure_plugin()) + plugin = min(plugin_costs, key=lambda cost: cost.with_us) + reference = min(reference_costs, key=lambda cost: cost.with_us) + if plugin.with_us <= reference.with_us * MOST_OVER_REFERENCE: + return Budget(log, plugin, reference, within=True) + return Budget(log, plugin, reference, within=False) + + +def check_budget(tools: Tools, folder: Path) -> Budget: + """The worst verdict over the plugin's own logs and the shared session log. + + The shared log means a plugin can't look cheap by testing on three lines. + """ + logs = [*sorted((folder / "tests").glob("*.txt")), tools.session_log] + budgets = [ + judge_budget( + log.name, + lambda log=log: read_cost(plugin_test(tools, folder, log)), + lambda log=log: read_cost(plugin_test(tools, tools.reference, log)), + ) + for log in logs + ] + return max(budgets, key=lambda budget: (not budget.within, budget.ratio)) + + +def check_plugin(tools: Tools, folder: Path) -> Result: + manifest = read_manifest(folder) + plugin_id = shown(folder.name) + layout_problems = check_layout(folder, manifest) + failures = layout_problems + check_license(manifest) + if layout_problems: + return Result(plugin_id, failures) # Nothing runs a plugin laid out like this. + + test_problems = test_failures(plugin_test(tools, folder)) + failures += test_problems + if any(failure.kind in ("manifest", "pattern", "lint") for failure in test_problems): + return Result(plugin_id, failures) # It didn't load, so nothing else can run. + + hook_files = manifest.get("hooks", {}).get("files", []) + failures += lint_hooks(tools, folder, hook_files) + # `plugin test` covered its own logs; a hook must survive the shared one too. + failures += test_failures(plugin_test(tools, folder, tools.session_log)) + budget = check_budget(tools, folder) + if not budget.within: + limit = f"{MOST_OVER_REFERENCE:.2f}" + failures.append( + Failure( + "budget", + f"on {budget.log}, {budget.ratio:.2f}× the reference's cost a line, and the limit is {limit}×", + ) + ) + return Result(plugin_id, failures, budget) + + +def plugin_folders(plugins: Path) -> list[Path]: + return sorted(path for path in plugins.iterdir() if path.is_dir()) + + +def render_budget_table(results: list[dict]) -> str: + """The budget, from a report. A pull request can forge the report, and this + goes on the pull request, so only ids and numbers get through.""" + rows = [ + "| Plugin | Added a line | Reference added | Against the reference | Limit | Log |", + "| --- | ---: | ---: | ---: | ---: | --- |", + ] + for result in results: + budget = result.get("budget") + if budget is None or not PLUGIN_ID.fullmatch(result["id"]): + continue + plugin, reference = budget["plugin"], budget["reference"] + ratio = float(plugin["with_us"]) / float(reference["with_us"]) + log = budget["log"] if PLUGIN_ID.fullmatch(budget["log"]) else "(not shown)" + rows.append( + f"| {result['id']} | +{float(plugin['added_us']):.2f} µs | +{float(reference['added_us']):.2f} µs" + f" | {ratio:.2f}× | {MOST_OVER_REFERENCE:.2f}× | {log} |" + ) + return "\n".join(rows) if len(rows) > 2 else "" + + +def budget_comment(report: Path) -> str: + table = render_budget_table(json.loads(report.read_text())) + if not table: + return "" + return ( + "\n" + "### Line budget\n\n" + f"{table}\n\n" + "These are this runner's numbers, measured in one job beside a reference plugin that costs " + "about the 5 µs budget on a quiet machine. Only the comparison with the reference counts: " + f"see [the budget]({BUDGET_DOCS})." + ) + + +def run_check(args: argparse.Namespace) -> bool: + tools = Tools(args.mudling.resolve(), args.luau_analyze.resolve(), args.session_log.resolve()) + results = check_stray_files(args.plugins) + results += [check_plugin(tools, folder) for folder in plugin_folders(args.plugins)] + for result in results: + for failure in result.failures: + print(f"fail {result.id} {failure.kind}: {failure.detail}") + if not result.failures: + print(f"passed {result.id}") + print(f"{len(results)} entries under plugins/ checked") + report = [dataclasses.asdict(result) for result in results] + if args.report is not None: + args.report.write_text(json.dumps(report, indent=2)) + table = render_budget_table(report) + summary = os.environ.get("GITHUB_STEP_SUMMARY") + if summary and table: + with open(summary, "a") as file: + file.write(f"### Line budget\n\n{table}\n") + return not any(result.failures for result in results) + + +def content_hash(folder: Path) -> str: + """Hashes a folder's relative paths and contents: docs/index-format.md.""" + files = sorted(path.relative_to(folder).as_posix() for path in folder.rglob("*") if path.is_file()) + listing = "".join( + f"{hashlib.sha256((folder / name).read_bytes()).hexdigest()} {name}\n" for name in files + ) + return "sha256:" + hashlib.sha256(listing.encode()).hexdigest() + + +def index_entry(folder: Path) -> dict: + manifest = tomllib.loads((folder / "plugin.toml").read_text()) + servers = manifest.get("servers", {}) + return { + "id": manifest["id"], + "name": manifest["name"], + "version": manifest["version"], + "license": manifest["license"], + "games": { + "hosts": servers.get("hosts", []), + "mssp_names": servers.get("mssp_names", []), + }, + "source": f"plugins/{folder.name}", + "hash": content_hash(folder), + } + + +def sign(payload: bytes, private_key_pem: str) -> str: + """The base64 Ed25519 signature of `payload`.""" + with tempfile.TemporaryDirectory() as scratch: + key, message, signature = (Path(scratch) / name for name in ("key", "message", "signature")) + key.write_text(private_key_pem) + message.write_bytes(payload) + subprocess.run( + ["openssl", "pkeyutl", "-sign", "-rawin", "-inkey", key, "-in", message, "-out", signature], + check=True, + capture_output=True, + ) + return base64.b64encode(signature.read_bytes()).decode() + + +def build_index(plugins: Path, commit: str, published_at: str, private_key_pem: str) -> str: + signed = json.dumps( + { + "format": INDEX_FORMAT, + "commit": commit, + "published_at": published_at, + "plugins": [index_entry(folder) for folder in plugin_folders(plugins)], + }, + ensure_ascii=False, + indent=2, + ) + signature = sign(signed.encode(), private_key_pem) + return json.dumps({"signed": signed, "signature": signature}, ensure_ascii=False, indent=2) + "\n" + + +def run_index(args: argparse.Namespace) -> bool: + private_key_pem = os.environ.get(SIGNING_KEY_VARIABLE) + if not private_key_pem: + raise CouldNotRun( + f"the {SIGNING_KEY_VARIABLE} secret isn't set, so no index was signed: see docs/signing.md" + ) + args.output.write_text(build_index(args.plugins, args.commit, args.published_at, private_key_pem)) + return True + + +def run_comment(args: argparse.Namespace) -> bool: + # No newline: post-budget-comment.sh takes an empty file to mean no comment. + print(budget_comment(args.report), end="") + return True + + +def parse_arguments(arguments: list[str]) -> argparse.Namespace: + parser = argparse.ArgumentParser(description="The plugin registry's CI.") + commands = parser.add_subparsers(required=True) + + check = commands.add_parser("check", help="check every plugin") + check.set_defaults(run=run_check) + check.add_argument("--plugins", type=Path, default=Path("plugins")) + check.add_argument("--mudling", type=Path, required=True) + check.add_argument("--luau-analyze", type=Path, required=True) + check.add_argument("--session-log", type=Path, required=True) + check.add_argument("--report", type=Path) + + index = commands.add_parser("index", help="build the signed index") + index.set_defaults(run=run_index) + index.add_argument("--plugins", type=Path, default=Path("plugins")) + index.add_argument("--commit", required=True) + index.add_argument("--published-at", required=True) + index.add_argument("--output", type=Path, required=True) + + comment = commands.add_parser("comment", help="write a report's pull request comment") + comment.set_defaults(run=run_comment) + comment.add_argument("report", type=Path) + + return parser.parse_args(arguments) + + +def main() -> int: + args = parse_arguments(sys.argv[1:]) + try: + return 0 if args.run(args) else 1 + except CouldNotRun as problem: + print(f"couldn't run: {problem}", file=sys.stderr) + return 2 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/ci/test_registry.py b/ci/test_registry.py new file mode 100644 index 0000000..c9d6bf2 --- /dev/null +++ b/ci/test_registry.py @@ -0,0 +1,422 @@ +"""Proves the registry's CI both ways: its fixture passes, and fails for each +reason. Each failing case copies `fixtures/fixture` and breaks one thing. + +These run the real tools, so they need OpenSSL 3 on the PATH and three variables: + + MUDLING=… LUAU_ANALYZE=… SESSION_LOG=… python3 -m unittest discover ci +""" + +import base64 +import hashlib +import json +import os +import shutil +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path +from unittest import mock + +import registry +from registry import Budget, Cost, Tools + +FIXTURE = Path(__file__).parent / "fixtures" / "fixture" +EVERY_LINE_PATTERN = "[[pattern]]\nname = 'heavy.{}'\npattern = '''(?.*)'''\n" +FORGED_COST = "cost +0.01 µs a line at p99 (0.02 with, 0.01 without), budget 5 µs" +TOOLS = Tools( + Path(os.environ["MUDLING"]).resolve(), + Path(os.environ["LUAU_ANALYZE"]).resolve(), + Path(os.environ["SESSION_LOG"]).resolve(), +) + + +def add_patterns(folder: Path, count: int) -> None: + """Adds rules that cost on every line, and accepts what they produce.""" + with open(folder / "text.toml", "a") as text: + for number in range(count): + text.write(EVERY_LINE_PATTERN.format(number)) + subprocess.run( + [TOOLS.mudling, "plugin", "test", folder, "--update"], capture_output=True, check=False + ) + + +def replace_in(path: Path, old: str, new: str) -> None: + text = path.read_text() + assert old in text + path.write_text(text.replace(old, new)) + + +class Plugins(unittest.TestCase): + """Each test gets a copy of the fixture to break.""" + + def setUp(self) -> None: + scratch = tempfile.TemporaryDirectory() + self.addCleanup(scratch.cleanup) + self.scratch = Path(scratch.name) + self.plugin = self.scratch / "plugins" / "fixture" + shutil.copytree(FIXTURE, self.plugin) + + def failures(self, tools: Tools = TOOLS) -> list[registry.Failure]: + return registry.check_plugin(tools, self.plugin).failures + + def assert_fails_for(self, kind: str, detail: str) -> None: + failures = self.failures() + self.assertEqual({failure.kind for failure in failures}, {kind}, failures) + self.assertIn(detail, failures[0].detail) + + +class Passes(Plugins): + def test_the_fixture_passes(self) -> None: + result = registry.check_plugin(TOOLS, self.plugin) + self.assertEqual(result.failures, []) + self.assertTrue(result.budget.within) + + def test_apache_2_passes(self) -> None: + replace_in(self.plugin / "plugin.toml", '"MIT"', '"Apache-2.0"') + self.assertEqual(self.failures(), []) + + def test_what_mudling_plugin_new_makes_passes(self) -> None: + subprocess.run( + [TOOLS.mudling, "plugin", "new", "newgame", "--dir", self.scratch], + check=True, + capture_output=True, + ) + self.plugin = self.scratch / "newgame" + self.assertEqual(self.failures(), []) + + def test_over_five_microseconds_on_a_slow_machine_is_no_failure(self) -> None: + """A reference that also costs more stands for a slow runner: the plugin + fails `plugin test`'s absolute budget here, and only the comparison counts.""" + add_patterns(self.plugin, 24) + output = registry.plugin_test(TOOLS, self.plugin) + self.assertTrue(any(line.startswith("fail budget: +") for line in output), output) + slow_runner = self.scratch / "slow-runner" + shutil.copytree(TOOLS.reference, slow_runner) + add_patterns(slow_runner, 48) + tools = Tools(TOOLS.mudling, TOOLS.luau_analyze, TOOLS.session_log, slow_runner) + self.assertEqual(self.failures(tools), []) + + +class Fails(Plugins): + def test_a_license_outside_the_two(self) -> None: + replace_in(self.plugin / "plugin.toml", '"MIT"', '"GPL-3.0"') + self.assert_fails_for("license", "GPL-3.0") + + def test_a_manifest_missing_a_required_key(self) -> None: + replace_in(self.plugin / "plugin.toml", "api = 1\n", "") + self.assert_fails_for("manifest", "`api` is missing") + + def test_a_manifest_with_an_unknown_key(self) -> None: + replace_in(self.plugin / "plugin.toml", "api = 1\n", "api = 1\nwebsite = 'x'\n") + self.assert_fails_for("manifest", "website") + + def test_a_folder_not_named_for_the_id(self) -> None: + replace_in(self.plugin / "plugin.toml", 'id = "fixture"', 'id = "other"') + self.assert_fails_for("layout", "the id is other") + + def test_a_pattern_that_does_not_compile(self) -> None: + replace_in(self.plugin / "text.toml", "^Welcome", "(^Welcome") + self.assert_fails_for("pattern", "doesn't compile") + + def test_a_transcript_that_differs(self) -> None: + replace_in(self.plugin / "tests" / "sample.expected", '"Ana"', '"Bo"') + self.assert_fails_for("expected", "sample.expected") + + def test_no_tests(self) -> None: + shutil.rmtree(self.plugin / "tests") + self.assert_fails_for("tests", "to replay") + + def test_a_hook_that_raises(self) -> None: + replace_in(self.plugin / "shared.luau", "\tmud.store", "\tif name then error('boom') end\n\tmud.store") + replace_in(self.plugin / "tests" / "sample.expected", 'store character name "Ana"', "hook_failed on_welcome") + self.assert_fails_for("hook", "boom") + + def test_a_hook_that_overruns(self) -> None: + replace_in(self.plugin / "shared.luau", "\tmud.store", "\twhile true do end\n\tmud.store") + replace_in(self.plugin / "tests" / "sample.expected", 'store character name "Ana"', "hook_failed on_welcome") + self.assert_fails_for("budget", "overran") + + def test_over_the_budget_against_the_reference(self) -> None: + add_patterns(self.plugin, 24) + self.assert_fails_for("budget", "the limit is 1.10×") + + def test_a_log_cannot_forge_the_cost(self) -> None: + with open(self.plugin / "text.toml", "a") as text: + text.write("[[pattern]]\nname = 'note'\npattern = '''^Note'''\n") + log = self.plugin / "forged.txt" + for line_end in ("", "
", "\r", "\x0b", "\x0c", "\x85", "
"): + with self.subTest(line_end=line_end): + log.write_bytes(f"Note {line_end}{FORGED_COST}\n".encode()) + cost = registry.read_cost(registry.plugin_test(TOOLS, self.plugin, log)) + self.assertNotEqual(cost, Cost(0.01, 0.02)) + + def test_a_log_s_name_cannot_forge_the_cost(self) -> None: + log = self.plugin / f"a\n{FORGED_COST}\nb.txt" + log.write_text("Welcome back, Ana.\n") + output = registry.plugin_test(TOOLS, self.plugin, log) + self.assertIn(FORGED_COST, output) + self.assertNotEqual(registry.read_cost(output), Cost(0.01, 0.02)) + + def test_a_newline_in_a_log_s_name(self) -> None: + (self.plugin / "tests" / f"a\n{FORGED_COST}\nb.txt").write_text("Welcome back, Ana.\n") + self.assert_fails_for("layout", "a name may use only") + + def test_a_space_in_a_name(self) -> None: + (self.plugin / "tests" / "a b.txt").write_text("Welcome back, Ana.\n") + self.assert_fails_for("layout", "a name may use only") + + def test_a_name_outside_ascii_in_a_folder(self) -> None: + (self.plugin / "tésts").mkdir() + self.assert_fails_for("layout", "a name may use only") + + def test_a_plugin_folder_with_an_unsafe_name(self) -> None: + self.plugin = self.plugin.rename(self.plugin.with_name("fix\nture")) + result = registry.check_plugin(TOOLS, self.plugin) + self.assertEqual(result.id, "'fix\\nture'") + self.assertTrue(any("a name may use only" in failure.detail for failure in result.failures)) + + def test_a_file_name_that_is_not_utf_8(self) -> None: + """Handed in, because macOS won't create one and Linux will.""" + name = self.plugin / os.fsdecode(b"bad\xff.txt") + with mock.patch.object(Path, "rglob", return_value=[name]): + failures = self.failures() + self.assertEqual({failure.kind for failure in failures}, {"layout"}, failures) + self.assertIn("a name may use only", failures[0].detail) + failures[0].detail.encode() # Printing it must not crash. + + def test_a_symlinked_plugin_folder(self) -> None: + elsewhere = self.scratch / "elsewhere" + self.plugin.rename(elsewhere) + self.plugin.symlink_to(elsewhere, target_is_directory=True) + self.assert_fails_for("layout", "fixture is a symbolic link") + + def test_stray_files_under_plugins(self) -> None: + plugins = self.plugin.parent + (plugins / "README.md").write_text("Allowed.\n") + (plugins / "notes.txt").write_text("Not allowed.\n") + (plugins / "link").symlink_to("/etc/hosts") + strays = [result.id for result in registry.check_stray_files(plugins)] + self.assertEqual(strays, ["link", "notes.txt"]) + + def test_a_hook_that_raises_only_on_the_shared_log(self) -> None: + self.add_hook_on_shared_text("error('boom')") + self.assert_fails_for("hook", "boom") + + def test_a_hook_that_overruns_only_on_the_shared_log(self) -> None: + self.add_hook_on_shared_text("while true do end") + self.assert_fails_for("budget", "overran") + + def add_hook_on_shared_text(self, body: str) -> None: + """A hook on text that the shared log has and the fixture's own log hasn't.""" + with open(self.plugin / "text.toml", "a") as text: + text.write("[[pattern]]\nname = 'rat'\npattern = '''cave rat'''\nhook = 'on_rat'\n") + (self.plugin / "rat.luau").write_text(f"function on_rat(event)\n\t{body}\nend\n") + replace_in(self.plugin / "plugin.toml", '"greet.luau"]', '"greet.luau", "rat.luau"]') + + def test_a_luau_lint_finding_names_the_plugin_s_own_file_and_line(self) -> None: + replace_in(self.plugin / "greet.luau", "\tShared", "\tlocal unused = 1\n\tShared") + self.assert_fails_for("lint", "greet.luau:2:8: LocalUnused") + + def test_a_plugin_s_own_luau_config_changes_nothing(self) -> None: + (self.plugin / ".luaurc").write_text('{"lint": {"*": false}}') + replace_in(self.plugin / "greet.luau", "\tShared", "\tlocal unused = 1\n\tShared") + self.assert_fails_for("lint", "LocalUnused") + + def test_luau_that_does_not_compile(self) -> None: + replace_in(self.plugin / "greet.luau", "function on_welcome(event)", "function on_welcome(event") + self.assert_fails_for("lint", "doesn't compile") + + def test_a_gitattributes_file_anywhere_in_the_plugin(self) -> None: + for place in ("", "tests"): + with self.subTest(place=place or "the plugin's folder"): + attributes = self.plugin / place / ".gitattributes" + attributes.write_text("*.txt text eol=crlf\n") + self.assert_fails_for("layout", "can't carry .gitattributes") + attributes.unlink() + + def test_a_session_log(self) -> None: + (self.plugin / "tests" / "session.log").write_text("Bo tells you 'hi'\n") + self.assert_fails_for("layout", "session.log") + + def test_a_symbolic_link(self) -> None: + (self.plugin / "escape").symlink_to("/etc/hosts") + self.assert_fails_for("layout", "escape") + + +class Budgets(unittest.TestCase): + @staticmethod + def measures(*with_us: float): + costs = iter(with_us) + return lambda: Cost(0.0, next(costs)) + + def test_one_block_within_is_within(self) -> None: + plugin = self.measures(20, 9, 20, 9, 9, 9) + reference = self.measures(10, 10, 10, 10, 10, 10) + self.assertTrue(registry.judge_budget("log", plugin, reference).within) + + def test_over_only_when_it_loses_every_block(self) -> None: + plugin = self.measures(*[12] * 9) + reference = self.measures(*[10] * 9) + self.assertFalse(registry.judge_budget("log", plugin, reference).within) + + def test_each_block_compares_the_lowest_of_each_side(self) -> None: + plugin = self.measures(30, 10, 30) + reference = self.measures(40, 10, 40) + budget = registry.judge_budget("log", plugin, reference) + self.assertEqual((budget.within, budget.ratio), (True, 1.0)) + + def test_a_cost_over_the_absolute_budget_is_read_like_one_within_it(self) -> None: + within = "cost +1.50 µs a line at p99 (1.75 with, 0.25 without), budget 5 µs" + over = "fail budget: +9.50 µs a line at p99 (9.75 with, 0.25 without), budget 5 µs" + self.assertEqual(registry.read_cost([within]), Cost(1.5, 1.75)) + self.assertEqual(registry.read_cost([over]), Cost(9.5, 9.75)) + self.assertEqual(registry.test_failures([within, over]), []) + + def test_the_last_cost_line_is_the_real_one(self) -> None: + real = "fail budget: +9.50 µs a line at p99 (9.75 with, 0.25 without), budget 5 µs" + self.assertEqual(registry.read_cost([FORGED_COST, real, "failed"]), Cost(9.5, 9.75)) + + +class Comment(unittest.TestCase): + def comment(self, results: list[dict]) -> str: + with tempfile.TemporaryDirectory() as scratch: + report = Path(scratch) / "report.json" + report.write_text(json.dumps(results)) + return registry.budget_comment(report) + + @staticmethod + def result(plugin_id: str = "fixture", log: str = "session.txt") -> dict: + budget = Budget(log, Cost(1.0, 2.0), Cost(5.0, 5.5), True) + return {"id": plugin_id, "budget": registry.dataclasses.asdict(budget)} + + def test_shows_the_numbers(self) -> None: + comment = self.comment([self.result()]) + self.assertIn("| fixture | +1.00 µs | +5.00 µs | 0.36× | 1.10× | session.txt |", comment) + + def test_nothing_measured_is_no_comment(self) -> None: + self.assertEqual(self.comment([{"id": "fixture", "budget": None}]), "") + + def test_nothing_measured_writes_an_empty_file_for_the_post_script(self) -> None: + with tempfile.TemporaryDirectory() as scratch: + report = Path(scratch) / "report.json" + report.write_text("[]") + run = subprocess.run( + [sys.executable, registry.__file__, "comment", report], + capture_output=True, + check=True, + ) + self.assertEqual(run.stdout, b"") + + def test_a_forged_report_gets_no_text_through(self) -> None: + self.assertEqual(self.comment([self.result("![x](http://evil)")]), "") + self.assertNotIn("evil", self.comment([self.result(log="[x](http://evil)")])) + forged = self.result() + forged["budget"]["plugin"]["added_us"] = "[x](http://evil)" + with self.assertRaises(ValueError): + self.comment([forged]) + + +class Index(Plugins): + def setUp(self) -> None: + super().setUp() + self.key = self.scratch / "key.pem" + subprocess.run( + ["openssl", "genpkey", "-algorithm", "ed25519", "-out", self.key], + check=True, + capture_output=True, + ) + + def build(self) -> dict: + text = registry.build_index( + self.plugin.parent, "abc123", "2026-11-01T12:00:00Z", self.key.read_text() + ) + return json.loads(text) + + def test_an_entry_has_what_the_app_reads(self) -> None: + entry = json.loads(self.build()["signed"])["plugins"][0] + self.assertEqual( + {key: entry[key] for key in entry if key != "hash"}, + { + "id": "fixture", + "name": "Fixture", + "version": "1.0.0", + "license": "MIT", + "games": {"hosts": ["fixture.example"], "mssp_names": ["Fixture"]}, + "source": "plugins/fixture", + }, + ) + + def test_the_header_says_what_was_published(self) -> None: + signed = json.loads(self.build()["signed"]) + self.assertEqual( + (signed["format"], signed["commit"], signed["published_at"]), + (1, "abc123", "2026-11-01T12:00:00Z"), + ) + + def test_the_registry_may_be_empty(self) -> None: + shutil.rmtree(self.plugin) + self.assertEqual(json.loads(self.build()["signed"])["plugins"], []) + + def test_the_signature_covers_the_exact_signed_text(self) -> None: + index = self.build() + public_key = self.scratch / "public.pem" + subprocess.run( + ["openssl", "pkey", "-in", self.key, "-pubout", "-out", public_key], + check=True, + capture_output=True, + ) + signature = self.scratch / "signature" + signature.write_bytes(base64.b64decode(index["signature"])) + + def verifies(text: str) -> bool: + message = self.scratch / "message" + message.write_text(text) + run = subprocess.run( + ["openssl", "pkeyutl", "-verify", "-rawin", "-pubin", "-inkey", public_key, + "-in", message, "-sigfile", signature], + capture_output=True, + ) + return run.returncode == 0 + + self.assertTrue(verifies(index["signed"])) + self.assertFalse(verifies(index["signed"].replace("1.0.0", "1.0.1"))) + + def test_a_missing_key_fails_plainly(self) -> None: + args = registry.parse_arguments( + ["index", "--commit", "abc", "--published-at", "now", "--output", str(self.scratch / "out")] + ) + with mock.patch.dict(os.environ, {registry.SIGNING_KEY_VARIABLE: ""}): + with self.assertRaisesRegex(registry.CouldNotRun, "INDEX_SIGNING_KEY secret isn't set"): + registry.run_index(args) + self.assertFalse((self.scratch / "out").exists()) + + +class ContentHash(unittest.TestCase): + def test_matches_the_documented_recipe(self) -> None: + with tempfile.TemporaryDirectory() as scratch: + folder = Path(scratch) + (folder / "tests").mkdir() + (folder / "plugin.toml").write_text("a\n") + (folder / "tests" / "b.txt").write_text("b\n") + + def sha256(text: str) -> str: + return hashlib.sha256(text.encode()).hexdigest() + + first, second = sha256("a\n"), sha256("b\n") + listing = f"{first} plugin.toml\n{second} tests/b.txt\n" + self.assertEqual(registry.content_hash(folder), f"sha256:{sha256(listing)}") + + def test_notices_a_rename_and_an_edit(self) -> None: + with tempfile.TemporaryDirectory() as scratch: + folder = Path(scratch) + (folder / "a").write_text("a\n") + first = registry.content_hash(folder) + (folder / "a").rename(folder / "b") + renamed = registry.content_hash(folder) + (folder / "b").write_text("b\n") + self.assertEqual(len({first, renamed, registry.content_hash(folder)}), 3) + + +if __name__ == "__main__": + unittest.main() diff --git a/docs/ci.md b/docs/ci.md new file mode 100644 index 0000000..b3e52d0 --- /dev/null +++ b/docs/ci.md @@ -0,0 +1,139 @@ +# What CI checks + +`.github/workflows/registry.yml` runs on every pull request and on every push to +`main`. It builds `mudling` from the commit pinned in +[`ci/pins.env`](../ci/pins.env), tests the checks themselves against +[a fixture](../ci/test_registry.py), then runs `ci/registry.py check` over every +folder in `plugins/`. + +| Check | How | `fail` kind | +| --- | --- | --- | +| Only plugin folders sit under `plugins/`, beside its README. Each is named for its `id`. Every file and folder name uses only ASCII letters, digits, `.`, `_` and `-`. There are no symbolic links and no `*.log` files. | `ci/registry.py` | `layout` | +| The license is `MIT` or `Apache-2.0`, exactly. | `ci/registry.py` | `license` | +| The manifest and every other file load. | `mudling plugin test` | `manifest` | +| Every pattern compiles. | `mudling plugin test` | `pattern` | +| The plugin has tests, each produces its `.expected`, and no hook fails. | `mudling plugin test` | `tests`, `expected`, `hook` | +| No hook overruns its limits, and each log stays within the budget. | `mudling plugin test`, then below | `budget` | +| The Luau compiles and lints clean. | `luau-analyze`, under [`ci/luaurc`](../ci/luaurc) | `lint` | + +A layout failure stops that plugin's other checks, because `plugin test` prints +paths and a bad name could confuse what reads them. Hooks must also survive the +shared log described [below](#the-budget), not only the plugin's own tests. + +The hook files are linted as one, in the manifest's order, because they load into +one VM. A plugin's own `.luaurc` doesn't count. + +Merging needs every check to pass. On `main` the same checks run again, and the +[signed index](index-format.md) is built only if they pass. + +## What a failure means + +| Line | What to do | +| --- | --- | +| `fail layout: …` | Rename the folder or the `id` so that they match, or rename or remove the file it names. | +| `fail license: …` | Set `license = "MIT"` or `"Apache-2.0"`, if you have the right to. | +| `fail manifest: …` | The reason names the file. Try `mudling plugin test plugins/`. | +| `fail pattern: …` | The reason shows the pattern. Patterns are Rust `regex`, with no lookaround or backreferences. | +| `fail expected: …` | Your plugin produced something else. If the new output is right, run `mudling plugin test plugins/ --update`, read the difference, and commit it. | +| `fail tests: …` | Add a test: see [CONTRIBUTING](../CONTRIBUTING.md#4-write-its-tests). | +| `fail hook: …` | A hook raised an error on one of your test logs, or on the shared log. Text from another game can match your pattern, so a hook shouldn't assume what it gets. | +| `fail budget: … overran` | A hook hit its limits. Do less work per event. | +| `fail budget: … the reference` | It costs too much per line: see below. | +| `fail lint: …` | The finding names the file and line. Prefix a variable you mean to leave unused with `_`. | +| `couldn't run: …` | The problem is in CI, not your plugin. A maintainer will look. | + +## The budget + +A plugin may add at most 5 µs per line at p99: see +[the line budget](https://github.com/Vyttle-LLC/mudling/blob/main/docs/plugins/reference.md#the-line-budget) +in the plugin API reference. `mudling plugin test` measures that directly, but GitHub's shared runners can't be trusted for an +absolute number: they read up to four times over and vary twofold between runs. +So CI ignores `plugin test`'s own 5 µs verdict and judges the plugin against +[a reference plugin](../ci/reference) in the same job, as `mudling-bench compare` +judges a base against a head: + +- The reference costs about 5 µs a line on a quiet machine. +- Both replay the same log, in turns: plugin, reference, reference, plugin. +- Stalls only ever add time, so each side's lowest time in a block of three rounds + is its truest. +- A plugin is over budget if its lowest p99 per line, with the host's own work, + is more than 1.10× the reference's. +- One lucky round can set a low, so a plugin that loses gets a fresh block. It + fails only if it loses three blocks running. +- This repeats for each of the plugin's test logs and for one shared log, the + fixture session from `mudling-bench`, so that a short test log can't hide a + cost. The worst result stands. + +The total p99 is compared, not the amount added, because the difference of two +p99s is mostly noise. The pull request gets a comment with the amount added by +each, as this runner measured them, and the ratio that decides. Only the ratio +counts. + +### The absolute check + +A maintainer can check the 5 µs itself on a quiet machine, with nothing else +running, on a release build: + +```sh +cargo build --release -p mudling-cli # in the MUDling repo +target/release/mudling plugin test +target/release/mudling plugin test --log crates/mudling-bench/fixtures/session.txt +``` + +Each prints `cost +<µs>` when within budget and `fail budget: +<µs>` when over. +Run this for a plugin close to the limit, or when a player reports a slow one. + +### Keeping the reference honest + +Run the same on the reference after raising `MUDLING_COMMIT`, or when the numbers +look wrong: + +```sh +target/release/mudling plugin test --log crates/mudling-bench/fixtures/session.txt +``` + +It should read just under `+5 µs`. Each rule costs about 0.6 µs on that log, so +add or remove rules in [`ci/reference/text.toml`](../ci/reference/text.toml) to +bring it back. On an Apple Silicon Mac at MUDling commit `1282f8a`, with a load +average under 4, eight rules read between +4.5 and +4.8 µs on that log. + +A rule costs less on short lines, so on a log of short lines the reference reads +nearer +3 µs, and the limit there is stricter than 5 µs. The shared log holds the +game's usual mix of lengths, and it's the one that stops most heavy plugins. + +## Running it yourself + +You need Python 3.12, `luau-analyze` from +[Luau's releases](https://github.com/luau-lang/luau/releases), OpenSSL 3 (the tests +sign with it; macOS's own `openssl` won't do) and a `mudling` built from the commit +in `ci/pins.env`: + +```sh +python3 ci/registry.py check --mudling --luau-analyze \ + --session-log /crates/mudling-bench/fixtures/session.txt +MUDLING= LUAU_ANALYZE= SESSION_LOG= \ + python3 -m unittest discover ci +``` + +## Repository settings this relies on + +CI can't set these itself. A maintainer sets them on GitHub: + +- A ruleset on `main` that requires a pull request, the `Check plugins` status, and + a review from a code owner. Without it, a failed check and `CODEOWNERS` only + advise. +- Under Settings › Actions › General, approval only for "first-time contributors + who are new to GitHub". On the stricter setting, a first-time contributor's CI + waits for a person to approve it. + +## Why it's safe to run a stranger's plugin + +- The `check` job has a read-only token and no secrets. Plugins can't reach the + file system or the network anyway, because hooks run in MUDling's Luau sandbox. +- The `publish` job holds the signing key. It runs only on `main`, after review, + and it only reads plugin files. It never runs them. +- A pull request can change the checks too, and under `pull_request` its version + runs. That can't touch the key, and the review catches it: a change outside + `plugins/` is never a plugin. +- `budget-comment.yml` can write to pull requests, so it runs from `main` and + treats the report as forgeable. Only ids and numbers reach the comment. diff --git a/docs/index-format.md b/docs/index-format.md new file mode 100644 index 0000000..b1dd9ee --- /dev/null +++ b/docs/index-format.md @@ -0,0 +1,120 @@ +# The signed index + +MUDling's plugin directory reads this file to learn what the registry holds. CI +builds it from `plugins/` on every push to `main` (`build_index` in +[`ci/registry.py`](../ci/registry.py)). + +## Where it is + +```text +https://raw.githubusercontent.com/Vyttle-LLC/mudling-plugins/index/index.json +``` + +That's `index.json` on the `index` branch, which holds nothing else and gets one +commit per publish. Its history is a record of every index. + +## The file + +The index and its signature are one file, so a client can never fetch one without +the other. It's a JSON object with two strings: + +```json +{ + "signed": "{\n \"format\": 1,\n \"commit\": \"…\", …}", + "signature": "2Qxl…==" +} +``` + +| Key | What it is | +| --- | --- | +| `signed` | The index, as a string of JSON. | +| `signature` | The base64 Ed25519 signature of `signed`'s UTF-8 bytes. | + +To read it, a client must, in this order: + +1. Parse the outer object. +2. Verify `signature` over the exact bytes of `signed`, with the public key built + into the app. If it fails, stop and keep the last good index. See + [signing.md](signing.md) for the key. +3. Only then parse `signed`. +4. Refuse a `format` it doesn't know. +5. Refuse an index with an older `published_at` than the one it has, so that an + old signed index can't be replayed to hide an update. + +Because the signature covers a string, nothing needs canonicalizing, and a client +must not re-serialize `signed` before verifying. + +## The index + +```json +{ + "format": 1, + "commit": "9f2c1e7a54b8d3f06a1c2e4b7d8091a3c5e6f7ab", + "published_at": "2026-11-02T17:04:31Z", + "plugins": [ + { + "id": "mygame", + "name": "My Game", + "version": "1.2.0", + "license": "MIT", + "games": { + "hosts": ["mygame.example", "*.mygame.example"], + "mssp_names": ["My Game"] + }, + "source": "plugins/mygame", + "hash": "sha256:3b0f…" + } + ] +} +``` + +| Key | What it is | +| --- | --- | +| `format` | This format's version: `1`. A change a client can't ignore raises it. A new key doesn't. | +| `commit` | The full commit on `main` this was built from. Plugins are fetched at this commit, never from `main`. | +| `published_at` | That commit's committer time, as UTC ISO 8601. | +| `plugins` | One entry per plugin, sorted by `id`. It may be empty. | + +Each entry: + +| Key | What it is | +| --- | --- | +| `id` | The plugin's `id`. | +| `name` | The name players see. | +| `version` | `MAJOR.MINOR.PATCH`. | +| `license` | `MIT` or `Apache-2.0`. | +| `games` | Which games it's for: `hosts` and `mssp_names`, as in the manifest's `[servers]`. A host may start with a `*.` wildcard, and case doesn't matter in either. Both empty means a `default` plugin, for any game. | +| `source` | The plugin's folder in the repo at `commit`. | +| `hash` | The folder's content hash, below. | + +## Fetching a plugin + +Download the folder at `source` from the repo at `commit`, for instance from +`https://codeload.github.com/Vyttle-LLC/mudling-plugins/tar.gz/`. Compute +its content hash, and install it only if the hash equals the entry's `hash`. + +## The content hash + +The hash covers the name and exact bytes of every file in the folder, and works +the way `sha256sum` prints: + +1. List every file under the folder, as paths relative to it with `/` separators. +2. Sort them by their UTF-8 bytes. +3. For each, write a line: the lowercase hex SHA-256 of its contents, two spaces, + the path, and a newline. +4. Take the SHA-256 of those lines. The hash is `sha256:` and its lowercase hex. + +CI allows only ASCII letters, digits, `.`, `_` and `-` in a name, so a path can't +hold a space or a newline. Each line therefore has one reading, and two different +folders can't produce the same list. + +The bytes are the files exactly as committed, which are also git's raw blobs at +`commit`. The repo's own `.gitattributes` turns off line-ending conversion under +`plugins/`, and CI refuses a `.gitattributes` inside a plugin, so a checkout and +the raw blobs give the same hash. + +From inside a plugin's folder, this prints the same hex: + +```sh +find . -type f | sed 's|^\./||' | LC_ALL=C sort | xargs shasum -a 256 | shasum -a 256 +``` diff --git a/docs/signing.md b/docs/signing.md new file mode 100644 index 0000000..2532ddd --- /dev/null +++ b/docs/signing.md @@ -0,0 +1,43 @@ +# The signing key + +CI signs [the index](index-format.md) with **Ed25519**. MUDling verifies it with the +public key built into the app, so someone who gets hold of the `index` branch, or +sits between a player and GitHub, can't change what the app installs. + +Ed25519 is small and well known: a 32-byte public key that fits on a line in the +app's source, a 64-byte signature, and no parameters to get wrong. It's in OpenSSL +on every CI runner, so signing adds no dependency, and it has audited +implementations in Rust, such as `ed25519-dalek`. + +## Setting it up + +This needs doing once. You need OpenSSL 3 (macOS's own `openssl` is LibreSSL, which +can't do this, so use `nix shell nixpkgs#openssl` or Homebrew's), and +[`gh`](https://cli.github.com) signed in with admin rights on this repo. + +```sh +# 1. Make the key pair. +openssl genpkey -algorithm ed25519 -out index-signing-key.pem + +# 2. Print the public key, the one line the app needs. +openssl pkey -in index-signing-key.pem -pubout -outform DER | tail -c 32 | base64 + +# 3. Give the private key to CI. +gh secret set INDEX_SIGNING_KEY --repo Vyttle-LLC/mudling-plugins < index-signing-key.pem + +# 4. Keep it in your password manager, then remove the file. +rm index-signing-key.pem +``` + +The public key from step 2 is 44 base64 characters, the raw 32 bytes. It isn't +secret. Build it into the app. + +Until the secret is set, the `publish` job fails with +`the INDEX_SIGNING_KEY secret isn't set`, and nothing is published. + +## Replacing it + +If the key leaks, the app must get a new public key, so that's an app release. +Repeat the steps above, ship the release, and tell players to update. An app with +the old key refuses every index signed with the new one, and keeps its last good +index. diff --git a/plugins/README.md b/plugins/README.md new file mode 100644 index 0000000..0a3d448 --- /dev/null +++ b/plugins/README.md @@ -0,0 +1,4 @@ +# Plugins + +One folder per plugin, named for its `id`. There are none yet: yours could be +the first. [CONTRIBUTING.md](../CONTRIBUTING.md) shows how to add one.