diff --git a/.github/workflows/terminal-demo.yml b/.github/workflows/terminal-demo.yml new file mode 100644 index 0000000..a0f84fc --- /dev/null +++ b/.github/workflows/terminal-demo.yml @@ -0,0 +1,87 @@ +name: Terminal demo +on: + workflow_call: + inputs: + artifact: + description: Name of the built CLI artifact from this workflow run + type: string + required: true + archive: + description: Relative path or glob matching exactly one .tar.gz in the artifact + type: string + default: '' + executable: + description: Relative path or glob matching exactly one executable in the artifact or extracted archive + type: string + required: true + assets: + description: Terminal asset directory in the caller checkout + type: string + default: .github/assets/terminal + runner: + description: Runner label that can execute the built CLI + type: string + required: true +permissions: {} +jobs: + demo: + runs-on: ${{ inputs.runner }} + timeout-minutes: 15 + permissions: + contents: read + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ github.sha }} + persist-credentials: false + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + repository: ${{ job.workflow_repository }} + ref: ${{ job.workflow_sha }} + path: .shared + persist-credentials: false + - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7 + with: + python-version: '3.13' + - name: Prepare a fresh artifact directory + id: directory + shell: bash + run: | + set -euo pipefail + directory="$(mktemp -d "$RUNNER_TEMP/terminal-demo.XXXXXX")" + printf 'path=%s\n' "$directory" >> "$GITHUB_OUTPUT" + - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + name: ${{ inputs.artifact }} + path: ${{ steps.directory.outputs.path }}/artifact + - name: Resolve the built executable + id: executable + env: + DEMO_ARTIFACT: ${{ steps.directory.outputs.path }}/artifact + DEMO_ARCHIVE: ${{ inputs.archive }} + DEMO_EXECUTABLE: ${{ inputs.executable }} + shell: bash + run: | + set -euo pipefail + executable="$(python3 -I .shared/scripts/resolve-terminal-demo.py \ + --artifact-dir "$DEMO_ARTIFACT" --archive "$DEMO_ARCHIVE" \ + --executable "$DEMO_EXECUTABLE")" + printf 'path=%s\n' "$executable" >> "$GITHUB_OUTPUT" + - name: Check the terminal recording + uses: showxu/skills/skills/github-readme-design/scripts@36707036061a2d0ba012184ef0b6d6820082127f + with: + asset: terminal + command: check + recording-only: 'true' + assets: ${{ inputs.assets }} + executable: ${{ steps.executable.outputs.path }} + - name: Remove temporary demo files + if: always() + env: + DEMO_DIRECTORY: ${{ steps.directory.outputs.path }} + shell: bash + run: | + set -euo pipefail + if [[ -n "$DEMO_DIRECTORY" ]]; then + rm -rf -- "$DEMO_DIRECTORY" + fi diff --git a/README.md b/README.md index bc5d8ca..a63ce53 100644 --- a/README.md +++ b/README.md @@ -52,6 +52,7 @@ jobs: | [actions/notify-catalog](actions/notify-catalog/action.yml) | Required `client-id`, `private-key` | `run-url`; receiver-scoped App token with `actions: write` | | [organization.yml](.github/workflows/organization.yml) | Required `declaration-revision`; `mode=online` or `offline`; optional secret `organization-token` | `declaration-revision`; GET-only observations; `contents: read` | | [policy.yml](.github/workflows/policy.yml) | Required `declaration-revision`; `path-exceptions=''` | `declaration-revision`; pass/fail; `contents: read` | +| [terminal-demo.yml](.github/workflows/terminal-demo.yml) | Required `artifact`, `executable`, `runner`; `archive=''`, `assets=.github/assets/terminal` | Pass/fail; `contents: read` | | [result.yml](.github/workflows/result.yml) | Required `needs-json`; `optional-jobs='[]'` | Pass/fail aggregate; `contents: read` | [Runtime adoption](docs/plugin-runtime.md) describes the unchanged digest @@ -237,6 +238,38 @@ organization default-branch rules to one SHA per run and calls the same policy. Until those rules reach the organization's default branch, this check correctly fails for missing declarations. No temporary organization revision is embedded. +## Terminal demo + +Re-record the caller's terminal demo against its freshly built CLI and compare +only `recording.json`. Assets default to `.github/assets/terminal`; DESIGN and +fonts are not required. The presentation toolchain pin lives in this workflow. + +The build job uploads the named artifact in the same run. Use a `.tar.gz` to +preserve executable permissions across artifact upload/download. When `archive` +is set, it must match one `.tar.gz`, extracted into a fresh directory; +`executable` is relative to that directory. Otherwise `executable` is relative +to the downloaded artifact. Both accept globs, require exactly one regular file +and reject absolute paths, `..` components and paths escaping their directory. +The executable must have execute permission. Choose a `runner` that can run it. + +```yaml +jobs: + demo: + needs: package + uses: computer-mcp/github-workflows/.github/workflows/terminal-demo.yml@ + with: + artifact: + archive: + executable: + runner: + validate: + if: always() + needs: [package, demo] + uses: computer-mcp/github-workflows/.github/workflows/result.yml@ + with: + needs-json: ${{ toJSON(needs) }} +``` + ## Aggregation Use `always()` on the caller and reusable aggregate. Required dependencies must diff --git a/scripts/resolve-terminal-demo.py b/scripts/resolve-terminal-demo.py new file mode 100644 index 0000000..3b29470 --- /dev/null +++ b/scripts/resolve-terminal-demo.py @@ -0,0 +1,72 @@ +#!/usr/bin/env python3 +"""Resolve a built CLI within an artifact or a safely extracted .tar.gz.""" + +import argparse +import os +from pathlib import Path, PurePosixPath, PureWindowsPath +import sys +import tarfile +import tempfile + + +def require_relative(value, label): + paths = (PurePosixPath(value), PureWindowsPath(value)) + if (not value or any(character in value for character in "\0\r\n") or + any(path.is_absolute() or path.drive or ".." in path.parts for path in paths)): + raise ValueError(f"{label} must be a relative path without '..' or line breaks") + + +def match_file(root, pattern, label): + require_relative(pattern, label) + matches = list(root.glob(pattern)) + if len(matches) != 1: + raise ValueError(f"{label} must match exactly one file; found {len(matches)}") + target = matches[0].resolve(strict=True) + if not target.is_relative_to(root): + raise ValueError(f"{label} resolves outside its directory") + if not target.is_file(): + raise ValueError(f"{label} must be a regular file") + if any(character in str(target) for character in "\r\n"): + raise ValueError(f"{label} path must not contain line breaks") + return target + + +def archive_member(member, destination): + require_relative(member.name, "archive member") + return tarfile.data_filter(member, destination) + + +def resolve(artifact_dir, archive, executable): + root = Path(artifact_dir).resolve(strict=True) + if not root.is_dir(): + raise ValueError("artifact directory must be a directory") + require_relative(executable, "executable") + if archive: + bundle = match_file(root, archive, "archive") + if not bundle.name.endswith(".tar.gz"): + raise ValueError("archive must be a .tar.gz file") + root = Path(tempfile.mkdtemp(prefix="terminal-demo-extracted-", dir=root.parent)) + with tarfile.open(bundle, "r:gz") as source: + source.extractall(root, filter=archive_member) + target = match_file(root, executable, "executable") + if not os.access(target, os.X_OK): + raise ValueError("executable must have executable permission") + return target + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--artifact-dir", type=Path, required=True) + parser.add_argument("--archive", default="") + parser.add_argument("--executable", required=True) + args = parser.parse_args(argv) + try: + print(resolve(args.artifact_dir, args.archive, args.executable)) + return 0 + except (OSError, ValueError, tarfile.TarError) as error: + print("FAIL terminal demo: " + str(error), file=sys.stderr) + return 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/test_terminal_demo.py b/tests/test_terminal_demo.py new file mode 100644 index 0000000..f953e40 --- /dev/null +++ b/tests/test_terminal_demo.py @@ -0,0 +1,161 @@ +import importlib.util +import io +import os +from pathlib import Path +import subprocess +import sys +import tarfile +import tempfile +import unittest + +SCRIPT = Path(__file__).resolve().parents[1] / "scripts/resolve-terminal-demo.py" +spec = importlib.util.spec_from_file_location("terminal_demo", SCRIPT) +terminal_demo = importlib.util.module_from_spec(spec) +spec.loader.exec_module(terminal_demo) + + +class TerminalDemoTests(unittest.TestCase): + def setUp(self): + temporary = tempfile.TemporaryDirectory(prefix="terminal demo ") + self.addCleanup(temporary.cleanup) + self.root = Path(temporary.name).resolve() + self.artifact = self.root / "artifact" + self.artifact.mkdir() + + def executable(self, name, mode=0o755): + target = self.artifact / name + target.parent.mkdir(parents=True, exist_ok=True) + target.write_text("#!/bin/sh\nprintf 'demo\\n'\n") + target.chmod(mode) + return target + + def archive(self, name="cli.tar.gz", members=None): + target = self.artifact / name + target.parent.mkdir(parents=True, exist_ok=True) + if members is None: + member = tarfile.TarInfo("package/bin/cli") + member.mode = 0o755 + members = [(member, b"#!/bin/sh\nprintf 'demo\\n'\n")] + with tarfile.open(target, "w:gz") as bundle: + for member, content in members: + member.size = len(content) + bundle.addfile(member, io.BytesIO(content)) + return target + + def test_executable_paths_and_globs_resolve_one_file(self): + target = self.executable("bin/demo cli") + for pattern in ("bin/demo cli", "bin/demo*", "**/demo*"): + with self.subTest(pattern=pattern): + self.assertEqual(terminal_demo.resolve(self.artifact, "", pattern), target) + + def test_executable_zero_and_multiple_matches_fail(self): + with self.assertRaisesRegex(ValueError, "exactly one.*found 0"): + terminal_demo.resolve(self.artifact, "", "bin/*") + self.executable("bin/one") + self.executable("bin/two") + with self.assertRaisesRegex(ValueError, "exactly one.*found 2"): + terminal_demo.resolve(self.artifact, "", "bin/*") + + def test_non_executable_and_directory_targets_fail(self): + self.executable("bin/cli", mode=0o644) + with self.assertRaisesRegex(ValueError, "executable permission"): + terminal_demo.resolve(self.artifact, "", "bin/cli") + with self.assertRaisesRegex(ValueError, "regular file"): + terminal_demo.resolve(self.artifact, "", "bin") + + def test_absolute_and_parent_paths_fail_for_both_inputs(self): + for pattern in ("/bin/cli", "../cli", "bin/../cli", "bin/../../cli", + "C:/bin/cli", "C:\\bin\\cli", "\\\\server\\share\\cli", "bin\\..\\cli"): + for argument in ("archive", "executable"): + with self.subTest(pattern=pattern, argument=argument): + args = {"archive": "", "executable": "cli", argument: pattern} + with self.assertRaisesRegex(ValueError, "relative path"): + terminal_demo.resolve(self.artifact, **args) + + def test_line_breaks_and_nul_are_rejected(self): + for pattern in ("cli\noutput=value", "cli\routput=value", "cli\0"): + with self.subTest(pattern=repr(pattern)): + with self.assertRaisesRegex(ValueError, "relative path"): + terminal_demo.resolve(self.artifact, "", pattern) + self.executable("cli\noutput=value") + with self.assertRaisesRegex(ValueError, "line breaks"): + terminal_demo.resolve(self.artifact, "", "cli*") + + def test_symlink_cannot_escape_artifact(self): + outside = self.root / "outside" + outside.write_text("#!/bin/sh\n") + outside.chmod(0o755) + (self.artifact / "cli").symlink_to(outside) + with self.assertRaisesRegex(ValueError, "outside"): + terminal_demo.resolve(self.artifact, "", "cli") + (self.artifact / "external").symlink_to(self.root, target_is_directory=True) + with self.assertRaisesRegex(ValueError, "outside"): + terminal_demo.resolve(self.artifact, "", "external/outside") + + def test_archive_extracts_into_a_fresh_directory_and_preserves_mode(self): + self.archive("packages/demo cli.tar.gz") + self.executable("package/bin/cli", mode=0o644) + first = terminal_demo.resolve(self.artifact, "packages/*.tar.gz", "package/bin/*") + second = terminal_demo.resolve(self.artifact, "packages/*.tar.gz", "package/bin/cli") + self.assertTrue(os.access(first, os.X_OK)) + self.assertEqual(first.read_bytes(), second.read_bytes()) + self.assertNotEqual(first.parents[2], second.parents[2]) + self.assertEqual(first.parents[2].parent, self.root) + self.assertFalse(first.is_relative_to(self.artifact)) + self.assertEqual(subprocess.check_output([str(first)], text=True), "demo\n") + + def test_archive_zero_and_multiple_matches_fail(self): + with self.assertRaisesRegex(ValueError, "exactly one.*found 0"): + terminal_demo.resolve(self.artifact, "*.tar.gz", "cli") + self.archive("one.tar.gz") + self.archive("two.tar.gz") + with self.assertRaisesRegex(ValueError, "exactly one.*found 2"): + terminal_demo.resolve(self.artifact, "*.tar.gz", "cli") + + def test_archive_must_be_a_regular_gzip_tar_file(self): + self.archive("cli.zip") + with self.assertRaisesRegex(ValueError, r"\.tar\.gz"): + terminal_demo.resolve(self.artifact, "cli.zip", "cli") + (self.artifact / "directory.tar.gz").mkdir() + with self.assertRaisesRegex(ValueError, "regular file"): + terminal_demo.resolve(self.artifact, "directory.tar.gz", "cli") + (self.artifact / "broken.tar.gz").write_text("not a gzip archive") + with self.assertRaises(tarfile.TarError): + terminal_demo.resolve(self.artifact, "broken.tar.gz", "cli") + + def test_unsafe_archive_member_paths_fail(self): + for name in ("../escaped", "/absolute", "package/../../escaped"): + with self.subTest(name=name): + member = tarfile.TarInfo(name) + self.archive(members=[(member, b"unsafe")]) + with self.assertRaisesRegex(ValueError, "relative path"): + terminal_demo.resolve(self.artifact, "cli.tar.gz", "cli") + self.assertFalse((self.root / "escaped").exists()) + + def test_archive_links_cannot_escape_extraction_directory(self): + for kind in (tarfile.SYMTYPE, tarfile.LNKTYPE): + with self.subTest(kind=kind): + member = tarfile.TarInfo("cli") + member.type = kind + member.linkname = "../outside" + self.archive(members=[(member, b"")]) + with self.assertRaises(tarfile.FilterError): + terminal_demo.resolve(self.artifact, "cli.tar.gz", "cli") + + def test_cli_emits_only_a_resolved_path_or_a_failure(self): + target = self.executable("bin/demo cli") + command = [sys.executable, "-I", str(SCRIPT), "--artifact-dir", str(self.artifact), + "--executable", "bin/demo*"] + result = subprocess.run(command, capture_output=True, text=True) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(result.stdout, str(target) + "\n") + self.assertEqual(result.stderr, "") + target.chmod(0o644) + result = subprocess.run(command, capture_output=True, text=True) + self.assertEqual(result.returncode, 1) + self.assertEqual(result.stdout, "") + self.assertIn("FAIL terminal demo:", result.stderr) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_workflows.py b/tests/test_workflows.py index 4bcdbe9..08e12c2 100644 --- a/tests/test_workflows.py +++ b/tests/test_workflows.py @@ -12,7 +12,7 @@ class WorkflowTests(unittest.TestCase): def test_actual_workflows_and_action_pass_contracts(self): - self.assertEqual(len(workflows.validate()), 7) + self.assertEqual(len(workflows.validate()), 8) def test_duplicate_yaml_keys_are_rejected(self): with tempfile.TemporaryDirectory() as directory: @@ -52,6 +52,55 @@ def test_release_and_runtime_keep_public_interfaces(self): runtime = workflows.read(ROOT / ".github/workflows/plugin-runtime.yml")["on"] self.assertEqual(runtime["workflow_call"], "") + def test_terminal_demo_interface_and_permissions(self): + workflow = workflows.read(ROOT / ".github/workflows/terminal-demo.yml") + call = workflow["on"]["workflow_call"] + self.assertEqual(set(call["inputs"]), {"artifact", "archive", "executable", "assets", "runner"}) + self.assertNotIn("outputs", call) + for name in ("artifact", "executable", "runner"): + self.assertEqual(call["inputs"][name]["required"], "true") + self.assertEqual(call["inputs"][name]["type"], "string") + self.assertEqual(call["inputs"]["archive"]["default"], "") + self.assertEqual(call["inputs"]["assets"]["default"], ".github/assets/terminal") + self.assertEqual(set(workflow["jobs"]), {"demo"}) + job = workflow["jobs"]["demo"] + self.assertEqual(workflow["permissions"], {}) + self.assertEqual(job["permissions"], {"contents": "read"}) + self.assertEqual(job["runs-on"], "${{ inputs.runner }}") + self.assertGreater(int(job["timeout-minutes"]), 0) + self.assertNotIn("outputs", job) + self.assertNotIn("concurrency", workflow) + self.assertNotIn("concurrency", job) + self.assertNotIn("cache", (ROOT / ".github/workflows/terminal-demo.yml").read_text().lower()) + + def test_terminal_demo_uses_caller_source_and_pinned_recording_check(self): + steps = workflows.read(ROOT / ".github/workflows/terminal-demo.yml")["jobs"]["demo"]["steps"] + self.assertEqual(steps[0]["with"]["ref"], "${{ github.sha }}") + for step in steps: + if step.get("uses", "").startswith("actions/checkout@"): + self.assertEqual(step["with"]["persist-credentials"], "false") + if "run" in step: + self.assertEqual(step["shell"], "bash") + self.assertIn("set -euo pipefail", step["run"]) + self.assertNotIn("${{", step["run"]) + directory = next(step for step in steps if step.get("id") == "directory") + self.assertIn('mktemp -d "$RUNNER_TEMP/', directory["run"]) + download = next(step for step in steps if step.get("uses", "").startswith("actions/download-artifact@")) + self.assertEqual(download["with"], {"name": "${{ inputs.artifact }}", + "path": "${{ steps.directory.outputs.path }}/artifact"}) + executable = next(step for step in steps if step.get("id") == "executable") + self.assertEqual(executable["env"]["DEMO_ARCHIVE"], "${{ inputs.archive }}") + self.assertEqual(executable["env"]["DEMO_EXECUTABLE"], "${{ inputs.executable }}") + self.assertIn('--archive "$DEMO_ARCHIVE"', executable["run"]) + self.assertIn('--executable "$DEMO_EXECUTABLE"', executable["run"]) + presentation = next(step for step in steps if step.get("uses", "").startswith("showxu/skills/")) + self.assertEqual(presentation["uses"], + "showxu/skills/skills/github-readme-design/scripts@36707036061a2d0ba012184ef0b6d6820082127f") + self.assertEqual(presentation["with"], {"asset": "terminal", "command": "check", + "recording-only": "true", "assets": "${{ inputs.assets }}", + "executable": "${{ steps.executable.outputs.path }}"}) + self.assertEqual(steps[-1]["if"], "always()") + if __name__ == "__main__": unittest.main()