From aafdecc1186888f856992c267e25a8a6f2935dc8 Mon Sep 17 00:00:00 2001 From: SkyFi Geek <45924209+mobileskyfi@users.noreply.github.com> Date: Fri, 30 Oct 2026 17:27:54 -0700 Subject: [PATCH 1/7] RouterOS /app integration harness, workflow, and install docs (#245) Phase 1 (manual rehearsal on Intel Mac, both arches green): the README /app block is correct as written; adds the missing storage-disk prerequisite step (/app/setup or /app/settings, 2 GB sizing, CHR second-disk note) and MANUAL disk-sizing evidence. Phase 2 (this harness): scripts/app-integration.ts boots a fresh disposable CHR per leg, runs the README block with exactly two substitutions, and completes a real MCP session through ui-url; app-integration.yml (dispatch only) runs the x86 (KVM) and arm64 (TCG) legs; scripts/smoke-oci.ts is the shared MCP smoke also specified by #246. V-app-mcp-x86/arm64 rows added as non-blocking manual-dispatch gates. --- .github/workflows/app-integration.yml | 96 ++++ .gitignore | 3 + CHANGELOG.md | 4 + MANUAL.md | 30 ++ Makefile | 18 +- README.md | 18 +- VALIDATION.md | 2 + project-words.txt | 5 + scripts/app-integration.ts | 662 ++++++++++++++++++++++++++ scripts/smoke-oci.ts | 96 ++++ src/app-integration.test.ts | 281 +++++++++++ 11 files changed, 1210 insertions(+), 5 deletions(-) create mode 100644 .github/workflows/app-integration.yml create mode 100644 scripts/app-integration.ts create mode 100644 scripts/smoke-oci.ts create mode 100644 src/app-integration.test.ts diff --git a/.github/workflows/app-integration.yml b/.github/workflows/app-integration.yml new file mode 100644 index 0000000..e96c201 --- /dev/null +++ b/.github/workflows/app-integration.yml @@ -0,0 +1,96 @@ +name: App Integration + +# RouterOS /app integration (#245 Phase 2): boots a fresh disposable CHR per +# leg (x86 + arm64), runs the README's own /app/add block against it, and +# completes a real MCP session through the app's ui-url. All logic lives in +# scripts/app-integration.ts so local (`make app-integration`) and CI runs are +# identical — this file only adds runner setup. +# +# Dispatch-only: release gating is #246's job. Dispatch with the candidate +# image and its release version, e.g.: +# +# gh workflow run app-integration.yml \ +# -f image=ghcr.io/tikoci/rosetta:sha-abc123 -f version=0.12.0 +# +# A green run proves the HTTP port-redirect path only (use-https=no): it says +# nothing about certificate issuance or the reverse-proxy/SNI path. Each leg +# logs host arch, guest arch, the accelerator actually selected, and the +# container platform; a skipped leg is not a pass (fail-fast is off and there +# are no leg conditions). + +on: + workflow_dispatch: + inputs: + image: + description: "Candidate image ref, e.g. ghcr.io/tikoci/rosetta:sha-abc123 or :v0.12.0" + required: true + default: "ghcr.io/tikoci/rosetta:latest" + ros_version: + description: "RouterOS version for both legs (one stable >= 7.22)" + required: false + default: "7.25" + version: + description: "Expected release version for provenance (e.g. 0.12.0); required for floating/sha tags" + required: false + default: "" + +permissions: + contents: read + +jobs: + leg: + name: App integration (${{ matrix.arch }}) + strategy: + fail-fast: false + matrix: + include: + # x86 CHR needs KVM: the Bun binary SIGILLs under TCG (Phase 1), and + # hosted x64 runners ship /dev/kvm. quickchr auto-selects it. + - arch: x86 + runs-on: ubuntu-latest + timeout: 30 + step-timeout: 20 + # Hosted arm64 has no usable KVM (quickchr integration.yml: 12/12 + # runs fell back), so this leg is same-arch TCG and gets the long + # budget. Same-arch TCG is much faster than the cross-arch TCG the + # Mac rehearsal used, but still the slow leg. + - arch: arm64 + runs-on: ubuntu-24.04-arm + timeout: 60 + step-timeout: 50 + runs-on: ${{ matrix.runs-on }} + timeout-minutes: ${{ matrix.timeout }} + steps: + - uses: actions/checkout@v7 + + - uses: oven-sh/setup-bun@v2 + with: + bun-version: latest + + - run: bun install --frozen-lockfile + + - name: Install QEMU + run: | + set -eo pipefail + sudo apt-get update + sudo apt-get install -y qemu-system-x86 qemu-system-arm qemu-utils qemu-efi-aarch64 + + # Pinned to match QUICKCHR_PIN in scripts/app-integration.ts (the script + # asserts the pin; src/app-integration.test.ts asserts they agree). + - name: Install pinned quickchr + run: bun install -g @tikoci/quickchr@0.5.4 + + - name: Run integration leg + timeout-minutes: ${{ matrix.step-timeout }} + run: | + set -eo pipefail + bun scripts/app-integration.ts --arch ${{ matrix.arch }} \ + --image ${{ inputs.image }} --ros-version ${{ inputs.ros_version }} \ + --version "${{ inputs.version }}" + + - name: Upload diagnostics bundle + if: always() + uses: actions/upload-artifact@v7 + with: + name: app-integration-${{ matrix.arch }} + path: app-integration-*.json diff --git a/.gitignore b/.gitignore index 517ae99..841478d 100644 --- a/.gitignore +++ b/.gitignore @@ -52,3 +52,6 @@ coverage/lcov.info # Experimental CLI-Reference extraction (experiments/cliref-*.ts) — regenerable experiments/cliref.db experiments/out/ + +# /app integration evidence bundles (scripts/app-integration.ts) — CI uploads as artifacts +app-integration-*.json diff --git a/CHANGELOG.md b/CHANGELOG.md index 09b4398..27ccf6f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -22,6 +22,10 @@ uses [Semantic Versioning](https://semver.org/). ## [Unreleased] +### Fixed + +- The README `/app` install steps now cover the storage-disk prerequisite (`/app/setup` or `/app/settings`, with sizing guidance): without a selected disk `/app/add` succeeds but the app sits idle with no error. The steps also note that the inline YAML's inner quotes must stay backslash-escaped. Phase 1 of #245. + ## [0.12.0] — 2026-10-30 ### Added diff --git a/MANUAL.md b/MANUAL.md index 176d0e8..2efd72c 100644 --- a/MANUAL.md +++ b/MANUAL.md @@ -93,6 +93,36 @@ docker run --rm -p 8080:8080 ghcr.io/tikoci/rosetta:latest These are the same images used by the [MikroTik /app install](README.md#install-on-mikrotik-app). Tags: `latest`, version (e.g., `v0.2.1`), and `sha-`. +### Disk sizing for /app installs + +The `/app` install needs its storage disk to have room to spare (see the README prerequisites). Measured on CHR (RouterOS 7.25, `v0.12.0` image): + +- Extracted app footprint: ~1 GB on x86, ~600 MB on arm64. +- First start copies the ~415 MB database aside (the image layer is read-only, so the first write duplicates the file into writable storage). The disk needs that much free *beyond* the extracted size: with under ~250 MB free the container crash-loops (`attempt to write a readonly database` is the symptom — the underlying failure is out-of-space on that copy), while ~450 MB free was enough. A 4 GB app disk leaves comfortable headroom on both architectures. +- A swap file roughly matching RAM (~500 MB on a 512 MB CHR, ~1 GB on a 1 GB CHR) may also be created on the app disk automatically; allow for it. +- No LAN bridge is required: without one the app runs on an internal NAT network with automatic port redirects to the container's port 8080. +- With `use-https=no` the endpoint is plain HTTP through those redirects, not through the reverse proxy (which only serves `use-https=yes` apps). + +### App integration runs (local + CI) + +`scripts/app-integration.ts` (#245) proves the README install end to end: it boots a fresh disposable CHR, runs the README's own `/app/add` block (exactly two substitutions: `use-https=no` for CHR, the candidate image ref), and completes a real MCP session through the app's ui-url. The same script runs locally and in CI (`app-integration.yml`); the workflow only adds runner setup. Local prerequisites: QEMU with `qemu-img`, Bun, and exactly quickchr 0.5.4 (`bun install -g @tikoci/quickchr@0.5.4` — the script asserts the pin). + +```sh +make app-integration ARCH=x86 IMAGE=ghcr.io/tikoci/rosetta:v0.12.0 +make app-integration ARCH=arm64 IMAGE=ghcr.io/tikoci/rosetta:sha-abc123 VERSION=0.12.0 +``` + +`ARCH` is `x86` or `arm64` (one leg per invocation); `ROS_VERSION` defaults to 7.25. `VERSION` is required for floating/sha tags (it is the provenance the smoke asserts) and defaults to the version parsed from a `vX.Y.Z` tag. Each run writes `app-integration-.json` (redacted evidence bundle: digests, timings, app/container state, smoke output) and removes its VM unless `--keep` is passed. + +Dispatch CI from the Actions tab or: + +```sh +gh workflow run app-integration.yml \ + -f image=ghcr.io/tikoci/rosetta:sha-abc123 -f version=0.12.0 +``` + +Both legs (x86 on `ubuntu-latest` with KVM, arm64 on `ubuntu-24.04-arm` with TCG) must run and pass; a skipped leg is not a pass. The workflow is dispatch-only — release gating is #246's job. A green run proves the HTTP port-redirect path only (see Disk sizing above): it says nothing about certificate issuance or the reverse-proxy path, which need a real router with `/ip/cloud`. + ## MCP Resources If your MCP client supports resources, rosetta exposes datasets and supplemental content: diff --git a/Makefile b/Makefile index 30d0198..02b4ae0 100644 --- a/Makefile +++ b/Makefile @@ -14,7 +14,8 @@ VERSION ?= extract-hardware-catalog search browse serve \ typecheck lint test preflight verify \ db-doctor db-sync \ - install setup clean eval eval-update eval-self eval-self-update + install setup clean eval eval-update eval-self eval-self-update \ + app-integration # ── Development ── @@ -87,6 +88,21 @@ extract-hardware-catalog: # ── Quality ── +# RouterOS /app integration leg (#245): boots a fresh disposable CHR, runs the +# README's own /app/add block against it, and completes a real MCP session +# through the app's ui-url. Same script CI runs (app-integration.yml). +# Requires quickchr 0.5.4 and QEMU (see MANUAL "App integration runs"). +# Example: make app-integration ARCH=arm64 IMAGE=ghcr.io/tikoci/rosetta:v0.12.0 +ARCH ?= x86 +IMAGE ?= +ROS_VERSION ?= 7.25 +VERSION ?= +app-integration: +ifndef IMAGE + $(error IMAGE is required, e.g. make app-integration ARCH=x86 IMAGE=ghcr.io/tikoci/rosetta:v0.12.0) +endif + bun run scripts/app-integration.ts --arch $(ARCH) --image $(IMAGE) --ros-version $(ROS_VERSION) $(if $(VERSION),--version $(VERSION)) + typecheck: bun run typecheck diff --git a/README.md b/README.md index b0fc7bf..001b68e 100644 --- a/README.md +++ b/README.md @@ -54,7 +54,17 @@ After reboot: See MikroTik's [Container documentation](https://manual.mikrotik.com/docs/containers/) for full prerequisites and troubleshooting. -### 2. Add the rosetta app +### 2. Give /app a storage disk + +The `/app` system cannot install anything until a storage disk is selected: without one, `/app/add` succeeds but the app sits idle with no status and no error. Run MikroTik's setup wizard (WebFig: App → Setup, or `/app/setup` on the CLI) and pick a disk, or point `/app/settings` at an already-mounted disk directly: + +```routeros +/app/settings/set disk= +``` + +Allow at least 2 GB of free space on that disk — the extracted app is up to ~1 GB, and RouterOS copies the ~415 MB database aside when the container first writes to it. No LAN bridge is required: without one the app runs on an internal NAT network with automatic port redirects. (On CHR, attach a second disk first — the system disk cannot be used for `/app` storage.) + +### 3. Add the rosetta app ```routeros /app/add use-https=yes disabled=no yaml="name: rosetta @@ -74,9 +84,9 @@ services: " ``` -That's it. RouterOS downloads the container image, configures networking and firewall redirects, and starts the MCP server. The `auto-update: true` setting pulls the latest image on each boot. +The inner double quotes must stay backslash-escaped, as shown — an unescaped `"` ends the `yaml` string early and the command fails. With storage configured, that's it: RouterOS downloads the container image, configures networking and firewall redirects, and starts the MCP server. The `auto-update: true` setting pulls the latest image on each boot. -### 3. Get the MCP endpoint URL +### 4. Get the MCP endpoint URL The URL to use with your AI assistant is shown as **UI URL** in WebFig (App → rosetta), or from the CLI: @@ -86,7 +96,7 @@ The URL to use with your AI assistant is shown as **UI URL** in WebFig (App → This URL includes the `/mcp` path and is ready to paste into any MCP client that supports HTTP transport. With `use-https=yes`, the URL uses HTTPS with a MikroTik-managed `*.routingthecloud.net` certificate. -### 4. Configure your AI assistant +### 5. Configure your AI assistant Point any HTTP-capable MCP client at the URL from the previous step: diff --git a/VALIDATION.md b/VALIDATION.md index 0d08d63..e1bab5e 100644 --- a/VALIDATION.md +++ b/VALIDATION.md @@ -46,6 +46,8 @@ Tasks in `tasks/` reference these IDs in their `validation:` frontmatter. When a | V-bunx-upgrade | An explicitly shared `DB_PATH` holds a real `bunx`-installed DB seeded from the previously-published version on the same dist-tag auto-refreshes to the just-published version on an explicit-tag invocation (`@latest`/`@next`, no `--refresh`); a warm bare `bunx` serves its cache and is deliberately not gated (decision B, #226). `ROSETTA_OFFLINE=1` against that same stale DB degrades gracefully instead of crashing (#76/#23) | `bunx-upgrade-smoke` matrix (macOS/Linux/Windows) in `release-smoke.yml`; skipped (not failed) when no prior publish exists yet on that channel | blocking (when a previous version exists) | #226 | | V-stdio-handshake | MCP stdio handshake completes against a real `@modelcontextprotocol/sdk` client; no stdout pollution | `bun test src/mcp-stdio-client.test.ts` in `.github/workflows/test.yml` | blocking | — | | V-http-handshake | MCP HTTP handshake + multi-session lifecycle works end-to-end | `src/mcp-http.test.ts` | blocking | — | +| V-app-mcp-x86 | The README `/app` install works end to end on x86: a fresh CHR runs the README's own `/app/add` (HTTP leg) and serves a real MCP session (initialize → tools/list → provenance match → nonempty search) through its ui-url | `app-integration.yml` x86 leg (`scripts/app-integration.ts --arch x86`); unit + workflow-structure pins in `src/app-integration.test.ts` | non-blocking (manual dispatch) | #245 | +| V-app-mcp-arm64 | Same on arm64 CHR | `app-integration.yml` arm64 leg (`scripts/app-integration.ts --arch arm64`) | non-blocking (manual dispatch) | #245 | | V-tui-mcp-parity | Every MCP tool reachable via a `.routeros_*` dot-command in `browse` | `src/browse-parity.test.ts` via `bun test` in `.github/workflows/test.yml` | blocking | — | | V-cli-flag-uniformity | CLI flags documented in `MANUAL.md` match `bun src/mcp.ts --help` output | `src/cli-help.test.ts` via `bun test` in `.github/workflows/test.yml` | blocking | — | | V-cli-once-json | `browse --once .` prints exactly one JSON document to stdout (diagnostics on stderr) and exits non-zero when the dot-command fails | `src/browse-once.test.ts` via `bun test` in `.github/workflows/test.yml` | blocking | — | diff --git a/project-words.txt b/project-words.txt index e592c75..8aa0ade 100644 --- a/project-words.txt +++ b/project-words.txt @@ -123,6 +123,7 @@ easyops ebusy editsection eexist +efi EIRP elif elr @@ -186,6 +187,7 @@ HPACD HPD hpn htb +hvf hwcat hwmp idx @@ -213,6 +215,7 @@ joineui kbd kne kpps +kvm laravel ldf ldp @@ -417,6 +420,7 @@ slugified sma smips smsc +sni snmp snp socksify @@ -448,6 +452,7 @@ sxtsq syntaxhighlighter syscap tabl +tcg tek thirdparty tik diff --git a/scripts/app-integration.ts b/scripts/app-integration.ts new file mode 100644 index 0000000..05adb34 --- /dev/null +++ b/scripts/app-integration.ts @@ -0,0 +1,662 @@ +#!/usr/bin/env bun +/** + * app-integration.ts — one RouterOS /app integration leg (#245 Phase 2). + * + * Boots a fresh disposable CHR with the Phase 1 recipe, runs the README's + * own /app/add block against it (exactly two substitutions), and completes a + * real MCP session through the app's ui-url. Same script runs locally on a + * Mac and in CI (app-integration.yml) — the workflow only adds runner setup. + * + * Usage: + * bun scripts/app-integration.ts --arch --image + * [--ros-version ] [--version ] [--host-port ] [--name ] + * [--diagnostics-file ] [--keep] + * + * --arch Guest arch: x86 or arm64 (required). + * --image Candidate image ref, e.g. ghcr.io/tikoci/rosetta:v0.12.0 (required). + * --ros-version RouterOS version (default: 7.25). + * --version Expected release version for provenance, e.g. 0.12.0. + * Defaults to the version parsed from a vX.Y.Z image tag; + * required for floating/sha tags. + * --host-port Host side of the QEMU port forward (default: 9803). + * --name quickchr machine name (default: auto-generated). + * --diagnostics-file Where to write the JSON evidence bundle + * (default: app-integration-.json in cwd). + * --keep Skip VM cleanup (debugging aid; default cleans up always). + * + * Exit codes: 0 pass; 1 integration failure; 2 usage/config error. + */ + +import path from "node:path"; + +/** Pinned quickchr — local and CI must run exactly this (validated in Phase 2). */ +export const QUICKCHR_PIN = "0.5.4"; +/** Default RouterOS version: one stable >= 7.22, validated in Phase 1. */ +export const ROS_VERSION_DEFAULT = "7.25"; +/** App-disk size in GB. 4G leaves headroom; 2G fails on arm64 (swap + overlay + * copy-up of the ~415MB DB exceed it — see MANUAL "Disk sizing"). */ +export const APP_DISK_GB = 4; +/** Guest RAM in MB per arch (Phase 1 measurements). */ +export const GUEST_MEM_MB: Record = { x86: 512, arm64: 1024 }; +/** Guest web port from the README YAML (host side is --host-port). */ +export const GUEST_WEB_PORT = 9803; +/** Poll interval while waiting for running=true. */ +export const POLL_INTERVAL_MS = 15_000; +/** /app/add → running=true budget per arch (Phase 1: ~1min x86, ~4.5min arm64). */ +export const RUNNING_TIMEOUT_MS: Record = { x86: 6 * 60_000, arm64: 18 * 60_000 }; +/** quickchr start (first boot + provisioning) budget per arch (Phase 1: ~1min / ~3.5min). */ +export const START_TIMEOUT_MS: Record = { x86: 10 * 60_000, arm64: 20 * 60_000 }; + +// ── Pure helpers (unit-tested in src/app-integration.test.ts) ─────────────── + +/** Extract the one fenced block whose first line is the /app/add command. */ +export function extractAppAddBlock(readme: string): string { + const fences = [...readme.matchAll(/```routeros\n([\s\S]*?)\n```/g)].map((m) => m[1]); + const hits = fences.filter((b) => b.trimStart().startsWith("/app/add ")); + if (hits.length === 0) throw new Error("README has no fenced routeros block starting with /app/add"); + if (hits.length > 1) { + throw new Error(`README has ${hits.length} fenced blocks starting with /app/add (expected exactly 1)`); + } + return hits[0]; +} + +function substituteOnce(haystack: string, needle: string, replacement: string): string { + const count = haystack.split(needle).length - 1; + if (count !== 1) { + throw new Error( + `Expected exactly 1 occurrence of ${JSON.stringify(needle)} in README /app/add block, found ${count}`, + ); + } + return haystack.replace(needle, replacement); +} + +/** + * Apply the two documented substitutions to the README block: HTTP instead of + * HTTPS (CHR has no /ip/cloud certificates), and the candidate image ref. + * Anything else must come from the README, never from a second fixture. + */ +export function applyAppAddSubstitutions(block: string, imageRef: string): string { + const http = substituteOnce(block, "use-https=yes", "use-https=no"); + return substituteOnce(http, "ghcr.io/tikoci/rosetta:latest", imageRef); +} + +/** + * Assert the ui-url is the http://…/mcp shape a use-https=no leg produces, + * then rewrite only host:port to the QEMU forward. + */ +export function rewriteUiUrl(uiUrl: string, hostPort: number): string { + let parsed: URL; + try { + parsed = new URL(uiUrl.trim()); + } catch { + throw new Error(`ui-url is not a URL: ${JSON.stringify(uiUrl)}`); + } + if (parsed.protocol !== "http:") { + throw new Error(`ui-url must use http (use-https=no leg), got: ${uiUrl.trim()}`); + } + if (!parsed.pathname.startsWith("/mcp")) { + throw new Error(`ui-url must carry the /mcp path, got: ${uiUrl.trim()}`); + } + parsed.hostname = "127.0.0.1"; + parsed.port = String(hostPort); + return parsed.toString(); +} + +export interface ParsedImageRef { + registry: string; + repo: string; + /** Tag or digest (digest keeps its "sha256:…" form). */ + reference: string; + /** True when reference is a digest rather than a tag. */ + isDigest: boolean; +} + +/** Split registry/repo:tag[@digest]. A tag or digest is required. */ +export function parseImageRef(ref: string): ParsedImageRef { + const trimmed = ref.trim(); + const slash = trimmed.indexOf("/"); + let registry = "docker.io"; + let rest = trimmed; + if (slash !== -1 && (trimmed.slice(0, slash).includes(".") || trimmed.slice(0, slash).includes(":"))) { + registry = trimmed.slice(0, slash); + rest = trimmed.slice(slash + 1); + } + const at = rest.indexOf("@"); + const colon = rest.lastIndexOf(":"); + let repo = rest; + let reference = ""; + let isDigest = false; + if (at !== -1) { + repo = rest.slice(0, at); + reference = rest.slice(at + 1); + isDigest = true; + } else if (colon !== -1) { + repo = rest.slice(0, colon); + reference = rest.slice(colon + 1); + } + if (!repo || !reference) throw new Error(`Image ref must include a tag or digest: ${JSON.stringify(ref)}`); + if (registry === "docker.io" && !repo.includes("/")) repo = `library/${repo}`; + return { registry, repo, reference, isDigest }; +} + +/** Derive the bare release version from a vX.Y.Z… tag; null for floating/sha tags. */ +export function deriveVersionFromTag(tag: string): string | null { + const match = /^v?(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)$/.exec(tag.trim()); + return match ? match[1] : null; +} + +/** Registry API host for a parsed ref (Docker Hub's API host differs). */ +export function registryApiHost(registry: string): string { + return registry === "docker.io" ? "registry-1.docker.io" : registry; +} + +const SECRET_KEY = /password|passwd|secret|token|authorization|auth|credential|header/i; + +/** Deep-clone with credential-shaped values replaced (diagnostics bundle). */ +export function redactCredentials(value: T): T { + if (Array.isArray(value)) return value.map(redactCredentials) as T; + if (value !== null && typeof value === "object") { + const out: Record = {}; + for (const [key, entry] of Object.entries(value as Record)) { + out[key] = SECRET_KEY.test(key) ? "[redacted]" : redactCredentials(entry); + } + return out as T; + } + return value; +} + +/** Parse `-accel ` from a QEMU process command line (reporting only). */ +export function parseQemuAccel(argvText: string): string | null { + const match = /(?:^|\s)-accel\s+(\S+)/.exec(argvText.replace(/\n/g, " ")); + return match ? match[1].split(",")[0] : null; +} + +/** True when a container-log excerpt shows our app's container dying. */ +export function logShowsContainerExit(logText: string, containerName: string): string[] { + const hits: string[] = []; + for (const line of logText.split("\n")) { + if (line.includes(containerName) && /exited with (status|signal)/.test(line)) hits.push(line.trim()); + } + return hits; +} + +// ── Runner ─────────────────────────────────────────────────────────────────── + +interface LegConfig { + arch: "x86" | "arm64"; + image: ParsedImageRef; + imageRef: string; + version: string; + rosVersion: string; + hostPort: number; + machineName: string; + keep: boolean; + diagnosticsFile: string; +} + +interface DigestRecord { + indexDigest: string; + platforms: Array<{ os: string; arch: string; digest: string }>; +} + +const startedAt = Date.now(); +function log(message: string): void { + console.log(`[T+${Math.round((Date.now() - startedAt) / 1000)}s] ${message}`); +} + +function fail(message: string): never { + throw new Error(message); +} + +async function runCmd(argv: string[], opts: { timeoutMs?: number } = {}): Promise<{ + stdout: string; + stderr: string; + exitCode: number | null; + timedOut: boolean; +}> { + const proc = Bun.spawn(argv, { stdout: "pipe", stderr: "pipe" }); + let timedOut = false; + let timer: ReturnType | undefined; + if (opts.timeoutMs !== undefined) { + timer = setTimeout(() => { + timedOut = true; + proc.kill(); + }, opts.timeoutMs); + timer.unref?.(); + } + try { + const [stdout, stderr] = await Promise.all([ + new Response(proc.stdout).text(), + new Response(proc.stderr).text(), + ]); + const exitCode = await proc.exited; + return { stdout, stderr, exitCode, timedOut }; + } finally { + clearTimeout(timer); + } +} + +interface RestEndpoint { + url: string; + authHeader: string; +} + +/** POST one RouterOS script to /rest/execute; returns the console output. */ +async function restExecute(endpoint: RestEndpoint, script: string): Promise { + const res = await fetch(`${endpoint.url}/execute`, { + method: "POST", + headers: { Authorization: endpoint.authHeader, "Content-Type": "application/json" }, + body: JSON.stringify({ script, "as-string": true }), + signal: AbortSignal.timeout(60_000), + }); + const text = await res.text(); + if (!res.ok) fail(`REST /rest/execute HTTP ${res.status}: ${text.slice(0, 500)}`); + const body = JSON.parse(text) as { ret?: string } | unknown[]; + if (Array.isArray(body)) return ""; + return (body.ret ?? "").replace(/\r/g, ""); +} + +function parseWwwAuthenticate(header: string): { realm: string; service: string; scope: string } | null { + if (!header.startsWith("Bearer ")) return null; + const params: Record = {}; + for (const match of header.slice("Bearer ".length).matchAll(/(\w+)="([^"]*)"/g)) { + params[match[1]] = match[2]; + } + if (!params.realm) return null; + return { realm: params.realm, service: params.service ?? "", scope: params.scope ?? "" }; +} + +/** + * Resolve the multi-arch manifest digest + per-platform digests over the OCI + * HTTP API (the no-Docker equivalent of `docker buildx imagetools inspect`, + * so local and CI runs share one code path). Anonymous first; GITHUB_TOKEN / + * GH_TOKEN is used when anonymous auth is refused. + */ +async function resolveDigests(image: ParsedImageRef): Promise { + const host = registryApiHost(image.registry); + const manifestUrl = `https://${host}/v2/${image.repo}/manifests/${image.reference}`; + const accept = "application/vnd.oci.image.index.v1+json, application/vnd.docker.distribution.manifest.list.v2+json"; + const envToken = process.env.GITHUB_TOKEN ?? process.env.GH_TOKEN ?? ""; + + async function getManifest(auth?: string): Promise { + const headers: Record = { Accept: accept }; + if (auth) headers.Authorization = auth; + return fetch(manifestUrl, { headers, signal: AbortSignal.timeout(30_000) }); + } + + let res = await getManifest(envToken ? `Bearer ${envToken}` : undefined); + if (res.status === 401) { + const challenge = parseWwwAuthenticate(res.headers.get("www-authenticate") ?? ""); + if (!challenge) fail(`Registry ${host} refused anonymous access without a Bearer challenge`); + const scope = challenge.scope || `repository:${image.repo}:pull`; + const tokenUrl = `${challenge.realm}?service=${encodeURIComponent(challenge.service)}&scope=${encodeURIComponent(scope)}`; + const tokenHeaders: Record = {}; + if (envToken) tokenHeaders.Authorization = `Basic ${Buffer.from(`oauth2:${envToken}`).toString("base64")}`; + const tokenRes = await fetch(tokenUrl, { headers: tokenHeaders, signal: AbortSignal.timeout(30_000) }); + if (!tokenRes.ok) fail(`Registry token request failed: HTTP ${tokenRes.status}`); + const { token, access_token } = (await tokenRes.json()) as { token?: string; access_token?: string }; + const bearer = token ?? access_token; + if (!bearer) fail("Registry token endpoint returned no token"); + res = await getManifest(`Bearer ${bearer}`); + } + if (!res.ok) fail(`Registry manifest fetch failed: HTTP ${res.status} for ${image.repo}:${image.reference}`); + const indexDigest = res.headers.get("docker-content-digest") ?? ""; + if (!indexDigest) fail("Registry response carried no docker-content-digest header"); + const manifest = (await res.json()) as { + mediaType?: string; + manifests?: Array<{ digest?: string; platform?: { os?: string; architecture?: string } }>; + }; + const entries = manifest.manifests ?? []; + if (entries.length === 0) { + // Single-platform manifest: record it; the CHR run itself proves the platform. + log(`WARNING: ${image.repo}:${image.reference} resolved to a single manifest, not an index`); + return { indexDigest, platforms: [{ os: "unknown", arch: "unknown", digest: indexDigest }] }; + } + return { + indexDigest, + platforms: entries.map((e) => ({ + os: e.platform?.os ?? "unknown", + arch: e.platform?.architecture ?? "unknown", + digest: e.digest ?? "unknown", + })), + }; +} + +function parseArgs(argv: string[]): LegConfig { + const get = (flag: string): string | undefined => { + const index = argv.indexOf(flag); + return index === -1 ? undefined : argv[index + 1]; + }; + if (argv.includes("--help") || argv.includes("-h")) { + console.log("Usage: bun scripts/app-integration.ts --arch --image [--ros-version ] [--version ] [--host-port ] [--name ] [--diagnostics-file ] [--keep]"); + process.exit(0); + } + const arch = get("--arch"); + if (arch !== "x86" && arch !== "arm64") { + console.error("Missing or invalid --arch (want x86 or arm64). See --help."); + process.exit(2); + } + const imageRef = get("--image"); + if (!imageRef) { + console.error("Missing --image , e.g. ghcr.io/tikoci/rosetta:v0.12.0. See --help."); + process.exit(2); + } + const image = parseImageRef(imageRef); + const tagVersion = !image.isDigest ? deriveVersionFromTag(image.reference) : null; + const version = (get("--version") || tagVersion || "").replace(/^v/, ""); + if (!version) { + console.error(`Cannot derive a release version from ${JSON.stringify(image.reference)} — pass --version , e.g. --version 0.12.0.`); + process.exit(2); + } + const stamp = new Date().toISOString().replace(/[-:]/g, "").replace(/\..+/, "").replace("T", "-"); + const machineName = get("--name") ?? `rosetta-app-${arch}-${stamp}`; + if (!/^[a-z0-9][a-z0-9-]{0,62}$/.test(machineName)) { + console.error(`Invalid --name ${JSON.stringify(machineName)} (lowercase letters, digits, dashes).`); + process.exit(2); + } + return { + arch, + image, + imageRef: imageRef.trim(), + version, + rosVersion: get("--ros-version") ?? ROS_VERSION_DEFAULT, + hostPort: Number(get("--host-port") ?? GUEST_WEB_PORT), + machineName, + keep: argv.includes("--keep"), + diagnosticsFile: get("--diagnostics-file") ?? path.join(process.cwd(), `app-integration-${machineName}.json`), + }; +} + +async function assertQuickchrPin(): Promise { + const res = await runCmd(["quickchr", "--version"]); + const firstLine = res.stdout.split("\n")[0] ?? ""; + const match = /^quickchr (\S+)/.exec(firstLine.trim()); + if (res.exitCode !== 0 || !match) { + fail(`quickchr not usable: ${res.stderr.slice(0, 300) || res.stdout.slice(0, 300)}`); + } + if (match[1] !== QUICKCHR_PIN) { + fail(`quickchr ${match[1]} found, this harness pins ${QUICKCHR_PIN} — run: bun install -g @tikoci/quickchr@${QUICKCHR_PIN}`); + } + log(`quickchr ${match[1]} (pinned)`); +} + +async function readAccel(pid: number): Promise { + for (let attempt = 1; attempt <= 3; attempt++) { + const ps = await runCmd(["ps", "-p", String(pid), "-o", "args="]); + const accel = parseQemuAccel(ps.stdout); + if (accel) return accel; + await new Promise((r) => setTimeout(r, 2000)); + } + log("WARNING: could not read the QEMU -accel flag; recording accel as unknown"); + return "unknown"; +} + +interface QuickchrInspect { + pid: number; + services: { + "rest-api": { url: string; port: number; auth: { username: string; password: string; header?: string } }; + }; +} + +async function inspectMachine(name: string): Promise<{ endpoint: RestEndpoint; pid: number; raw: unknown }> { + const res = await runCmd(["quickchr", "inspect", name, "--json"]); + if (res.exitCode !== 0) fail(`quickchr inspect failed: ${res.stderr.slice(0, 500)}`); + const parsed = JSON.parse(res.stdout) as QuickchrInspect; + const rest = parsed.services["rest-api"]; + const authHeader = rest.auth.header ?? `Basic ${Buffer.from(`${rest.auth.username}:${rest.auth.password}`).toString("base64")}`; + return { endpoint: { url: rest.url, authHeader }, pid: parsed.pid, raw: parsed }; +} + +async function main(): Promise { + const config = parseArgs(process.argv.slice(2)); + const repoRoot = path.resolve(import.meta.dir, ".."); + const timings: Record = {}; + const phase = async (name: string, fn: () => Promise): Promise => { + const start = Date.now(); + try { + return await fn(); + } finally { + timings[name] = Date.now() - start; + } + }; + + const bundle: Record = { + outcome: "fail", + config: { + arch: config.arch, + image: config.imageRef, + version: config.version, + rosVersion: config.rosVersion, + hostPort: config.hostPort, + machineName: config.machineName, + quickchrPin: QUICKCHR_PIN, + hostArch: process.arch, + hostPlatform: process.platform, + }, + }; + + let endpoint: RestEndpoint | undefined; + const noteFailure = (message: string): never => { + bundle.failure = message; + throw new Error(message); + }; + + try { + // README extraction: the one fenced block starting with /app/add, exactly + // the two documented substitutions, each matching exactly once. + const readme = await Bun.file(path.join(repoRoot, "README.md")).text(); + const block = extractAppAddBlock(readme); + const appAddCommand = applyAppAddSubstitutions(block, config.imageRef); + log("Substituted /app/add command (README + 2 substitutions):"); + console.log(appAddCommand); + bundle.substitutedCommand = appAddCommand; + + await phase("preflight", async () => { + await assertQuickchrPin(); + log(`host ${process.platform}/${process.arch}, guest ${config.arch}, RouterOS ${config.rosVersion}`); + }); + + const digestsBefore = await phase("digests-before", async () => { + const digests = await resolveDigests(config.image); + log(`manifest digest: ${digests.indexDigest}`); + for (const platform of digests.platforms) { + log(`platform ${platform.os}/${platform.arch}: ${platform.digest}`); + } + return digests; + }); + bundle.digestsBefore = digestsBefore; + + await phase("boot", async () => { + log(`quickchr add ${config.machineName} (RouterOS ${config.rosVersion} ${config.arch}, ${GUEST_MEM_MB[config.arch]}MB, +${APP_DISK_GB}G disk)`); + const add = await runCmd([ + "quickchr", "add", + "--name", config.machineName, + "--version", config.rosVersion, + "--arch", config.arch, + "--mem", String(GUEST_MEM_MB[config.arch]), + "--add-disk", `${APP_DISK_GB}G`, + "--add-package", "container", + "--device-mode-enable", "container", + "--forward", `mcp:${config.hostPort}:${GUEST_WEB_PORT}/tcp`, + ]); + if (add.exitCode !== 0) noteFailure(`quickchr add failed: ${(add.stderr || add.stdout).slice(0, 800)}`); + log(`quickchr start ${config.machineName}`); + const start = await runCmd(["quickchr", "start", config.machineName], { + timeoutMs: START_TIMEOUT_MS[config.arch], + }); + if (start.timedOut) { + await runCmd(["quickchr", "stop", config.machineName]).catch(() => {}); + noteFailure(`quickchr start timed out after ${START_TIMEOUT_MS[config.arch] / 60000}min`); + } + if (start.exitCode !== 0) noteFailure(`quickchr start failed: ${(start.stderr || start.stdout).slice(0, 800)}`); + }); + + const inspected = await inspectMachine(config.machineName); + endpoint = inspected.endpoint; + bundle.quickchrInspect = redactCredentials(inspected.raw); + const accel = await readAccel(inspected.pid); + (bundle.config as Record).accel = accel; + log(`accel: ${accel}, REST: ${endpoint.url.replace(/\/\/.*@/, "//")}`); + if (config.arch === "x86" && accel !== "kvm" && accel !== "hvf" && accel !== "unknown") { + noteFailure( + `x86 leg requires hardware accel (kvm/hvf), got ${accel} — the Bun binary SIGILLs under TCG (Phase 1).`, + ); + } + + await phase("storage", async () => { + const formatted = await restExecute(endpoint as RestEndpoint, "/disk/format numbers=0 file-system=ext4"); + if (!formatted.includes("format done")) noteFailure(`disk format did not complete: ${formatted.slice(0, 300)}`); + const disks = await restExecute(endpoint as RestEndpoint, "/disk/print detail"); + const mounts = [...new Set([...disks.matchAll(/mount-point="([^"]+)"/g)].map((m) => m[1]))]; + if (mounts.length !== 1) noteFailure(`Expected exactly 1 mounted disk, found: ${JSON.stringify(mounts)}`); + const settings = await restExecute(endpoint as RestEndpoint, `/app/settings/set disk=${mounts[0]}\n/app/settings/print`); + if (!settings.includes(`disk: ${mounts[0]}`)) noteFailure(`/app/settings did not take disk=${mounts[0]}`); + log(`app disk: ${mounts[0]}`); + }); + + await phase("app-add", async () => { + const ret = await restExecute(endpoint as RestEndpoint, appAddCommand); + if (ret.trim() !== "") noteFailure(`/app/add returned an error: ${ret.slice(0, 500)}`); + log("/app/add accepted"); + }); + + const runningBudget = RUNNING_TIMEOUT_MS[config.arch]; + const uiUrl = await phase("wait-running", async () => { + const deadline = Date.now() + runningBudget; + for (;;) { + const state = await restExecute( + endpoint as RestEndpoint, + ":put [/app/get rosetta status]\n:put [/app/get rosetta running]\n:put [/app/get rosetta ui-url]", + ); + const lines = state.split("\n").map((line) => line.trim()); + const status = lines[0] ?? ""; + const running = lines[1] === "true"; + const candidateUrl = lines[2] ?? ""; + if (running && candidateUrl) { + log(`running=true, ui-url=${candidateUrl}`); + return candidateUrl; + } + const containerLog = await restExecute(endpoint as RestEndpoint, '/log/print where topics~"container"'); + const exits = logShowsContainerExit(containerLog, "app-rosetta"); + if (exits.length > 0) { + bundle.containerLogTail = containerLog.slice(-3000); + noteFailure(`Container died while starting (last: ${exits[exits.length - 1]})`); + } + if (Date.now() >= deadline) { + bundle.containerLogTail = containerLog.slice(-3000); + noteFailure(`Still not running after ${runningBudget / 60000}min (status=${JSON.stringify(status)})`); + } + log(`status=${JSON.stringify(status)} running=false — waiting`); + await new Promise((r) => setTimeout(r, POLL_INTERVAL_MS)); + } + }); + + const smokeUrl = rewriteUiUrl(uiUrl, config.hostPort); + (bundle.config as Record).uiUrl = uiUrl; + (bundle.config as Record).smokeUrl = smokeUrl; + log(`smoke URL (host:port rewrite only): ${smokeUrl}`); + + await phase("evidence", async () => { + const appDetail = await restExecute(endpoint as RestEndpoint, "/app/print detail where name=rosetta"); + const containerDetail = await restExecute(endpoint as RestEndpoint, "/container/print detail"); + bundle.appDetail = appDetail; + bundle.containerDetail = containerDetail; + const arch = /arch="([^"]+)"/.exec(containerDetail)?.[1] ?? "unknown"; + const imageId = /image-id="([0-9a-f]+)/.exec(containerDetail)?.[1] ?? "unknown"; + (bundle.config as Record).containerArch = arch; + (bundle.config as Record).containerImageId = imageId; + log(`container arch=${arch} image-id=${imageId.slice(0, 12)}`); + const digestsAfter = await resolveDigests(config.image); + bundle.digestsAfter = digestsAfter; + if (digestsAfter.indexDigest !== digestsBefore.indexDigest) { + noteFailure(`Candidate tag moved mid-run: ${digestsBefore.indexDigest} -> ${digestsAfter.indexDigest}`); + } + log("manifest digest unchanged after the run"); + }); + + await phase("smoke", async () => { + const smoke = await runCmd( + [process.execPath, path.join(import.meta.dir, "smoke-oci.ts"), smokeUrl, config.version], + { timeoutMs: 5 * 60_000 }, + ); + bundle.smokeStdout = smoke.stdout; + bundle.smokeStderr = smoke.stderr; + console.log(smoke.stdout.trimEnd()); + if (smoke.timedOut) noteFailure("MCP smoke timed out after 5min"); + if (smoke.exitCode !== 0) noteFailure(`MCP smoke failed (exit ${smoke.exitCode}): ${(smoke.stderr || smoke.stdout).slice(0, 800)}`); + }); + + bundle.outcome = "pass"; + bundle.timings = timings; + log(`APP-INTEGRATION PASS: ${config.arch} serves ${config.imageRef} (provenance v${config.version})`); + } catch (error) { + bundle.outcome = "fail"; + bundle.timings = timings; + if (bundle.failure === undefined) bundle.failure = error instanceof Error ? error.message : String(error); + await collectFailureDiagnostics(endpoint, bundle).catch((diagnosticError) => { + log(`Diagnostics collection failed: ${diagnosticError instanceof Error ? diagnosticError.message : diagnosticError}`); + }); + log(`APP-INTEGRATION FAIL: ${bundle.failure}`); + } finally { + bundle.config = redactCredentials(bundle.config); + await Bun.write(config.diagnosticsFile, `${JSON.stringify(bundle, null, 2)}\n`); + log(`diagnostics bundle: ${config.diagnosticsFile}`); + appendStepSummary(config, bundle as { outcome: string; failure?: string; config?: Record; digestsBefore?: DigestRecord }); + if (!config.keep) { + log(`cleanup: quickchr stop/remove ${config.machineName}`); + const stop = await runCmd(["quickchr", "stop", config.machineName]).catch(() => null); + if (stop && stop.exitCode !== 0) log(`cleanup stop warning: ${(stop.stderr || stop.stdout).slice(0, 300)}`); + const remove = await runCmd(["quickchr", "remove", config.machineName]).catch(() => null); + if (remove && remove.exitCode !== 0) log(`cleanup remove warning: ${(remove.stderr || remove.stdout).slice(0, 300)}`); + } else { + log(`--keep: machine ${config.machineName} left running`); + } + } + + if (bundle.outcome !== "pass") process.exit(1); +} + +async function collectFailureDiagnostics(endpoint: RestEndpoint | undefined, bundle: Record): Promise { + if (!endpoint) { + log("no REST endpoint — VM never became reachable; skipping router diagnostics"); + return; + } + log("collecting failure diagnostics (/app, /container, /log)..."); + const appDetail = await restExecute(endpoint, "/app/print detail where name=rosetta").catch((e) => `unavailable: ${e}`); + const containerDetail = await restExecute(endpoint, "/container/print detail").catch((e) => `unavailable: ${e}`); + const routerLog = await restExecute(endpoint, '/log/print where topics~"container"').catch((e) => `unavailable: ${e}`); + bundle.appDetail = appDetail; + bundle.containerDetail = containerDetail; + bundle.containerLogTail = typeof routerLog === "string" ? routerLog.slice(-4000) : routerLog; + console.log("--- /app/print detail ---\n" + String(appDetail).slice(0, 3000)); + console.log("--- /container/print detail ---\n" + String(containerDetail).slice(0, 4000)); + console.log("--- container log tail ---\n" + String(bundle.containerLogTail).slice(-2000)); +} + +function appendStepSummary( + config: LegConfig, + bundle: { outcome: string; failure?: string; config?: Record; digestsBefore?: DigestRecord }, +): void { + const summaryFile = process.env.GITHUB_STEP_SUMMARY; + if (!summaryFile) return; + const rows: Array<[string, string]> = [ + ["arch", config.arch], + ["image", config.imageRef], + ["outcome", bundle.outcome], + ["manifest digest", bundle.digestsBefore?.indexDigest ?? "unknown"], + ["accel", String(bundle.config?.accel ?? "unknown")], + ["container arch", String(bundle.config?.containerArch ?? "unknown")], + ["ui-url", String(bundle.config?.uiUrl ?? "unknown")], + ]; + if (bundle.failure) rows.push(["failure", String(bundle.failure)]); + const table = ["| key | value |", "| --- | --- |", ...rows.map(([k, v]) => `| ${k} | ${v} |`)].join("\n"); + Bun.write(summaryFile, `\n## app-integration (${config.arch})\n\n${table}\n`).catch(() => {}); +} + +process.on("SIGINT", () => process.exit(130)); +process.on("SIGTERM", () => process.exit(143)); + +if (import.meta.main) { + await main(); +} + diff --git a/scripts/smoke-oci.ts b/scripts/smoke-oci.ts new file mode 100644 index 0000000..0546c2b --- /dev/null +++ b/scripts/smoke-oci.ts @@ -0,0 +1,96 @@ +#!/usr/bin/env bun +/** + * smoke-oci.ts — real MCP session against a rosetta HTTP endpoint. + * + * Usage: bun scripts/smoke-oci.ts + * + * Full MCP endpoint URL, e.g. http://127.0.0.1:9803/mcp + * Expected release version, bare (0.12.0) or v-prefixed (v0.12.0) + * + * Runs initialize → tools/list → routeros_stats (provenance must equal + * v) → nonempty routeros_search. Exits 0 on success, 1 on any + * protocol, tool, or provenance failure. Shared by #245 (RouterOS /app + * integration, any reachable URL) and #246 (release OCI smoke). + */ +import { Client } from "@modelcontextprotocol/sdk/client/index.js"; +import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js"; + +const CONNECT_TIMEOUT_MS = 120_000; +const CALL_TIMEOUT_MS = 120_000; + +function usage(): never { + console.error("Usage: bun scripts/smoke-oci.ts "); + console.error(" MCP endpoint, e.g. http://127.0.0.1:9803/mcp"); + console.error(" expected release version, e.g. 0.12.0"); + process.exit(2); + throw new Error("unreachable"); +} + +async function withTimeout(label: string, ms: number, fn: () => Promise): Promise { + let timer: ReturnType | undefined; + const timeout = new Promise((_, reject) => { + timer = setTimeout(() => reject(new Error(`${label} timed out after ${ms}ms`)), ms); + }); + try { + return await Promise.race([fn(), timeout]); + } finally { + clearTimeout(timer); + } +} + +const [urlArg, versionArg] = process.argv.slice(2); +if (!urlArg || !versionArg) usage(); + +let url: URL; +try { + url = new URL(urlArg); +} catch { + console.error(`Invalid URL: ${urlArg}`); + process.exit(2); + throw new Error("unreachable"); +} +const expectedTag = `v${versionArg.replace(/^v/, "")}`; +const client = new Client({ name: "rosetta-oci-smoke", version: "1" }); + +try { + const started = Date.now(); + await withTimeout("MCP connect/initialize", CONNECT_TIMEOUT_MS, async () => { + const transport = new StreamableHTTPClientTransport(url); + await client.connect(transport); + }); + console.log(`initialize: ok (${Date.now() - started}ms)`); + + const tools = await withTimeout("tools/list", CALL_TIMEOUT_MS, () => client.listTools()); + const names = (tools.tools ?? []).map((t) => t.name); + console.log(`tools/list: ${names.length} tools (${names.join(", ")})`); + for (const need of ["routeros_stats", "routeros_search"]) { + if (!names.includes(need)) throw new Error(`tools/list is missing required tool: ${need}`); + } + + const statsRes = await withTimeout("routeros_stats", CALL_TIMEOUT_MS, () => + client.callTool({ name: "routeros_stats", arguments: {} }), + ); + if (statsRes.isError) throw new Error(`routeros_stats returned an error: ${JSON.stringify(statsRes).slice(0, 500)}`); + const stats = JSON.parse((statsRes.content as { text: string }[])[0].text) as { + provenance?: { release_tag?: string }; + }; + console.log(`provenance.release_tag: ${stats.provenance?.release_tag} (expected ${expectedTag})`); + if (stats.provenance?.release_tag !== expectedTag) { + throw new Error(`Provenance mismatch: got ${stats.provenance?.release_tag}, expected ${expectedTag}`); + } + + const search = await withTimeout("routeros_search", CALL_TIMEOUT_MS, () => + client.callTool({ name: "routeros_search", arguments: { query: "firewall" } }), + ); + if (search.isError) throw new Error(`routeros_search returned an error: ${JSON.stringify(search).slice(0, 500)}`); + const text = (search.content as { text: string }[])[0].text; + console.log(`routeros_search: ${text.length} chars`); + if (text.length === 0) throw new Error("routeros_search returned empty content"); + + console.log(`SMOKE OK: ${urlArg} serves ${expectedTag} (${Date.now() - started}ms)`); +} catch (error) { + console.error(`SMOKE FAIL: ${error instanceof Error ? error.message : error}`); + process.exitCode = 1; +} finally { + await client.close().catch(() => {}); +} diff --git a/src/app-integration.test.ts b/src/app-integration.test.ts new file mode 100644 index 0000000..38b7ab4 --- /dev/null +++ b/src/app-integration.test.ts @@ -0,0 +1,281 @@ +/** + * app-integration.test.ts — RouterOS /app integration harness (#245). + * + * Unit tests for the pure helpers in scripts/app-integration.ts (README + * extraction, substitutions, ui-url rewrite, image-ref parsing, redaction) + * plus structural checks pinning the app-integration.yml workflow shape. + * No network, no VMs — just file reads and pure functions. + */ +import { describe, expect, test } from "bun:test"; +import { readFileSync } from "node:fs"; +import path from "node:path"; +import { + APP_DISK_GB, + applyAppAddSubstitutions, + deriveVersionFromTag, + extractAppAddBlock, + logShowsContainerExit, + parseImageRef, + parseQemuAccel, + QUICKCHR_PIN, + ROS_VERSION_DEFAULT, + redactCredentials, + registryApiHost, + rewriteUiUrl, +} from "../scripts/app-integration.ts"; + +const ROOT = path.resolve(import.meta.dirname, ".."); + +function readText(relPath: string): string { + return readFileSync(path.join(ROOT, relPath), "utf-8"); +} + +const SAMPLE_BLOCK = `/app/add use-https=yes disabled=no yaml="name: rosetta +descr: \\"docs\\" +services: + rosetta: + image: ghcr.io/tikoci/rosetta:latest + ports: + - 9803:8080/tcp:web +"`; + +describe("extractAppAddBlock", () => { + test("finds the one /app/add block among other fences", () => { + const readme = [ + "# title", + "", + "```routeros", + "/system/identity/print", + "```", + "", + "```routeros", + SAMPLE_BLOCK, + "```", + "", + "```sh", + "/app/add use-https=yes", + "```", + "", + ].join("\n"); + expect(extractAppAddBlock(readme)).toBe(SAMPLE_BLOCK); + }); + + test("throws when no /app/add block exists", () => { + expect(() => extractAppAddBlock("# empty\n")).toThrow(/no fenced routeros block/); + }); + + test("throws when two /app/add blocks exist", () => { + const readme = `\`\`\`routeros\n${SAMPLE_BLOCK}\n\`\`\`\n\`\`\`routeros\n${SAMPLE_BLOCK}\n\`\`\`\n`; + expect(() => extractAppAddBlock(readme)).toThrow(/exactly 1/); + }); + + test("the real README has exactly one /app/add block", () => { + const block = extractAppAddBlock(readText("README.md")); + expect(block).toContain("use-https=yes"); + expect(block).toContain("ghcr.io/tikoci/rosetta:latest"); + }); +}); + +describe("applyAppAddSubstitutions", () => { + test("applies exactly the two documented substitutions", () => { + const out = applyAppAddSubstitutions(SAMPLE_BLOCK, "ghcr.io/tikoci/rosetta:sha-abc123"); + expect(out).toContain("use-https=no"); + expect(out).not.toContain("use-https=yes"); + expect(out).toContain("ghcr.io/tikoci/rosetta:sha-abc123"); + expect(out).not.toContain("ghcr.io/tikoci/rosetta:latest"); + // Everything else is byte-identical to the input. + expect(out.replace("use-https=no", "use-https=yes").replace("ghcr.io/tikoci/rosetta:sha-abc123", "ghcr.io/tikoci/rosetta:latest")).toBe( + SAMPLE_BLOCK, + ); + }); + + test("fails unless use-https=yes matches exactly once", () => { + expect(() => applyAppAddSubstitutions("no match here", "img")).toThrow(/exactly 1/); + expect(() => applyAppAddSubstitutions("use-https=yes use-https=yes", "img")).toThrow(/exactly 1/); + }); + + test("fails unless the image ref matches exactly once", () => { + const missing = SAMPLE_BLOCK.replace("ghcr.io/tikoci/rosetta:latest", "other/image:tag"); + expect(() => applyAppAddSubstitutions(missing, "img")).toThrow(/exactly 1/); + const doubled = SAMPLE_BLOCK.replace("latest", "latest ghcr.io/tikoci/rosetta:latest"); + expect(() => applyAppAddSubstitutions(doubled, "img")).toThrow(/exactly 1/); + }); +}); + +describe("rewriteUiUrl", () => { + test("rewrites only host:port", () => { + expect(rewriteUiUrl("http://10.0.2.15:9803/mcp", 9803)).toBe("http://127.0.0.1:9803/mcp"); + expect(rewriteUiUrl("http://10.0.2.15:9803/mcp", 9999)).toBe("http://127.0.0.1:9999/mcp"); + }); + + test("rejects https (wrong leg shape)", () => { + expect(() => rewriteUiUrl("https://10.0.2.15:9803/mcp", 9803)).toThrow(/must use http/); + }); + + test("rejects a missing /mcp path", () => { + expect(() => rewriteUiUrl("http://10.0.2.15:9803/", 9803)).toThrow(/\/mcp path/); + }); + + test("rejects garbage", () => { + expect(() => rewriteUiUrl("", 9803)).toThrow(/not a URL/); + expect(() => rewriteUiUrl("not a url", 9803)).toThrow(/not a URL/); + }); +}); + +describe("parseImageRef", () => { + test("parses registry/repo:tag", () => { + expect(parseImageRef("ghcr.io/tikoci/rosetta:v0.12.0")).toEqual({ + registry: "ghcr.io", + repo: "tikoci/rosetta", + reference: "v0.12.0", + isDigest: false, + }); + }); + + test("parses repo@digest", () => { + const parsed = parseImageRef("ghcr.io/tikoci/rosetta@sha256:9fbf37e0"); + expect(parsed.isDigest).toBe(true); + expect(parsed.reference).toBe("sha256:9fbf37e0"); + }); + + test("requires a tag or digest", () => { + expect(() => parseImageRef("ghcr.io/tikoci/rosetta")).toThrow(/must include a tag or digest/); + }); + + test("docker.io gets the library/ prefix", () => { + expect(parseImageRef("alpine:3.21").repo).toBe("library/alpine"); + }); +}); + +describe("deriveVersionFromTag", () => { + test("strips a v prefix and keeps prereleases", () => { + expect(deriveVersionFromTag("v0.12.0")).toBe("0.12.0"); + expect(deriveVersionFromTag("0.12.0")).toBe("0.12.0"); + expect(deriveVersionFromTag("v0.12.0-next.125")).toBe("0.12.0-next.125"); + }); + + test("returns null for floating/sha tags", () => { + expect(deriveVersionFromTag("latest")).toBeNull(); + expect(deriveVersionFromTag("next")).toBeNull(); + expect(deriveVersionFromTag("sha-abc123")).toBeNull(); + }); +}); + +describe("registryApiHost", () => { + test("maps docker.io to its API host, leaves others alone", () => { + expect(registryApiHost("docker.io")).toBe("registry-1.docker.io"); + expect(registryApiHost("ghcr.io")).toBe("ghcr.io"); + }); +}); + +describe("redactCredentials", () => { + test("redacts credential-shaped keys at any depth, keeps the rest", () => { + const input = { + url: "http://127.0.0.1:9110/rest", + auth: { username: "admin", password: "", header: "Basic eQ==" }, + nested: { token: "abc", port: 9110 }, + }; + expect(redactCredentials(input) as unknown).toEqual({ + url: "http://127.0.0.1:9110/rest", + auth: "[redacted]", + nested: { token: "[redacted]", port: 9110 }, + }); + // Input untouched. + expect(input.auth.header).toBe("Basic eQ=="); + }); +}); + +describe("parseQemuAccel", () => { + test("reads the -accel flag value", () => { + expect(parseQemuAccel("qemu-system-x86_64 -accel hvf -m 512")).toBe("hvf"); + expect(parseQemuAccel("qemu-system-aarch64 -accel tcg,tb-size=256 -m 1024")).toBe("tcg"); + expect(parseQemuAccel("qemu-system-x86_64 -accel kvm -cpu host")).toBe("kvm"); + expect(parseQemuAccel("qemu-system-x86_64 -m 512")).toBeNull(); + }); +}); + +describe("logShowsContainerExit", () => { + test("matches our container's deaths, ignores neighbors", () => { + const logText = [ + "2026-10-30 container,info,debug app-rosetta: *** started /entrypoint.sh", + "2026-10-30 container,error,debug app-rosetta: exited with status 1", + "2026-10-30 container,error,debug other-thing: exited with status 1", + "2026-10-30 container,error,debug app-rosetta: exited with signal 4 (Illegal instruction)", + ].join("\n"); + const hits = logShowsContainerExit(logText, "app-rosetta"); + expect(hits).toHaveLength(2); + expect(hits[0]).toContain("status 1"); + expect(hits[1]).toContain("signal 4"); + }); + + test("empty when nothing died", () => { + expect(logShowsContainerExit("all quiet", "app-rosetta")).toEqual([]); + }); +}); + +describe("recipe pins", () => { + test("RouterOS default is one stable >= 7.22", () => { + expect(ROS_VERSION_DEFAULT).toMatch(/^7\.(2[2-9]|[3-9]\d)(\.\d+)?$/); + }); + + test("app disk leaves headroom (Phase 1: 2G fails on arm64)", () => { + expect(APP_DISK_GB).toBeGreaterThanOrEqual(4); + }); +}); + +describe("app-integration.yml", () => { + const yml = readText(".github/workflows/app-integration.yml"); + + test("workflow file exists and is dispatch-only", () => { + expect(yml).toContain("workflow_dispatch:"); + // No push/pull_request triggers anywhere in the triggers block: releases + // are #246's job, and a skipped leg must never pass silently. + const onBlock = yml.slice(yml.indexOf("\non:"), yml.indexOf("\npermissions:")); + expect(onBlock).not.toContain("push:"); + expect(onBlock).not.toContain("pull_request:"); + }); + + test("both legs run independently (matrix, no fail-fast, no conditions)", () => { + expect(yml).toContain("fail-fast: false"); + expect(yml).toContain("- arch: x86"); + expect(yml).toContain("- arch: arm64"); + expect(yml).toContain("runs-on: ubuntu-latest"); + expect(yml).toContain("runs-on: ubuntu-24.04-arm"); + expect(yml).not.toContain("continue-on-error"); + }); + + test("quickchr install matches the script pin", () => { + expect(yml).toContain(`@tikoci/quickchr@${QUICKCHR_PIN}`); + }); + + test("takes the candidate image, ros version, and expected version inputs", () => { + for (const input of ["image:", "ros_version:", "version:"]) { + expect(yml).toContain(input); + } + expect(yml).toContain("--image $" + "{{ inputs.image }}"); + }); + + test("diagnostics upload always runs", () => { + expect(yml).toContain("if: always()"); + expect(yml).toContain("app-integration-*.json"); + }); +}); + +describe("app-integration Makefile target", () => { + const makefile = readText("Makefile"); + + test("target exists with ARCH/IMAGE/ROS_VERSION knobs and IMAGE required", () => { + expect(makefile).toContain("app-integration:"); + expect(makefile).toContain("ARCH ?= x86"); + expect(makefile).toContain("IMAGE ?="); + expect(makefile).toContain("ROS_VERSION ?= 7.25"); + expect(makefile).toContain("$(error IMAGE is required"); + expect(makefile).toContain("scripts/app-integration.ts --arch $(ARCH) --image $(IMAGE)"); + }); + + test("target is phony", () => { + const phonyStart = makefile.indexOf(".PHONY:"); + const phonyEnd = makefile.indexOf("\n\n", phonyStart); + expect(makefile.slice(phonyStart, phonyEnd)).toContain("app-integration"); + }); +}); From 39271e127744a2ad739155476839eca5745263e6 Mon Sep 17 00:00:00 2001 From: SkyFi Geek <45924209+mobileskyfi@users.noreply.github.com> Date: Fri, 30 Oct 2026 17:28:16 -0700 Subject: [PATCH 2/7] TEMP: pre-merge proof run of app-integration.yml (remove before merge) --- .github/workflows/app-integration.yml | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/.github/workflows/app-integration.yml b/.github/workflows/app-integration.yml index e96c201..9d567e6 100644 --- a/.github/workflows/app-integration.yml +++ b/.github/workflows/app-integration.yml @@ -19,6 +19,11 @@ name: App Integration # are no leg conditions). on: + # TEMP (pre-merge proof only — remove before merge): workflow_dispatch cannot + # be dispatched until this file exists on main, so rehearse via a + # branch-filtered push trigger once, then delete this block. + push: + branches: [feat/app-integration] workflow_dispatch: inputs: image: @@ -84,9 +89,10 @@ jobs: timeout-minutes: ${{ matrix.step-timeout }} run: | set -eo pipefail + # TEMP (pre-merge proof only — push events carry no inputs, so the + # candidate is hardcoded here; the shipped revision takes inputs.*). bun scripts/app-integration.ts --arch ${{ matrix.arch }} \ - --image ${{ inputs.image }} --ros-version ${{ inputs.ros_version }} \ - --version "${{ inputs.version }}" + --image ghcr.io/tikoci/rosetta:v0.12.0 --ros-version 7.25 --version "" - name: Upload diagnostics bundle if: always() From cbc3a22c8a47b63e90383e0cdb28fb476fe7d3b3 Mon Sep 17 00:00:00 2001 From: SkyFi Geek <45924209+mobileskyfi@users.noreply.github.com> Date: Fri, 30 Oct 2026 17:34:10 -0700 Subject: [PATCH 3/7] Enable KVM for the x86 app-integration leg MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Proof run 41150341700 showed hosted ubuntu-latest ships /dev/kvm without runner write access: quickchr fell back to TCG and the harness failed the leg at its accel gate (correctly — the Bun binary SIGILLs under TCG). chmod 666 the device on the x86 leg before running. --- .github/workflows/app-integration.yml | 12 ++++++++++++ src/app-integration.test.ts | 5 +++++ 2 files changed, 17 insertions(+) diff --git a/.github/workflows/app-integration.yml b/.github/workflows/app-integration.yml index 9d567e6..d4de34a 100644 --- a/.github/workflows/app-integration.yml +++ b/.github/workflows/app-integration.yml @@ -80,6 +80,18 @@ jobs: sudo apt-get update sudo apt-get install -y qemu-system-x86 qemu-system-arm qemu-utils qemu-efi-aarch64 + # The x86 leg needs KVM: the Bun binary SIGILLs under TCG (Phase 1), and + # hosted x64 runners ship /dev/kvm without runner write access — without + # this step quickchr falls back to TCG and the leg fails at the harness + # accel gate instead of running. + - name: Enable KVM (x86 leg) + if: matrix.arch == 'x86' + run: | + set -eo pipefail + ls -la /dev/kvm || { echo "::error::No /dev/kvm on this runner — the x86 leg needs nested KVM"; exit 1; } + sudo chmod 666 /dev/kvm + ls -la /dev/kvm + # Pinned to match QUICKCHR_PIN in scripts/app-integration.ts (the script # asserts the pin; src/app-integration.test.ts asserts they agree). - name: Install pinned quickchr diff --git a/src/app-integration.test.ts b/src/app-integration.test.ts index 38b7ab4..0e8e4b7 100644 --- a/src/app-integration.test.ts +++ b/src/app-integration.test.ts @@ -248,6 +248,11 @@ describe("app-integration.yml", () => { expect(yml).toContain(`@tikoci/quickchr@${QUICKCHR_PIN}`); }); + test("x86 leg enables KVM (the Bun binary SIGILLs under TCG)", () => { + expect(yml).toContain("Enable KVM (x86 leg)"); + expect(yml).toContain("chmod 666 /dev/kvm"); + }); + test("takes the candidate image, ros version, and expected version inputs", () => { for (const input of ["image:", "ros_version:", "version:"]) { expect(yml).toContain(input); From badf3498f1bbfe9f584cacef26c99497f6173fa0 Mon Sep 17 00:00:00 2001 From: SkyFi Geek <45924209+mobileskyfi@users.noreply.github.com> Date: Fri, 30 Oct 2026 17:39:33 -0700 Subject: [PATCH 4/7] Remove pre-merge proof trigger (both legs green in run 41150883014) The branch-filtered push trigger and hardcoded candidate served their purpose: x86 (KVM, 1m40s) and arm64 (TCG, 4m31s) both passed against manifest sha256:9fbf37e0. Back to dispatch-only for merge. --- .github/workflows/app-integration.yml | 10 ++-------- 1 file changed, 2 insertions(+), 8 deletions(-) diff --git a/.github/workflows/app-integration.yml b/.github/workflows/app-integration.yml index d4de34a..1f53130 100644 --- a/.github/workflows/app-integration.yml +++ b/.github/workflows/app-integration.yml @@ -19,11 +19,6 @@ name: App Integration # are no leg conditions). on: - # TEMP (pre-merge proof only — remove before merge): workflow_dispatch cannot - # be dispatched until this file exists on main, so rehearse via a - # branch-filtered push trigger once, then delete this block. - push: - branches: [feat/app-integration] workflow_dispatch: inputs: image: @@ -101,10 +96,9 @@ jobs: timeout-minutes: ${{ matrix.step-timeout }} run: | set -eo pipefail - # TEMP (pre-merge proof only — push events carry no inputs, so the - # candidate is hardcoded here; the shipped revision takes inputs.*). bun scripts/app-integration.ts --arch ${{ matrix.arch }} \ - --image ghcr.io/tikoci/rosetta:v0.12.0 --ros-version 7.25 --version "" + --image ${{ inputs.image }} --ros-version ${{ inputs.ros_version }} \ + --version "${{ inputs.version }}" - name: Upload diagnostics bundle if: always() From bb38a3c10a4078e0f2d8073855932750b40653df Mon Sep 17 00:00:00 2001 From: SkyFi Geek <45924209+mobileskyfi@users.noreply.github.com> Date: Fri, 30 Oct 2026 17:55:59 -0700 Subject: [PATCH 5/7] Address bot review threads on #248 - Ownership-gated cleanup: only stop/remove a VM this run created; the signal path writes a cancelled bundle and cleans up too (was: exit() leaked the VM), with handlers registered only under import.meta.main. - Registry credentials: anonymous-first; GitHub tokens only for ghcr.io and only to a challenge realm on the API host itself. - parseImageRef strips a tag from repo:tag@digest refs. - smoke-oci asserts routeros_search returns >= 1 page (an empty result set is valid JSON metadata, so a length check could not fail). - Workflow: candidate image input has no floating default (accepting all defaults used to fail both legs); inputs cross into run: via env:. --- .github/workflows/app-integration.yml | 11 ++- scripts/app-integration.ts | 97 ++++++++++++++++++--- scripts/smoke-oci.ts | 121 +++++++++++++++----------- src/app-integration.test.ts | 52 ++++++++++- 4 files changed, 212 insertions(+), 69 deletions(-) diff --git a/.github/workflows/app-integration.yml b/.github/workflows/app-integration.yml index 1f53130..ec74c75 100644 --- a/.github/workflows/app-integration.yml +++ b/.github/workflows/app-integration.yml @@ -24,7 +24,6 @@ on: image: description: "Candidate image ref, e.g. ghcr.io/tikoci/rosetta:sha-abc123 or :v0.12.0" required: true - default: "ghcr.io/tikoci/rosetta:latest" ros_version: description: "RouterOS version for both legs (one stable >= 7.22)" required: false @@ -94,11 +93,15 @@ jobs: - name: Run integration leg timeout-minutes: ${{ matrix.step-timeout }} + env: + APP_IMAGE: ${{ inputs.image }} + APP_ROS_VERSION: ${{ inputs.ros_version }} + APP_VERSION: ${{ inputs.version }} run: | set -eo pipefail - bun scripts/app-integration.ts --arch ${{ matrix.arch }} \ - --image ${{ inputs.image }} --ros-version ${{ inputs.ros_version }} \ - --version "${{ inputs.version }}" + bun scripts/app-integration.ts --arch "${{ matrix.arch }}" \ + --image "$APP_IMAGE" --ros-version "$APP_ROS_VERSION" \ + --version "$APP_VERSION" - name: Upload diagnostics bundle if: always() diff --git a/scripts/app-integration.ts b/scripts/app-integration.ts index 05adb34..8ab08b7 100644 --- a/scripts/app-integration.ts +++ b/scripts/app-integration.ts @@ -127,7 +127,7 @@ export function parseImageRef(ref: string): ParsedImageRef { let reference = ""; let isDigest = false; if (at !== -1) { - repo = rest.slice(0, at); + repo = rest.slice(0, at).replace(/:[^/]*$/, ""); reference = rest.slice(at + 1); isDigest = true; } else if (colon !== -1) { @@ -150,6 +150,23 @@ export function registryApiHost(registry: string): string { return registry === "docker.io" ? "registry-1.docker.io" : registry; } +/** + * GitHub tokens authenticate only to GitHub's registry. A local run can point + * --image at any registry, and those credentials must never leave ghcr.io. + */ +export function registryCredential(registry: string, envToken: string): string { + return registry === "ghcr.io" ? envToken : ""; +} + +/** A Bearer challenge realm is trusted for credentials only on the API host itself. */ +export function isTrustedChallengeRealm(realm: string, apiHost: string): boolean { + try { + return new URL(realm).host === apiHost; + } catch { + return false; + } +} + const SECRET_KEY = /password|passwd|secret|token|authorization|auth|credential|header/i; /** Deep-clone with credential-shaped values replaced (diagnostics bundle). */ @@ -284,15 +301,24 @@ async function resolveDigests(image: ParsedImageRef): Promise { return fetch(manifestUrl, { headers, signal: AbortSignal.timeout(30_000) }); } - let res = await getManifest(envToken ? `Bearer ${envToken}` : undefined); + // Anonymous first, always. A GitHub token is only ever attached for ghcr.io, + // and only to a challenge realm on the API host itself — never to a + // third-party registry or a registry-chosen host. + const credential = registryCredential(image.registry, envToken); + let res = await getManifest(); if (res.status === 401) { const challenge = parseWwwAuthenticate(res.headers.get("www-authenticate") ?? ""); if (!challenge) fail(`Registry ${host} refused anonymous access without a Bearer challenge`); const scope = challenge.scope || `repository:${image.repo}:pull`; const tokenUrl = `${challenge.realm}?service=${encodeURIComponent(challenge.service)}&scope=${encodeURIComponent(scope)}`; - const tokenHeaders: Record = {}; - if (envToken) tokenHeaders.Authorization = `Basic ${Buffer.from(`oauth2:${envToken}`).toString("base64")}`; - const tokenRes = await fetch(tokenUrl, { headers: tokenHeaders, signal: AbortSignal.timeout(30_000) }); + const trusted = credential !== "" && isTrustedChallengeRealm(challenge.realm, host); + let tokenRes = await fetch(tokenUrl, { signal: AbortSignal.timeout(30_000) }); + if (!tokenRes.ok && trusted) { + tokenRes = await fetch(tokenUrl, { + headers: { Authorization: `Basic ${Buffer.from(`oauth2:${credential}`).toString("base64")}` }, + signal: AbortSignal.timeout(30_000), + }); + } if (!tokenRes.ok) fail(`Registry token request failed: HTTP ${tokenRes.status}`); const { token, access_token } = (await tokenRes.json()) as { token?: string; access_token?: string }; const bearer = token ?? access_token; @@ -407,6 +433,40 @@ async function inspectMachine(name: string): Promise<{ endpoint: RestEndpoint; p return { endpoint: { url: rest.url, authHeader }, pid: parsed.pid, raw: parsed }; } +// Signal-safe shutdown shares these with main(): the machine name is recorded +// only after *this* run creates it, so a signal (or the finally block) never +// touches a VM it does not own. Cleared after normal completion. +let ownedMachineName: string | null = null; +let activeBundle: Record | null = null; +let activeBundlePath: string | null = null; +let keepMachineOnSignal = false; +let signalShuttingDown = false; + +async function cleanupMachine(name: string): Promise { + const stop = await runCmd(["quickchr", "stop", name]).catch(() => null); + if (stop && stop.exitCode !== 0) log(`cleanup stop warning: ${(stop.stderr || stop.stdout).slice(0, 300)}`); + const remove = await runCmd(["quickchr", "remove", name]).catch(() => null); + if (remove && remove.exitCode !== 0) log(`cleanup remove warning: ${(remove.stderr || remove.stdout).slice(0, 300)}`); +} + +async function shutdownOnSignal(code: number): Promise { + if (signalShuttingDown) process.exit(1); + signalShuttingDown = true; + try { + if (activeBundle && activeBundlePath) { + activeBundle.outcome = "cancelled"; + activeBundle.failure = `interrupted by ${code === 130 ? "SIGINT" : "SIGTERM"}`; + await Bun.write(activeBundlePath, `${JSON.stringify(activeBundle, null, 2)}\n`); + } + if (ownedMachineName && !keepMachineOnSignal) { + console.log(`interrupted — cleaning up ${ownedMachineName}...`); + await cleanupMachine(ownedMachineName); + } + } finally { + process.exit(code); + } +} + async function main(): Promise { const config = parseArgs(process.argv.slice(2)); const repoRoot = path.resolve(import.meta.dir, ".."); @@ -436,6 +496,9 @@ async function main(): Promise { }; let endpoint: RestEndpoint | undefined; + activeBundle = bundle; + activeBundlePath = config.diagnosticsFile; + keepMachineOnSignal = config.keep; const noteFailure = (message: string): never => { bundle.failure = message; throw new Error(message); @@ -480,6 +543,7 @@ async function main(): Promise { "--forward", `mcp:${config.hostPort}:${GUEST_WEB_PORT}/tcp`, ]); if (add.exitCode !== 0) noteFailure(`quickchr add failed: ${(add.stderr || add.stdout).slice(0, 800)}`); + ownedMachineName = config.machineName; log(`quickchr start ${config.machineName}`); const start = await runCmd(["quickchr", "start", config.machineName], { timeoutMs: START_TIMEOUT_MS[config.arch], @@ -603,14 +667,18 @@ async function main(): Promise { log(`diagnostics bundle: ${config.diagnosticsFile}`); appendStepSummary(config, bundle as { outcome: string; failure?: string; config?: Record; digestsBefore?: DigestRecord }); if (!config.keep) { - log(`cleanup: quickchr stop/remove ${config.machineName}`); - const stop = await runCmd(["quickchr", "stop", config.machineName]).catch(() => null); - if (stop && stop.exitCode !== 0) log(`cleanup stop warning: ${(stop.stderr || stop.stdout).slice(0, 300)}`); - const remove = await runCmd(["quickchr", "remove", config.machineName]).catch(() => null); - if (remove && remove.exitCode !== 0) log(`cleanup remove warning: ${(remove.stderr || remove.stdout).slice(0, 300)}`); + if (ownedMachineName) { + log(`cleanup: quickchr stop/remove ${ownedMachineName}`); + await cleanupMachine(ownedMachineName); + } else { + log("cleanup skipped: this run never created its VM"); + } } else { log(`--keep: machine ${config.machineName} left running`); } + ownedMachineName = null; + activeBundle = null; + activeBundlePath = null; } if (bundle.outcome !== "pass") process.exit(1); @@ -653,10 +721,13 @@ function appendStepSummary( Bun.write(summaryFile, `\n## app-integration (${config.arch})\n\n${table}\n`).catch(() => {}); } -process.on("SIGINT", () => process.exit(130)); -process.on("SIGTERM", () => process.exit(143)); - if (import.meta.main) { + process.on("SIGINT", () => { + void shutdownOnSignal(130); + }); + process.on("SIGTERM", () => { + void shutdownOnSignal(143); + }); await main(); } diff --git a/scripts/smoke-oci.ts b/scripts/smoke-oci.ts index 0546c2b..0cab157 100644 --- a/scripts/smoke-oci.ts +++ b/scripts/smoke-oci.ts @@ -8,8 +8,8 @@ * Expected release version, bare (0.12.0) or v-prefixed (v0.12.0) * * Runs initialize → tools/list → routeros_stats (provenance must equal - * v) → nonempty routeros_search. Exits 0 on success, 1 on any - * protocol, tool, or provenance failure. Shared by #245 (RouterOS /app + * v) → routeros_search with at least one page. Exits 0 on success, 1 + * on any protocol, tool, or provenance failure. Shared by #245 (RouterOS /app * integration, any reachable URL) and #246 (release OCI smoke). */ import { Client } from "@modelcontextprotocol/sdk/client/index.js"; @@ -18,6 +18,18 @@ import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/ const CONNECT_TIMEOUT_MS = 120_000; const CALL_TIMEOUT_MS = 120_000; +/** Count result pages in a routeros_search response; metadata alone counts zero. */ +export function searchPageCount(responseText: string): number { + let parsed: unknown; + try { + parsed = JSON.parse(responseText); + } catch { + throw new Error("routeros_search returned non-JSON content"); + } + const pages = (parsed as { pages?: unknown }).pages; + return Array.isArray(pages) ? pages.length : 0; +} + function usage(): never { console.error("Usage: bun scripts/smoke-oci.ts "); console.error(" MCP endpoint, e.g. http://127.0.0.1:9803/mcp"); @@ -38,59 +50,66 @@ async function withTimeout(label: string, ms: number, fn: () => Promise): } } -const [urlArg, versionArg] = process.argv.slice(2); -if (!urlArg || !versionArg) usage(); +async function main(): Promise { + const [urlArg, versionArg] = process.argv.slice(2); + if (!urlArg || !versionArg) usage(); -let url: URL; -try { - url = new URL(urlArg); -} catch { - console.error(`Invalid URL: ${urlArg}`); - process.exit(2); - throw new Error("unreachable"); -} -const expectedTag = `v${versionArg.replace(/^v/, "")}`; -const client = new Client({ name: "rosetta-oci-smoke", version: "1" }); + let url: URL; + try { + url = new URL(urlArg); + } catch { + console.error(`Invalid URL: ${urlArg}`); + process.exit(2); + throw new Error("unreachable"); + } + const expectedTag = `v${versionArg.replace(/^v/, "")}`; + const client = new Client({ name: "rosetta-oci-smoke", version: "1" }); -try { - const started = Date.now(); - await withTimeout("MCP connect/initialize", CONNECT_TIMEOUT_MS, async () => { - const transport = new StreamableHTTPClientTransport(url); - await client.connect(transport); - }); - console.log(`initialize: ok (${Date.now() - started}ms)`); + try { + const started = Date.now(); + await withTimeout("MCP connect/initialize", CONNECT_TIMEOUT_MS, async () => { + const transport = new StreamableHTTPClientTransport(url); + await client.connect(transport); + }); + console.log(`initialize: ok (${Date.now() - started}ms)`); - const tools = await withTimeout("tools/list", CALL_TIMEOUT_MS, () => client.listTools()); - const names = (tools.tools ?? []).map((t) => t.name); - console.log(`tools/list: ${names.length} tools (${names.join(", ")})`); - for (const need of ["routeros_stats", "routeros_search"]) { - if (!names.includes(need)) throw new Error(`tools/list is missing required tool: ${need}`); - } + const tools = await withTimeout("tools/list", CALL_TIMEOUT_MS, () => client.listTools()); + const names = (tools.tools ?? []).map((t) => t.name); + console.log(`tools/list: ${names.length} tools (${names.join(", ")})`); + for (const need of ["routeros_stats", "routeros_search"]) { + if (!names.includes(need)) throw new Error(`tools/list is missing required tool: ${need}`); + } - const statsRes = await withTimeout("routeros_stats", CALL_TIMEOUT_MS, () => - client.callTool({ name: "routeros_stats", arguments: {} }), - ); - if (statsRes.isError) throw new Error(`routeros_stats returned an error: ${JSON.stringify(statsRes).slice(0, 500)}`); - const stats = JSON.parse((statsRes.content as { text: string }[])[0].text) as { - provenance?: { release_tag?: string }; - }; - console.log(`provenance.release_tag: ${stats.provenance?.release_tag} (expected ${expectedTag})`); - if (stats.provenance?.release_tag !== expectedTag) { - throw new Error(`Provenance mismatch: got ${stats.provenance?.release_tag}, expected ${expectedTag}`); - } + const statsRes = await withTimeout("routeros_stats", CALL_TIMEOUT_MS, () => + client.callTool({ name: "routeros_stats", arguments: {} }), + ); + if (statsRes.isError) throw new Error(`routeros_stats returned an error: ${JSON.stringify(statsRes).slice(0, 500)}`); + const stats = JSON.parse((statsRes.content as { text: string }[])[0].text) as { + provenance?: { release_tag?: string }; + }; + console.log(`provenance.release_tag: ${stats.provenance?.release_tag} (expected ${expectedTag})`); + if (stats.provenance?.release_tag !== expectedTag) { + throw new Error(`Provenance mismatch: got ${stats.provenance?.release_tag}, expected ${expectedTag}`); + } - const search = await withTimeout("routeros_search", CALL_TIMEOUT_MS, () => - client.callTool({ name: "routeros_search", arguments: { query: "firewall" } }), - ); - if (search.isError) throw new Error(`routeros_search returned an error: ${JSON.stringify(search).slice(0, 500)}`); - const text = (search.content as { text: string }[])[0].text; - console.log(`routeros_search: ${text.length} chars`); - if (text.length === 0) throw new Error("routeros_search returned empty content"); + const search = await withTimeout("routeros_search", CALL_TIMEOUT_MS, () => + client.callTool({ name: "routeros_search", arguments: { query: "firewall" } }), + ); + if (search.isError) throw new Error(`routeros_search returned an error: ${JSON.stringify(search).slice(0, 500)}`); + const text = (search.content as { text: string }[])[0].text; + const pageCount = searchPageCount(text); + console.log(`routeros_search: ${pageCount} pages (${text.length} chars)`); + if (pageCount === 0) throw new Error("routeros_search returned zero pages"); + + console.log(`SMOKE OK: ${urlArg} serves ${expectedTag} (${Date.now() - started}ms)`); + } catch (error) { + console.error(`SMOKE FAIL: ${error instanceof Error ? error.message : error}`); + process.exitCode = 1; + } finally { + await client.close().catch(() => {}); + } +} - console.log(`SMOKE OK: ${urlArg} serves ${expectedTag} (${Date.now() - started}ms)`); -} catch (error) { - console.error(`SMOKE FAIL: ${error instanceof Error ? error.message : error}`); - process.exitCode = 1; -} finally { - await client.close().catch(() => {}); +if (import.meta.main) { + await main(); } diff --git a/src/app-integration.test.ts b/src/app-integration.test.ts index 0e8e4b7..4db7dd9 100644 --- a/src/app-integration.test.ts +++ b/src/app-integration.test.ts @@ -14,6 +14,7 @@ import { applyAppAddSubstitutions, deriveVersionFromTag, extractAppAddBlock, + isTrustedChallengeRealm, logShowsContainerExit, parseImageRef, parseQemuAccel, @@ -21,8 +22,10 @@ import { ROS_VERSION_DEFAULT, redactCredentials, registryApiHost, + registryCredential, rewriteUiUrl, } from "../scripts/app-integration.ts"; +import { searchPageCount } from "../scripts/smoke-oci.ts"; const ROOT = path.resolve(import.meta.dirname, ".."); @@ -138,6 +141,13 @@ describe("parseImageRef", () => { expect(parsed.reference).toBe("sha256:9fbf37e0"); }); + test("strips a tag from repo:tag@digest", () => { + const parsed = parseImageRef("ghcr.io/tikoci/rosetta:v0.12.0@sha256:9fbf37e0"); + expect(parsed.repo).toBe("tikoci/rosetta"); + expect(parsed.reference).toBe("sha256:9fbf37e0"); + expect(parsed.isDigest).toBe(true); + }); + test("requires a tag or digest", () => { expect(() => parseImageRef("ghcr.io/tikoci/rosetta")).toThrow(/must include a tag or digest/); }); @@ -168,6 +178,39 @@ describe("registryApiHost", () => { }); }); +describe("registryCredential", () => { + test("GitHub tokens authenticate only to ghcr.io", () => { + expect(registryCredential("ghcr.io", "secret")).toBe("secret"); + expect(registryCredential("registry-1.docker.io", "secret")).toBe(""); + expect(registryCredential("example.com", "secret")).toBe(""); + expect(registryCredential("ghcr.io", "")).toBe(""); + }); +}); + +describe("isTrustedChallengeRealm", () => { + test("trusts a realm on the API host itself, nothing else", () => { + expect(isTrustedChallengeRealm("https://ghcr.io/token", "ghcr.io")).toBe(true); + expect(isTrustedChallengeRealm("https://evil.example/token", "ghcr.io")).toBe(false); + expect(isTrustedChallengeRealm("not a url", "ghcr.io")).toBe(false); + }); +}); + +describe("searchPageCount", () => { + test("counts pages in a search response", () => { + expect(searchPageCount(JSON.stringify({ pages: [{ id: 1 }, { id: 2 }] }))).toBe(2); + }); + + test("empty pages count zero (metadata alone is not a result)", () => { + expect( + searchPageCount(JSON.stringify({ query: "firewall", pages: [], total_pages: 0, related: {}, next_steps: [] })), + ).toBe(0); + }); + + test("non-JSON content throws", () => { + expect(() => searchPageCount("plain prose, no results")).toThrow(/non-JSON/); + }); +}); + describe("redactCredentials", () => { test("redacts credential-shaped keys at any depth, keeps the rest", () => { const input = { @@ -257,7 +300,14 @@ describe("app-integration.yml", () => { for (const input of ["image:", "ros_version:", "version:"]) { expect(yml).toContain(input); } - expect(yml).toContain("--image $" + "{{ inputs.image }}"); + // Inputs cross into the shell via env:, never by ${{ }} expansion in run:. + expect(yml).toContain("APP_IMAGE: $" + "{{ inputs.image }}"); + expect(yml).toContain('--image "$APP_IMAGE"'); + expect(yml).not.toContain("--image $" + "{{ inputs.image }}"); + }); + + test("image input has no floating default (defaults must not fail)", () => { + expect(yml).not.toContain('default: "ghcr.io/tikoci/rosetta:latest"'); }); test("diagnostics upload always runs", () => { From 39569bbf1c4d92f01e3b5372492b4c178b220cb4 Mon Sep 17 00:00:00 2001 From: SkyFi Geek <45924209+mobileskyfi@users.noreply.github.com> Date: Fri, 30 Oct 2026 18:00:19 -0700 Subject: [PATCH 6/7] Never let bundle-write failure skip VM cleanup (#248 review) writeDiagnosticsBundle returns false instead of throwing; both the main finally path and the signal path warn and continue to cleanup. --- scripts/app-integration.ts | 24 +++++++++++++++++++++--- src/app-integration.test.ts | 17 +++++++++++++++++ 2 files changed, 38 insertions(+), 3 deletions(-) diff --git a/scripts/app-integration.ts b/scripts/app-integration.ts index 8ab08b7..4b3bad9 100644 --- a/scripts/app-integration.ts +++ b/scripts/app-integration.ts @@ -169,6 +169,19 @@ export function isTrustedChallengeRealm(realm: string, apiHost: string): boolean const SECRET_KEY = /password|passwd|secret|token|authorization|auth|credential|header/i; +/** + * Write the diagnostics bundle, returning false instead of throwing: an + * evidence-write failure must never skip the VM cleanup that follows it. + */ +export async function writeDiagnosticsBundle(filePath: string, bundle: unknown): Promise { + try { + await Bun.write(filePath, `${JSON.stringify(bundle, null, 2)}\n`); + return true; + } catch { + return false; + } +} + /** Deep-clone with credential-shaped values replaced (diagnostics bundle). */ export function redactCredentials(value: T): T { if (Array.isArray(value)) return value.map(redactCredentials) as T; @@ -456,7 +469,9 @@ async function shutdownOnSignal(code: number): Promise { if (activeBundle && activeBundlePath) { activeBundle.outcome = "cancelled"; activeBundle.failure = `interrupted by ${code === 130 ? "SIGINT" : "SIGTERM"}`; - await Bun.write(activeBundlePath, `${JSON.stringify(activeBundle, null, 2)}\n`); + if (!(await writeDiagnosticsBundle(activeBundlePath, activeBundle))) { + console.log(`WARNING: could not write diagnostics bundle to ${activeBundlePath}`); + } } if (ownedMachineName && !keepMachineOnSignal) { console.log(`interrupted — cleaning up ${ownedMachineName}...`); @@ -663,8 +678,11 @@ async function main(): Promise { log(`APP-INTEGRATION FAIL: ${bundle.failure}`); } finally { bundle.config = redactCredentials(bundle.config); - await Bun.write(config.diagnosticsFile, `${JSON.stringify(bundle, null, 2)}\n`); - log(`diagnostics bundle: ${config.diagnosticsFile}`); + if (await writeDiagnosticsBundle(config.diagnosticsFile, bundle)) { + log(`diagnostics bundle: ${config.diagnosticsFile}`); + } else { + log(`WARNING: could not write diagnostics bundle to ${config.diagnosticsFile}`); + } appendStepSummary(config, bundle as { outcome: string; failure?: string; config?: Record; digestsBefore?: DigestRecord }); if (!config.keep) { if (ownedMachineName) { diff --git a/src/app-integration.test.ts b/src/app-integration.test.ts index 4db7dd9..cd399c9 100644 --- a/src/app-integration.test.ts +++ b/src/app-integration.test.ts @@ -24,6 +24,7 @@ import { registryApiHost, registryCredential, rewriteUiUrl, + writeDiagnosticsBundle, } from "../scripts/app-integration.ts"; import { searchPageCount } from "../scripts/smoke-oci.ts"; @@ -211,6 +212,22 @@ describe("searchPageCount", () => { }); }); +describe("writeDiagnosticsBundle", () => { + test("writes JSON on success, returns false instead of throwing on failure", async () => { + const { mkdtempSync, readFileSync, rmSync } = await import("node:fs"); + const { tmpdir } = await import("node:os"); + const dir = mkdtempSync(path.join(tmpdir(), "app-integration-")); + try { + const okPath = path.join(dir, "bundle.json"); + expect(await writeDiagnosticsBundle(okPath, { outcome: "pass" })).toBe(true); + expect(JSON.parse(readFileSync(okPath, "utf-8"))).toEqual({ outcome: "pass" }); + expect(await writeDiagnosticsBundle(dir, {})).toBe(false); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); +}); + describe("redactCredentials", () => { test("redacts credential-shaped keys at any depth, keeps the rest", () => { const input = { From 98d3a0058840242d0ba8819cf81c85116d6c61b3 Mon Sep 17 00:00:00 2001 From: SkyFi Geek <45924209+mobileskyfi@users.noreply.github.com> Date: Fri, 30 Oct 2026 19:09:50 -0700 Subject: [PATCH 7/7] Trust challenge realms only over HTTPS (#248 review) Co-Authored-By: Claude Opus 5.5 --- scripts/app-integration.ts | 5 +++-- src/app-integration.test.ts | 3 ++- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/scripts/app-integration.ts b/scripts/app-integration.ts index 4b3bad9..cd16d84 100644 --- a/scripts/app-integration.ts +++ b/scripts/app-integration.ts @@ -158,10 +158,11 @@ export function registryCredential(registry: string, envToken: string): string { return registry === "ghcr.io" ? envToken : ""; } -/** A Bearer challenge realm is trusted for credentials only on the API host itself. */ +/** A Bearer challenge realm is trusted for credentials only over HTTPS on the API host itself. */ export function isTrustedChallengeRealm(realm: string, apiHost: string): boolean { try { - return new URL(realm).host === apiHost; + const url = new URL(realm); + return url.protocol === "https:" && url.host === apiHost; } catch { return false; } diff --git a/src/app-integration.test.ts b/src/app-integration.test.ts index cd399c9..2e9fa9f 100644 --- a/src/app-integration.test.ts +++ b/src/app-integration.test.ts @@ -189,8 +189,9 @@ describe("registryCredential", () => { }); describe("isTrustedChallengeRealm", () => { - test("trusts a realm on the API host itself, nothing else", () => { + test("trusts an HTTPS realm on the API host itself, nothing else", () => { expect(isTrustedChallengeRealm("https://ghcr.io/token", "ghcr.io")).toBe(true); + expect(isTrustedChallengeRealm("http://ghcr.io/token", "ghcr.io")).toBe(false); expect(isTrustedChallengeRealm("https://evil.example/token", "ghcr.io")).toBe(false); expect(isTrustedChallengeRealm("not a url", "ghcr.io")).toBe(false); });