diff --git a/.github/contract-update-pr.md b/.github/contract-update-pr.md deleted file mode 100644 index 527f7ed..0000000 --- a/.github/contract-update-pr.md +++ /dev/null @@ -1,26 +0,0 @@ -## Summary - -Update the immutable bot contract pin and committed Kotlin client. Review `contract/assets/CHANGELOG.md`, the provenance, and generated changes together. - -## Why - -Keep Android operations and wire types aligned with the bot's latest published contract release. - -## Evidence - -Before reaching the PR step, this updater runs: - -- Checksums for every contract payload asset. -- Offline generator and updater tests. -- Byte-for-byte regeneration checks. -- `./gradlew test` and Android lint. - -The workflow uses only `GITHUB_TOKEN`. Follow-up PR workflows can require approval or remain suppressed; this updater does not rely on them. - -## Risk & Rollback - -**Reversibility:** Reversible by reverting the contract pin and generated output together. - -**Blast Radius:** Android HTTP requests, response decoding, and SSE payload decoding. - -Schema updates can expose API or app-adapter incompatibilities. Review the generated changes and test results before merging. diff --git a/.github/workflows/update-contract.yml b/.github/workflows/update-contract.yml deleted file mode 100644 index a165e6a..0000000 --- a/.github/workflows/update-contract.yml +++ /dev/null @@ -1,53 +0,0 @@ -name: Update bot contract - -on: - schedule: - - cron: '23 7 * * 1' - workflow_dispatch: - -permissions: - contents: read - -concurrency: - group: update-bot-contract - cancel-in-progress: false - -jobs: - update: - runs-on: ubuntu-latest - permissions: - contents: write - pull-requests: write - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - ref: main - - uses: actions/setup-java@b843ebf9b913146b38da2eaa7aeddf76074ae1ad # v6.1.0 - with: - distribution: temurin - java-version: '17' - - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 - with: - python-version: '3.13' - - uses: android-actions/setup-android@be39fa834029ff78f1a44aa3bb0819b8fc2bd8fd # v4.0.4 - with: - packages: 'platform-tools platforms;android-36 build-tools;36.0.0' - - run: python3 -m unittest discover -s scripts -p 'test_*.py' - - name: Download, verify, regenerate, and test - run: python3 scripts/contract.py update-latest - env: - GITHUB_TOKEN: ${{ github.token }} - - run: python3 scripts/contract.py check - - run: ./gradlew lintDebug - - uses: peter-evans/create-pull-request@5f6978faf089d4d20b00c7766989d076bb2fc7f1 # v8.1.1 - with: - token: ${{ github.token }} - branch: automation/shared-api-contract - base: main - add-paths: | - contract/assets/ - contract/pin.json - app/src/main/java/dev/crumble/android/generated/ - commit-message: 'chore(api): update the pinned bot contract' - title: 'chore(api): update the pinned bot contract' - body-path: .github/contract-update-pr.md diff --git a/CHANGELOG.md b/CHANGELOG.md index da77f2f..2d50476 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ ## Unreleased +- `scripts/contract.py update --from DIRECTORY` copies the contract files from a directory such as `bot/openapi/`, replacing `--local` and `--release`. `contract/` no longer carries `pin.json`, `SHA256SUMS`, `CHANGELOG.md`, or `source-commit.txt`; the `verify` and `update-latest` commands and the weekly contract update workflow are gone. - Publish signed release APKs: a `vX.Y.Z` tag builds one with FCM and attaches it to a GitHub release. Release builds are signed when `CRUMBLE_KEYSTORE_PATH` and `CRUMBLE_KEYSTORE_PASSWORD` are set, and take their version from `crumble.versionName` and `crumble.versionCode`. - The bot form shows the portrait with a pencil, and the avatar editor opens in a dialog instead of filling the form, as on the web. - Pin the bot's `6.0.0` contract as a local export and bump the generator to `1.1.0`, adding closed objects with declared properties, nullable named schemas and `allOf` parts, and `*/*` binary responses. diff --git a/README.md b/README.md index 3794ef2..ae40435 100644 --- a/README.md +++ b/README.md @@ -24,13 +24,12 @@ Open the navigation drawer › **Settings**, enter the server URL (`http://10.0. ## Shared API contract -`contract/pin.json` and `contract/assets/` pin a verified `bot` contract: a local export of a `bot` commit, or a release (`contract-vX.Y.Z`). `bot` no longer publishes contract releases, so current updates use `--local`. `scripts/generate-contract.py` generates Kotlin wire models and operations without external build-time dependencies. +`contract/assets/` holds a copy of the `bot` contract files from `bot/openapi/`. A running server also serves its document at `GET /openapi.json`. `scripts/generate-contract.py` generates Kotlin wire models and operations without external build-time dependencies. ```bash -python3 scripts/contract.py generate # Regenerate from current pin -python3 scripts/contract.py check # Verify checksums and byte-for-byte output -python3 scripts/contract.py update --release contract-vX.Y.Z # Update to a published release -python3 scripts/contract.py update --local EXPORT_DIR # Update from a local bot bundle +python3 scripts/contract.py generate # Regenerate from contract/assets/ +python3 scripts/contract.py check # Verify the generated output byte-for-byte +python3 scripts/contract.py update --from ../bot/openapi # Copy the contract files, regenerate, and run ./gradlew test ``` ## Release diff --git a/contract/assets/CHANGELOG.md b/contract/assets/CHANGELOG.md deleted file mode 100644 index 7c9c9f4..0000000 --- a/contract/assets/CHANGELOG.md +++ /dev/null @@ -1,3 +0,0 @@ -# Contract 6.0.0 - -- Local export from the bot checkout. The bot repository no longer publishes contract releases. diff --git a/contract/assets/SHA256SUMS b/contract/assets/SHA256SUMS deleted file mode 100644 index ac96184..0000000 --- a/contract/assets/SHA256SUMS +++ /dev/null @@ -1,6 +0,0 @@ -f1b51f5a2371989fb0a961e8d2097879a0fb90fc4d44a7554e32555ade38da32 CHANGELOG.md -4fa4a524cf635a837b53a322f2bdcbcccba75bc24b33260863ea8124f96ee21e activity-event.schema.json -eb4fc4fea61127a93e78b09eb7223a1ed730b49bc7a9a3dedfbf0fa70c3932c6 chat-snapshot.schema.json -e1fc21c5ca3e658bfbfbb5005a0d1dfec2be6e720b5a1ff86f699a13cc5db221 heartbeat.schema.json -3f389004678290cd63833233a48f17b321bb1157ae62956f72ae882b034a0c84 openapi.json -139de61622a3ef9a8c0112ca42971afcc5b5da9613f6604b2c64a37166a623e3 source-commit.txt diff --git a/contract/assets/source-commit.txt b/contract/assets/source-commit.txt deleted file mode 100644 index c4cbfbf..0000000 --- a/contract/assets/source-commit.txt +++ /dev/null @@ -1 +0,0 @@ -a3218780cf457d4377f195ef9e67d640c5158c24 diff --git a/contract/pin.json b/contract/pin.json deleted file mode 100644 index fde3392..0000000 --- a/contract/pin.json +++ /dev/null @@ -1,22 +0,0 @@ -{ - "checksums": { - "CHANGELOG.md": "f1b51f5a2371989fb0a961e8d2097879a0fb90fc4d44a7554e32555ade38da32", - "activity-event.schema.json": "4fa4a524cf635a837b53a322f2bdcbcccba75bc24b33260863ea8124f96ee21e", - "chat-snapshot.schema.json": "eb4fc4fea61127a93e78b09eb7223a1ed730b49bc7a9a3dedfbf0fa70c3932c6", - "heartbeat.schema.json": "e1fc21c5ca3e658bfbfbb5005a0d1dfec2be6e720b5a1ff86f699a13cc5db221", - "openapi.json": "3f389004678290cd63833233a48f17b321bb1157ae62956f72ae882b034a0c84", - "source-commit.txt": "139de61622a3ef9a8c0112ca42971afcc5b5da9613f6604b2c64a37166a623e3" - }, - "generator": { - "sha256": { - "scripts/generate-contract.py": "8563152a5691fcf7d4a59f16cb988cb6344217052780206e55a154046c7e5e74", - "scripts/templates/ContractBoundary.kt": "a901de2c9518930e80192d77aaa452047b10a0e2974eef424d22f7705fdbfeca" - }, - "version": "1.1.0" - }, - "release": null, - "repository": "crumble-project/bot", - "source": "local-export", - "sourceCommit": "a3218780cf457d4377f195ef9e67d640c5158c24", - "version": "6.0.0" -} diff --git a/scripts/contract.py b/scripts/contract.py index 29db173..f1ea6f1 100644 --- a/scripts/contract.py +++ b/scripts/contract.py @@ -1,78 +1,21 @@ #!/usr/bin/env python3 -"""Verify, regenerate, compare, or update the committed Crumble contract.""" +"""Regenerate, compare, or update the committed Crumble contract.""" import argparse -import hashlib -import json -import os import pathlib -import re import shutil import subprocess import tempfile -import urllib.request ROOT = pathlib.Path(__file__).resolve().parents[1] -ASSETS = ("openapi.json", "chat-snapshot.schema.json", "activity-event.schema.json", "heartbeat.schema.json", "CHANGELOG.md", "source-commit.txt") +ASSETS = ("openapi.json", "chat-snapshot.schema.json", "activity-event.schema.json", "heartbeat.schema.json") GENERATED = ROOT / "app/src/main/java/dev/crumble/android/generated" -GENERATOR = ("scripts/generate-contract.py", "scripts/templates/ContractBoundary.kt") -VERSION = "1.1.0" -def digest(path): - return hashlib.sha256(path.read_bytes()).hexdigest() - - -def verify_assets(directory): - entries = {} - for line in (directory / "SHA256SUMS").read_text().splitlines(): - match = re.fullmatch(r"([0-9a-f]{64}) ([a-zA-Z0-9.-]+)", line) - if not match or match[2] in entries: - raise ValueError("invalid or duplicate checksum entry: " + line) - entries[match[2]] = match[1] - if set(entries) != set(ASSETS): - raise ValueError("checksums must cover exactly the six payload assets") - if set(p.name for p in directory.iterdir()) != set(ASSETS) | {"SHA256SUMS"}: - raise ValueError("unexpected contract assets") - for name, expected in entries.items(): - if digest(directory / name) != expected: - raise ValueError("checksum mismatch: " + name) - source = (directory / "source-commit.txt").read_text().strip() - if not re.fullmatch(r"[0-9a-f]{40}", source): - raise ValueError("invalid source commit") - version = json.loads((directory / "openapi.json").read_text())["info"]["version"] - if not re.fullmatch(r"[0-9]+\.[0-9]+\.[0-9]+", version): - raise ValueError("invalid contract version") - for name in ASSETS: - if name.endswith(".json"): - json.loads((directory / name).read_text()) - return entries, source, version - - -def verify_pin(): - assets = ROOT / "contract/assets" - entries, source, version = verify_assets(assets) - manifest = json.loads((ROOT / "contract/pin.json").read_text()) - if (manifest["checksums"] != entries or manifest["sourceCommit"] != source or manifest["version"] != version): - raise ValueError("contract pin does not match verified assets") - if manifest["generator"] != {"version": VERSION, "sha256": {p: digest(ROOT / p) for p in GENERATOR}}: - raise ValueError("generator changed; regenerate and review the pin with the updater") - if manifest["repository"] != "crumble-project/bot": - raise ValueError("unexpected contract repository") - if manifest["source"] not in ("local-export", "github-release"): - raise ValueError("unknown pin source") - if manifest["source"] == "local-export" and manifest["release"] is not None: - raise ValueError("local export must not claim to be a published release") - if manifest["source"] == "github-release" and manifest["release"] != "contract-v" + version: - raise ValueError("release tag must match contract version") - return manifest - - -def generate(output=GENERATED): - subprocess.run(["python3", str(ROOT / "scripts/generate-contract.py"), "--output", str(output)], cwd=ROOT, check=True) +def generate(output=GENERATED, assets=ROOT / "contract/assets"): + subprocess.run(["python3", str(ROOT / "scripts/generate-contract.py"), "--assets", str(assets), "--output", str(output)], cwd=ROOT, check=True) def check(): - verify_pin() with tempfile.TemporaryDirectory(prefix="crumble-generated-") as temporary: output = pathlib.Path(temporary) generate(output) @@ -81,66 +24,21 @@ def check(): differences = sorted(str(p) for p in expected.keys() | actual.keys() if expected.get(p) != actual.get(p)) if differences: raise ValueError("stale or manually edited generated output: " + ", ".join(differences)) - print("Verified assets, generator pin, and byte-identical generated output") - - -def fetch_json(url): - headers = {"Accept": "application/vnd.github+json", "X-GitHub-Api-Version": "2022-11-28", "User-Agent": "crumble-android-contract"} - token = os.environ.get("GITHUB_TOKEN") - if token: - headers["Authorization"] = "Bearer " + token - with urllib.request.urlopen(urllib.request.Request(url, headers=headers), timeout=60) as response: - return json.load(response) - - -def latest(): - releases = [] - page = 1 - while True: - batch = fetch_json("https://api.github.com/repos/crumble-project/bot/releases?per_page=100&page=" + str(page)) - releases.extend(r for r in batch if not r["draft"] and not r["prerelease"] and re.fullmatch(r"contract-v[0-9]+\.[0-9]+\.[0-9]+", r["tag_name"])) - if len(batch) < 100: - break - page += 1 - if not releases: - print("No published contract releases; keeping the explicit local bootstrap pin") - return None - return max(releases, key=lambda r: r["published_at"])["tag_name"] + print("Verified byte-identical generated output") -def update(local=None, release=None): +def update(source): with tempfile.TemporaryDirectory(prefix="crumble-contract-") as temporary: directory = pathlib.Path(temporary) - if local: - verify_assets(local) - for name in (*ASSETS, "SHA256SUMS"): - shutil.copyfile(local / name, directory / name) - else: - if not re.fullmatch(r"contract-v[0-9]+\.[0-9]+\.[0-9]+", release): - raise ValueError("expected immutable contract-vX.Y.Z release tag") - metadata = fetch_json("https://api.github.com/repos/crumble-project/bot/releases/tags/" + release) - if metadata["draft"] or metadata["prerelease"] or metadata["tag_name"] != release: - raise ValueError("expected a published stable contract release") - urls = {asset["name"]: asset["browser_download_url"] for asset in metadata["assets"]} - for name in (*ASSETS, "SHA256SUMS"): - with urllib.request.urlopen(urls[name], timeout=60) as response: - (directory / name).write_bytes(response.read()) - entries, source, version = verify_assets(directory) - if release and release != "contract-v" + version: - raise ValueError("downloaded version does not match requested tag") - # Generate before changing the pin so unsupported schema updates leave it untouched. + for name in ASSETS: + shutil.copyfile(source / name, directory / name) + # Generate before replacing the assets so an unsupported schema leaves them untouched. candidate = directory / "generated" - subprocess.run(["python3", str(ROOT / "scripts/generate-contract.py"), "--assets", str(directory), "--output", str(candidate)], cwd=ROOT, check=True) + generate(candidate, directory) assets = ROOT / "contract/assets" assets.mkdir(parents=True, exist_ok=True) - for name in (*ASSETS, "SHA256SUMS"): + for name in ASSETS: shutil.copyfile(directory / name, assets / name) - manifest = { - "repository": "crumble-project/bot", "source": "local-export" if local else "github-release", - "release": release, "version": version, "sourceCommit": source, "checksums": entries, - "generator": {"version": VERSION, "sha256": {p: digest(ROOT / p) for p in GENERATOR}}, - } - (ROOT / "contract/pin.json").write_text(json.dumps(manifest, indent=2, sort_keys=True) + "\n") if GENERATED.exists(): shutil.rmtree(GENERATED) shutil.copytree(candidate, GENERATED) @@ -149,31 +47,18 @@ def update(local=None, release=None): def main(): - parser = argparse.ArgumentParser() - parser.add_argument("command", choices=["verify", "generate", "check", "update", "update-latest"]) - group = parser.add_mutually_exclusive_group() - group.add_argument("--local", type=pathlib.Path) - group.add_argument("--release") + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("command", choices=["generate", "check", "update"]) + parser.add_argument("--from", dest="source", type=pathlib.Path, help="Directory with the contract files, such as bot/openapi") args = parser.parse_args() - if args.command == "verify": - verify_pin() - elif args.command == "generate": - verify_pin() + if args.command == "generate": generate() elif args.command == "check": check() - elif args.command == "update-latest": - release = latest() - pin = json.loads((ROOT / "contract/pin.json").read_text()) - if release and pin["release"] != release: - update(release=release) - else: - check() - subprocess.run(["./gradlew", "test"], cwd=ROOT, check=True) else: - if not args.local and not args.release: - parser.error("update requires --local DIRECTORY or --release contract-vX.Y.Z") - update(args.local, args.release) + if not args.source: + parser.error("update requires --from DIRECTORY") + update(args.source) if __name__ == "__main__": diff --git a/scripts/test_contract.py b/scripts/test_contract.py index bd0160a..080fb96 100644 --- a/scripts/test_contract.py +++ b/scripts/test_contract.py @@ -1,11 +1,8 @@ import importlib.util -import io -import json import pathlib import shutil import tempfile import unittest -from unittest.mock import patch ROOT = pathlib.Path(__file__).resolve().parents[1] @@ -43,56 +40,6 @@ def test_rejects_manual_edits_and_unexpected_files(self): finally: contract.GENERATED = original - def test_every_payload_checksum_is_required_and_verified(self): - for filename in contract.ASSETS: - with self.subTest(asset=filename), tempfile.TemporaryDirectory() as temporary: - output = pathlib.Path(temporary) / "assets" - shutil.copytree(ROOT / "contract/assets", output) - path = output / filename - path.write_bytes(path.read_bytes() + b"corruption") - with self.assertRaisesRegex(ValueError, "checksum mismatch"): - contract.verify_assets(output) - - def test_corrupt_local_update_does_not_replace_the_pin(self): - pin = (ROOT / "contract/pin.json").read_bytes() - with tempfile.TemporaryDirectory() as temporary: - output = pathlib.Path(temporary) / "assets" - shutil.copytree(ROOT / "contract/assets", output) - (output / "CHANGELOG.md").write_text("corrupt") - with self.assertRaisesRegex(ValueError, "checksum mismatch"): - contract.update(local=output) - self.assertEqual(pin, (ROOT / "contract/pin.json").read_bytes()) - contract.check() - - def test_corrupt_release_download_does_not_replace_the_pin(self): - pin = (ROOT / "contract/pin.json").read_bytes() - assets = {name: (ROOT / "contract/assets" / name).read_bytes() for name in (*contract.ASSETS, "SHA256SUMS")} - assets["openapi.json"] += b" " - metadata = {"draft": False, "prerelease": False, "tag_name": "contract-v1.0.0", "assets": [{"name": name, "browser_download_url": "https://fixture.invalid/" + name} for name in assets]} - downloaded = [] - def download(request, timeout): - url = request.full_url if isinstance(request, contract.urllib.request.Request) else request - downloaded.append(url) - if url.startswith("https://api.github.com/"): - return io.BytesIO(json.dumps(metadata).encode()) - return io.BytesIO(assets[url.rsplit("/", 1)[1]]) - with patch.object(contract.urllib.request, "urlopen", side_effect=download): - with self.assertRaisesRegex(ValueError, "checksum mismatch"): - contract.update(release="contract-v1.0.0") - self.assertEqual(8, len(downloaded)) - self.assertEqual(pin, (ROOT / "contract/pin.json").read_bytes()) - contract.check() - - def test_missing_duplicate_and_traversal_checksums_fail(self): - for entry in ("", "../openapi.json", "openapi.json\n"): - with self.subTest(entry=entry), tempfile.TemporaryDirectory() as temporary: - output = pathlib.Path(temporary) / "assets" - shutil.copytree(ROOT / "contract/assets", output) - sums = output / "SHA256SUMS" - sums.write_text("0" * 64 + " " + entry + "\n") - with self.assertRaises(ValueError): - contract.verify_assets(output) - def test_unsupported_schema_fails_closed(self): instance = generator.Generator({"components": {"schemas": {}}, "paths": {}}) for schema in ({"type": "object", "patternProperties": {}}, {"type": "object", "additionalProperties": False}, {"type": ["string", "number"]}):