From 08b11ea7a24d7a23e2c0c236a6e84810a34df7e7 Mon Sep 17 00:00:00 2001 From: yeabow Date: Fri, 20 Nov 2026 14:13:46 +0800 Subject: [PATCH] feat: add scoped RAW artifact publisher action and workflow --- .github/workflows/raw_artifact_publish.yml | 64 +++++++ .github/workflows/raw_publish_test.yml | 35 ++++ .gitignore | 2 + README.md | 76 ++++++++ actions/publish-raw/action.yml | 67 +++++++ actions/publish-raw/publish.py | 213 +++++++++++++++++++++ tests/test_raw_publish.py | 157 +++++++++++++++ 7 files changed, 614 insertions(+) create mode 100644 .github/workflows/raw_artifact_publish.yml create mode 100644 .github/workflows/raw_publish_test.yml create mode 100644 .gitignore create mode 100644 actions/publish-raw/action.yml create mode 100644 actions/publish-raw/publish.py create mode 100644 tests/test_raw_publish.py diff --git a/.github/workflows/raw_artifact_publish.yml b/.github/workflows/raw_artifact_publish.yml new file mode 100644 index 0000000..cbc216c --- /dev/null +++ b/.github/workflows/raw_artifact_publish.yml @@ -0,0 +1,64 @@ +name: Publish RAW artifact to e2e +on: + workflow_call: + inputs: + platform-url: + type: string + default: '' + description: Platform URL; defaults to caller vars.E2E_PLATFORM_URL + package-url: + type: string + required: true + sha256: + type: string + required: true + source-commit: + type: string + required: true + description: Actual commit used to build this package + source-ref: + type: string + default: '' + filename: + type: string + default: '' + expected-version: + type: string + default: '' + runs-on: + type: string + default: '["ubuntu-latest"]' + description: JSON runner labels; caller provides network reachability + secrets: + E2E_RAW_PUBLISH_TOKEN: + required: true + outputs: + task-id: + value: ${{ jobs.publish.outputs.task-id }} + artifact-id: + value: ${{ jobs.publish.outputs.artifact-id }} + artifact-url: + value: ${{ jobs.publish.outputs.artifact-url }} +permissions: + contents: read +jobs: + publish: + runs-on: ${{ fromJSON(inputs.runs-on) }} + timeout-minutes: 35 + outputs: + task-id: ${{ steps.publish.outputs.task-id }} + artifact-id: ${{ steps.publish.outputs.artifact-id }} + artifact-url: ${{ steps.publish.outputs.artifact-url }} + steps: + - name: Import and verify RAW package + id: publish + uses: IceWhaleTech/github/actions/publish-raw@raw-publish-v1.0.0 + with: + platform-url: ${{ inputs.platform-url || vars.E2E_PLATFORM_URL }} + publish-token: ${{ secrets.E2E_RAW_PUBLISH_TOKEN }} + package-url: ${{ inputs.package-url }} + sha256: ${{ inputs.sha256 }} + source-commit: ${{ inputs.source-commit }} + source-ref: ${{ inputs.source-ref }} + filename: ${{ inputs.filename }} + expected-version: ${{ inputs.expected-version }} diff --git a/.github/workflows/raw_publish_test.yml b/.github/workflows/raw_publish_test.yml new file mode 100644 index 0000000..059fe60 --- /dev/null +++ b/.github/workflows/raw_publish_test.yml @@ -0,0 +1,35 @@ +name: RAW publisher checks +on: + pull_request: + paths: + - actions/publish-raw/** + - tests/test_raw_publish.py + - .github/workflows/raw_artifact_publish.yml + - .github/workflows/raw_publish_test.yml + push: + branches: [main] + paths: + - actions/publish-raw/** + - tests/test_raw_publish.py + - .github/workflows/raw_artifact_publish.yml + - .github/workflows/raw_publish_test.yml +permissions: + contents: read +jobs: + test: + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - uses: actions/checkout@v6 + with: + persist-credentials: false + - name: Test publisher without credentials or external services + run: python3 -m unittest discover -s tests -p 'test_raw_publish.py' -v + - uses: actions/setup-go@v6 + with: + go-version: '1.25' + cache: false + - name: Validate publisher workflows + run: | + go install github.com/rhysd/actionlint/cmd/actionlint@v1.7.12 + "$(go env GOPATH)/bin/actionlint" -shellcheck= -pyflakes= .github/workflows/raw_artifact_publish.yml .github/workflows/raw_publish_test.yml diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..7a60b85 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +__pycache__/ +*.pyc diff --git a/README.md b/README.md index 4f4ba27..db2a4b2 100644 --- a/README.md +++ b/README.md @@ -90,3 +90,79 @@ existing `API_TOKEN_GITHUB` secret: Callers should pin these workflows to a release tag such as `@openapi-sdk-v1.0.2` (or a full commit SHA), rather than `@main`. + +## Publish RAW application packages to e2e + +Use the immutable `raw-publish-v1.0.0` tag (or full commit SHA). The publisher +imports and verifies a package; device installation is a separate platform action. + +Create a repository-scoped credential in **Application artifacts → CI publishing**. +Set Actions Variable `E2E_PLATFORM_URL` and Secret `E2E_RAW_PUBLISH_TOKEN` in the +calling repository, or authorize it to use organization values. The caller owns +network reachability. The runner needs Python 3; local builds also use Git to +record the actual checkout commit. + +Add this step at the end of the job that builds the RAW file: + +```yaml +- name: Publish RAW to e2e + id: e2e + uses: IceWhaleTech/github/actions/publish-raw@raw-publish-v1.0.0 + with: + platform-url: ${{ vars.E2E_PLATFORM_URL }} + publish-token: ${{ secrets.E2E_RAW_PUBLISH_TOKEN }} + package-path: dist/folio.raw + # source-commit: actual 40-character build commit (defaults to checkout HEAD) + # source-ref: refs/tags/v1.2.3 (defaults to github.ref) + # expected-version: 1.2.3 (optional exact package version assertion) +``` + +No Actions artifact upload is needed. Alternatively, publish an existing HTTP(S) +download URL with the URL-only reusable workflow: + +```yaml +jobs: + publish-e2e: + needs: build + permissions: + contents: read + uses: IceWhaleTech/github/.github/workflows/raw_artifact_publish.yml@raw-publish-v1.0.0 + with: + package-url: ${{ needs.build.outputs.raw-url }} + sha256: ${{ needs.build.outputs.raw-sha256 }} + source-commit: ${{ needs.build.outputs.source-commit }} + source-ref: ${{ needs.build.outputs.source-ref }} + filename: folio.raw + # platform-url defaults to caller vars.E2E_PLATFORM_URL + # runs-on: '["self-hosted", "Linux", "X64", "my-network"]' + secrets: + E2E_RAW_PUBLISH_TOKEN: ${{ secrets.E2E_RAW_PUBLISH_TOKEN }} +``` + +`build` is caller-defined and must output the actual source commit/ref and package +checksum. The platform must be able to download the URL; private GitHub web URLs +are not direct download links. Signed URLs must last through ingestion. An import +source does not become a managed replica and is not deleted when the platform +artifact is deleted. + +The Action accepts exactly one of `package-path` / `package-url`. URL mode requires +`sha256`; local files are streamed and hashed automatically. `filename` preserves +the original download name. The package manifest is authoritative for its version; +git tags are recorded separately. The Action returns `task-id`, `sha256`, verified +`artifact-id` and `artifact-url`, and writes a step summary. The reusable workflow +returns task and artifact outputs. Import failures and timeouts fail the job; +timeouts leave the platform task running and preserve its ID. Default wait is +1800 seconds (`wait-timeout` input). + +Same repository/run/attempt/SHA/filename reuses the original task. Changed build +metadata under that identity is rejected. Distinct attempts retain provenance +while deduplicating bytes. Failed imports require a new GitHub run attempt, rather +than silently creating another task. Credentials cannot delete packages, access +settings, or deploy to devices. Rotate the Secret before revoking the old token. + +Use credentials only in trusted branches/tags or protected manual jobs. Do not +expose them to untrusted PRs/forks or execute their code using `pull_request_target`. +Local mock-HTTP tests run without credentials or external services. The package's +Action and reusable workflow share the same immutable `raw-publish-v*` release tag; +merge and pass checks before tagging, and never move existing tags. Real service +integration requires caller configuration after isolated acceptance. diff --git a/actions/publish-raw/action.yml b/actions/publish-raw/action.yml new file mode 100644 index 0000000..4275af6 --- /dev/null +++ b/actions/publish-raw/action.yml @@ -0,0 +1,67 @@ +name: Publish RAW to e2e +description: Import a verified RAW application package and preserve its GitHub build provenance +inputs: + platform-url: + description: e2e platform base URL; normally vars.E2E_PLATFORM_URL + required: true + publish-token: + description: Repository-scoped RAW publisher secret + required: true + package-path: + description: Local RAW path; mutually exclusive with package-url + default: '' + package-url: + description: Download URL; mutually exclusive with package-path + default: '' + sha256: + description: Required for URL publication; local files are hashed automatically + default: '' + filename: + description: Original RAW filename; defaults to path or URL basename + default: '' + expected-version: + description: Optional exact package version assertion; git refs are recorded separately + default: '' + source-commit: + description: Actual built commit; local file defaults to checked-out HEAD + default: '' + source-ref: + description: Full built ref; defaults to github.ref + default: '' + wait-timeout: + description: Seconds to wait for verified import + default: '1800' + poll-interval: + description: Seconds between task status requests + default: '5' +outputs: + task-id: + description: Platform import task ID + value: ${{ steps.publish.outputs.task-id }} + artifact-id: + description: Verified immutable artifact SHA-256 + value: ${{ steps.publish.outputs.artifact-id }} + artifact-url: + description: Platform artifact details URL + value: ${{ steps.publish.outputs.artifact-url }} + sha256: + description: Requested package SHA-256 + value: ${{ steps.publish.outputs.sha256 }} +runs: + using: composite + steps: + - id: publish + shell: bash + env: + INPUT_PLATFORM_URL: ${{ inputs.platform-url }} + INPUT_PUBLISH_TOKEN: ${{ inputs.publish-token }} + INPUT_PACKAGE_PATH: ${{ inputs.package-path }} + INPUT_PACKAGE_URL: ${{ inputs.package-url }} + INPUT_SHA256: ${{ inputs.sha256 }} + INPUT_FILENAME: ${{ inputs.filename }} + INPUT_EXPECTED_VERSION: ${{ inputs.expected-version }} + INPUT_SOURCE_COMMIT: ${{ inputs.source-commit }} + INPUT_SOURCE_REF: ${{ inputs.source-ref }} + INPUT_WAIT_TIMEOUT: ${{ inputs.wait-timeout }} + INPUT_POLL_INTERVAL: ${{ inputs.poll-interval }} + run: python3 "$GITHUB_ACTION_PATH/publish.py" diff --git a/actions/publish-raw/publish.py b/actions/publish-raw/publish.py new file mode 100644 index 0000000..0f9e490 --- /dev/null +++ b/actions/publish-raw/publish.py @@ -0,0 +1,213 @@ +#!/usr/bin/env python3 +"""Publish immutable RAW packages to e2e; no device deployment capability.""" +import base64 +import hashlib +import json +import os +from pathlib import Path +import re +import subprocess +import sys +import time +import urllib.error +import urllib.parse +import urllib.request + + +class PublishError(Exception): + pass + + +class NoRedirect(urllib.request.HTTPRedirectHandler): + def redirect_request(self, req, fp, code, msg, headers, newurl): + raise PublishError("Platform redirects are not allowed; configure the final E2E_PLATFORM_URL") + + +class Client: + def __init__(self, base, token): + parsed = urllib.parse.urlsplit(base) + if parsed.scheme not in ("http", "https") or not parsed.hostname or parsed.username or parsed.password or parsed.query or parsed.fragment: + raise PublishError("E2E_PLATFORM_URL must be an HTTP(S) base URL without credentials, query or fragment") + if not token or any(c in token for c in "\r\n"): + raise PublishError("E2E_RAW_PUBLISH_TOKEN is missing or invalid") + self.base, self.token = base.rstrip("/"), token + self.opener = urllib.request.build_opener(NoRedirect) + + def safe(self, message): + return str(message).replace(self.token, "[redacted]")[:1000] + + def request(self, method, path, body=None, headers=None, missing=False): + request = urllib.request.Request(self.base + path, data=body, method=method, + headers={"Authorization": "Bearer " + self.token, **(headers or {})}) + try: + with self.opener.open(request, timeout=60) as response: + return json.load(response) + except urllib.error.HTTPError as error: + if missing and error.code == 404: + error.close() + return None + try: + message = json.loads(error.read(1 << 20)).get("error", "Request rejected") + except (ValueError, AttributeError): + message = "Request rejected" + error.close() + raise PublishError(f"HTTP {error.code}: {self.safe(message)}") from None + except (urllib.error.URLError, TimeoutError, OSError) as error: + raise PublishError("Platform request failed: " + self.safe(error)) from None + except (ValueError, TypeError): + raise PublishError("Platform returned invalid JSON") from None + + +def value(name, default=""): + return os.environ.get("INPUT_" + name.upper().replace("-", "_"), default).strip() + + +def metadata(): + file_name, url = value("package-path"), value("package-url") + if bool(file_name) == bool(url): + raise PublishError("Provide exactly one of package-path or package-url") + file = Path(file_name) if file_name else None + expected = value("sha256").lower() + if file: + if not file.is_file(): + raise PublishError("package-path is not a regular file") + h = hashlib.sha256() + with file.open("rb") as stream: + for part in iter(lambda: stream.read(4 << 20), b""): + h.update(part) + actual = h.hexdigest() + if expected and actual != expected: + raise PublishError("Local package does not match sha256") + expected = actual + elif urllib.parse.urlsplit(url).scheme not in ("http", "https"): + raise PublishError("package-url must be an HTTP(S) RAW download URL") + filename = value("filename") or (file.name if file else Path(urllib.parse.unquote(urllib.parse.urlsplit(url).path)).name) + if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,127}\.raw", filename): + raise PublishError("Provide a valid .raw filename") + if not re.fullmatch(r"[0-9a-f]{64}", expected): + raise PublishError("URL publication requires the package sha256") + commit = value("source-commit") + if not commit and file: + try: + commit = subprocess.check_output(["git", "rev-parse", "HEAD"], text=True, stderr=subprocess.DEVNULL).strip() + except (OSError, subprocess.CalledProcessError): + pass + commit = (commit or os.environ.get("GITHUB_SHA", "")).lower() + repo = os.environ.get("GITHUB_REPOSITORY", "") + ref = value("source-ref") or os.environ.get("GITHUB_REF", "") + run = os.environ.get("GITHUB_RUN_ID", "") + attempt = os.environ.get("GITHUB_RUN_ATTEMPT", "1") + if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9-]{0,38}/[A-Za-z0-9_.-]{1,100}", repo) or repo.endswith(("/.", "/..")): + raise PublishError("GITHUB_REPOSITORY must identify the calling repository") + if not re.fullmatch(r"[0-9a-f]{40}", commit) or not re.fullmatch(r"[1-9][0-9]{0,19}", run) or not re.fullmatch(r"[1-9][0-9]{0,5}", attempt): + raise PublishError("Source commit and GitHub run identity are required") + if not ref.startswith(("refs/heads/", "refs/tags/")) or ref.endswith("/") or any(ord(c) < 32 for c in ref): + raise PublishError("source-ref must be a full branch or tag ref") + payload = dict(repository=repo, commit=commit, ref=ref, + workflow=os.environ.get("GITHUB_WORKFLOW", "GitHub Actions"), run_id=run, + run_attempt=int(attempt), filename=filename, sha256=expected) + if value("expected-version"): + payload["version"] = value("expected-version") + if url: + payload["url"] = url + key = hashlib.sha256("\n".join([repo.lower(), run, attempt, expected, filename]).encode()).hexdigest() + return payload, file, key + + +def publish(client, payload, file, key): + lookup = "/api/raw-artifacts/publish-requests/" + key + task = client.request("GET", lookup, missing=True) + if task is not None: + # POST validates that the same identity was not submitted with changed metadata. + if file: + encoded = base64.urlsafe_b64encode(json.dumps(payload).encode()).decode().rstrip("=") + return client.request("POST", "/api/raw-artifacts/publish-upload", b"", {"X-E2E-RAW-Metadata": encoded, "Content-Length": "0"}) + return client.request("POST", "/api/raw-artifacts/publish", json.dumps(payload).encode(), {"Content-Type": "application/json"}) + for attempt in range(3): + try: + if file: + encoded = base64.urlsafe_b64encode(json.dumps(payload).encode()).decode().rstrip("=") + with file.open("rb") as body: + return client.request("POST", "/api/raw-artifacts/publish-upload", body, + {"X-E2E-RAW-Metadata": encoded, "Content-Type": "application/octet-stream", "Content-Length": str(file.stat().st_size)}) + return client.request("POST", "/api/raw-artifacts/publish", json.dumps(payload).encode(), {"Content-Type": "application/json"}) + except PublishError as error: + text = str(error) + if text.startswith("HTTP 4") or attempt == 2: + raise + task = client.request("GET", lookup, missing=True) + if task is not None: + return task + time.sleep(attempt + 1) + raise PublishError("Unable to submit RAW publication") + + +def emit(outputs): + path = os.environ.get("GITHUB_OUTPUT") + if path: + with open(path, "a", encoding="utf-8") as stream: + for key, item in outputs.items(): + if "\n" in item or "\r" in item: + raise PublishError("Invalid output value") + stream.write(f"{key}={item}\n") + + +def main(): + client = Client(value("platform-url") or os.environ.get("E2E_PLATFORM_URL", ""), value("publish-token") or os.environ.get("E2E_RAW_PUBLISH_TOKEN", "")) + payload, file, key = metadata() + try: + timeout = int(value("wait-timeout", "1800")) + interval = int(value("poll-interval", "5")) + except ValueError: + raise PublishError("Timeout and polling interval must be integer seconds") from None + if not 1 <= timeout <= 10800 or not 1 <= interval <= 60: + raise PublishError("Invalid timeout or polling interval") + deadline = time.monotonic() + timeout + task = publish(client, payload, file, key) + source = task.get("source", {}) + fields = {"repo": payload["repository"], "commit": payload["commit"], "ref": payload["ref"], + "workflow": payload["workflow"], "run_id": payload["run_id"], "run_attempt": payload["run_attempt"], + "build_id": key, "declared_version": payload.get("version", "")} + if source.get("kind") != "github-actions" or any(source.get(name, "") != item for name, item in fields.items()) or task.get("expected_sha256") != payload["sha256"]: + raise PublishError("Platform task provenance does not match this GitHub build") + task_id = task.get("id", "") + if not re.fullmatch(r"raw-task-[A-Za-z0-9_-]+", task_id): + raise PublishError("Platform returned an invalid task ID") + emit({"task-id": task_id, "sha256": payload["sha256"]}) + last = None + while True: + state = task.get("state") + stage = task.get("stage", state) + if (state, stage) != last: + print(f"RAW import {task_id}: {state} / {stage}", flush=True) + last = state, stage + if state == "succeeded": + artifact = task.get("artifact_id", "") + if not re.fullmatch(r"[0-9a-f]{64}", artifact) or artifact != payload["sha256"]: + raise PublishError("Imported artifact does not match the requested SHA-256") + link = client.base + "/artifacts/?" + urllib.parse.urlencode({"view": "raw", "raw_artifact": artifact}) + emit({"artifact-id": artifact, "artifact-url": link}) + summary = os.environ.get("GITHUB_STEP_SUMMARY") + if summary: + with open(summary, "a", encoding="utf-8") as stream: + stream.write(f"RAW publication succeeded: [{payload['filename']}]({link})\n\nSHA-256: `{artifact}`\n\nTask: `{task_id}`\n") + print("RAW publication verified: " + link) + return + if state == "failed": + raise PublishError("RAW import failed: " + client.safe(task.get("error", "Unknown error")) + " (task " + task_id + ")") + if state not in ("queued", "running"): + raise PublishError("Unknown RAW import state") + if time.monotonic() >= deadline: + raise PublishError("Timed out waiting for RAW import; task " + task_id + " continues on the platform") + time.sleep(min(interval, max(0, deadline-time.monotonic()))) + task = client.request("GET", "/api/raw-artifacts/publish-tasks/" + task_id) + + +if __name__ == "__main__": + try: + main() + except PublishError as error: + secret = value("publish-token") or os.environ.get("E2E_RAW_PUBLISH_TOKEN", "") + message = str(error).replace(secret, "[redacted]") if secret else str(error) + print("RAW publication failed: " + message, file=sys.stderr) + sys.exit(1) diff --git a/tests/test_raw_publish.py b/tests/test_raw_publish.py new file mode 100644 index 0000000..bcb649a --- /dev/null +++ b/tests/test_raw_publish.py @@ -0,0 +1,157 @@ +import base64 +import hashlib +import importlib.util +import io +import json +import os +from pathlib import Path +import tempfile +import threading +import unittest +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from unittest.mock import patch + +SOURCE = Path(__file__).parents[1] / "actions/publish-raw/publish.py" +spec = importlib.util.spec_from_file_location("raw_publish", SOURCE) +module = importlib.util.module_from_spec(spec) +spec.loader.exec_module(module) + + +class Handler(BaseHTTPRequestHandler): + def log_message(self, *args): + pass + + def reply(self, value, code=200): + data = json.dumps(value).encode() + self.send_response(code) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(data))) + self.end_headers() + self.wfile.write(data) + + def do_GET(self): + fixture = self.server.fixture + fixture["requests"].append((self.command, self.path)) + if not self.headers.get("Authorization") == "Bearer rawpub_test-secret": + return self.reply({"error": "unauthorized"}, 401) + if "publish-requests" in self.path: + return self.reply(fixture["task"], 200) if fixture["task"] else self.reply({"error": "missing"}, 404) + fixture["polls"] += 1 + task = dict(fixture["task"]) + task.update(state=fixture["state"], artifact_id=fixture["sha"], error="package verification failed") + self.reply(task) + + def do_POST(self): + fixture = self.server.fixture + fixture["requests"].append((self.command, self.path)) + if fixture.get("redirect"): + self.send_response(307) + self.send_header("Location", fixture["redirect"]) + self.end_headers() + return + data = self.rfile.read(int(self.headers.get("Content-Length", "0"))) + if self.path.endswith("publish-upload"): + metadata = json.loads(base64.urlsafe_b64decode(self.headers["X-E2E-RAW-Metadata"] + "===")) + if data: + fixture["uploads"].append(data) + else: + metadata = json.loads(data) + fixture["metadata"] = metadata + fixture["sha"] = metadata["sha256"] + source = {"kind":"github-actions","repo":metadata["repository"],"commit":metadata["commit"],"ref":metadata["ref"],"workflow":metadata["workflow"],"run_id":metadata["run_id"],"run_attempt":metadata["run_attempt"],"declared_version":metadata.get("version","")} + source["build_id"]=hashlib.sha256("\n".join([metadata["repository"].lower(),metadata["run_id"],str(metadata["run_attempt"]),metadata["sha256"],metadata["filename"]]).encode()).hexdigest() + fixture["task"] = {"id": "raw-task-fixture", "state": "queued", "stage": "queued", "source":source,"expected_sha256":metadata["sha256"]} + if fixture.get("disconnect"): + fixture["disconnect"] = False + self.connection.close() + return + self.reply(fixture["task"], 202) + + +class RawPublishTests(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.root = Path(self.tmp.name) + self.file = self.root / "app.raw" + self.file.write_bytes(b"isolated raw fixture data") + self.fixture = dict(task=None, requests=[], uploads=[], polls=0, state="succeeded") + self.server = ThreadingHTTPServer(("127.0.0.1", 0), Handler) + self.server.fixture = self.fixture + self.thread = threading.Thread(target=self.server.serve_forever, daemon=True) + self.thread.start() + self.env = dict(INPUT_PLATFORM_URL=f"http://127.0.0.1:{self.server.server_port}", INPUT_PUBLISH_TOKEN="rawpub_test-secret", + INPUT_PACKAGE_PATH=str(self.file), INPUT_SOURCE_COMMIT="a" * 40, + GITHUB_REPOSITORY="Example/App", GITHUB_REF="refs/tags/v1.2.3", GITHUB_WORKFLOW="Build app", + GITHUB_SHA="b" * 40, GITHUB_RUN_ID="123", GITHUB_RUN_ATTEMPT="2", INPUT_POLL_INTERVAL="1", + GITHUB_OUTPUT=str(self.root / "outputs"), GITHUB_STEP_SUMMARY=str(self.root / "summary")) + + def tearDown(self): + self.server.shutdown() + self.server.server_close() + self.thread.join() + self.tmp.cleanup() + + def run_client(self): + with patch.dict(os.environ, self.env, clear=True), patch.object(module.time, "sleep", lambda _: None), patch("sys.stdout", new_callable=io.StringIO) as output: + module.main() + return output.getvalue() + + def test_file_upload_records_actual_commit_and_verified_outputs(self): + output = self.run_client() + self.assertEqual(self.fixture["uploads"], [self.file.read_bytes()]) + self.assertEqual(self.fixture["metadata"]["commit"], "a" * 40) + self.assertEqual(self.fixture["metadata"]["run_attempt"], 2) + self.assertEqual(self.fixture["metadata"]["ref"], "refs/tags/v1.2.3") + self.assertEqual(self.fixture["polls"], 1) + self.assertIn("artifact-id=" + hashlib.sha256(self.file.read_bytes()).hexdigest(), (self.root / "outputs").read_text()) + self.assertNotIn("rawpub_test-secret", output + (self.root / "summary").read_text()) + + def test_existing_request_does_not_upload_the_file_again(self): + self.run_client() + self.run_client() + self.assertEqual(len(self.fixture["uploads"]), 1) + + def test_network_disconnect_recovers_accepted_task_without_duplicate_upload(self): + self.fixture["disconnect"] = True + self.run_client() + self.assertEqual(len(self.fixture["uploads"]), 1) + self.assertGreaterEqual(sum("publish-requests" in path for _, path in self.fixture["requests"]), 2) + + def test_url_mode_submits_metadata_without_downloading_package(self): + self.env.update(INPUT_PACKAGE_PATH="", INPUT_PACKAGE_URL="https://packages.invalid/app.raw?signature=private", INPUT_SHA256="c" * 64) + self.run_client() + self.assertEqual(self.fixture["uploads"], []) + self.assertEqual(self.fixture["metadata"]["url"], self.env["INPUT_PACKAGE_URL"]) + self.assertNotIn("version", self.fixture["metadata"]) + + def test_failed_import_does_not_emit_success(self): + self.fixture["state"] = "failed" + with self.assertRaisesRegex(module.PublishError, "package verification failed"): + self.run_client() + self.assertNotIn("artifact-id", (self.root / "outputs").read_text()) + self.assertFalse((self.root / "summary").exists()) + + def test_redirect_is_rejected(self): + self.fixture["redirect"] = "https://other.invalid/collect" + with self.assertRaisesRegex(module.PublishError, "redirects are not allowed"): + self.run_client() + + def test_input_validation_happens_before_submission(self): + self.env.update(INPUT_SHA256="0" * 64) + with self.assertRaisesRegex(module.PublishError, "does not match"): + self.run_client() + self.assertEqual(self.fixture["requests"], []) + + def test_timeout_keeps_task_id_for_diagnosis(self): + self.fixture["state"] = "running" + self.env["INPUT_WAIT_TIMEOUT"] = "1" + clock = [0] + def advance(seconds): clock[0] += seconds + with patch.dict(os.environ, self.env, clear=True), patch.object(module.time, "monotonic", lambda: clock[0]), patch.object(module.time, "sleep", advance), patch("sys.stdout", new_callable=io.StringIO): + with self.assertRaisesRegex(module.PublishError, "task raw-task-fixture continues"): + module.main() + self.assertIn("task-id=raw-task-fixture", (self.root / "outputs").read_text()) + + +if __name__ == "__main__": + unittest.main()