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
87 changes: 87 additions & 0 deletions .github/workflows/terminal-demo.yml
Original file line number Diff line number Diff line change
@@ -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
33 changes: 33 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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@<workflow-sha>
with:
artifact: <artifact name uploaded by package>
archive: <archive glob>
executable: <path to the CLI>
runner: <runner label>
validate:
if: always()
needs: [package, demo]
uses: computer-mcp/github-workflows/.github/workflows/result.yml@<workflow-sha>
with:
needs-json: ${{ toJSON(needs) }}
```

## Aggregation

Use `always()` on the caller and reusable aggregate. Required dependencies must
Expand Down
72 changes: 72 additions & 0 deletions scripts/resolve-terminal-demo.py
Original file line number Diff line number Diff line change
@@ -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())
161 changes: 161 additions & 0 deletions tests/test_terminal_demo.py
Original file line number Diff line number Diff line change
@@ -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()
Loading