From 937d84f5f12f5edcc3d521320a68aa7d9c6d431a Mon Sep 17 00:00:00 2001 From: Dominique Guinard Date: Wed, 11 Nov 2026 14:12:53 +0100 Subject: [PATCH 1/3] Allocate algorithm identifiers after maintainer review --- .github/scripts/allocate_identifiers.py | 215 +++++++++++++++ .github/scripts/registry.py | 126 +++++++++ .github/scripts/test_registry.py | 302 +++++++++++++++++++++ .github/workflows/allocate-identifiers.yml | 45 +++ .github/workflows/validate-json.yaml | 73 +++-- README.md | 116 +++++++- 6 files changed, 854 insertions(+), 23 deletions(-) create mode 100644 .github/scripts/allocate_identifiers.py create mode 100644 .github/scripts/registry.py create mode 100644 .github/scripts/test_registry.py create mode 100644 .github/workflows/allocate-identifiers.yml diff --git a/.github/scripts/allocate_identifiers.py b/.github/scripts/allocate_identifiers.py new file mode 100644 index 0000000..c9f652e --- /dev/null +++ b/.github/scripts/allocate_identifiers.py @@ -0,0 +1,215 @@ +"""Reserve identifiers and open a data-only integration PR using GitHub's API. + +This script must be run from the trusted default branch, never from a fork. +No proposed code, workflow, schema, or git hooks are executed. +""" + +import base64 +import json +import os +from urllib.error import HTTPError +from urllib.parse import quote, urlencode +from urllib.request import Request, urlopen + +from registry import LIST, SCHEMA, additions, reserve, validate + +STATE_BRANCH = "bot/identifier-allocations" +STATE_FILE = "identifier-allocations.json" +LABEL = "ready-to-register" + + +class GitHub: + def __init__(self): + self.repo = os.environ["GITHUB_REPOSITORY"] + self.root = os.environ.get("GITHUB_API_URL", "https://api.github.com") + self.token = os.environ["GH_TOKEN"] + + def call(self, method, path, data=None): + request = Request( + f"{self.root}/repos/{self.repo}/{path}", + data=json.dumps(data).encode() if data is not None else None, + method=method, + headers={"Authorization": f"Bearer {self.token}", + "Accept": "application/vnd.github+json", + "Content-Type": "application/json", + "X-GitHub-Api-Version": "2022-11-28"}, + ) + with urlopen(request, timeout=60) as response: + body = response.read() + return json.loads(body) if body else None + + def get(self, path): + return self.call("GET", path) + + def optional(self, path): + try: + return self.get(path) + except HTTPError as error: + if error.code == 404: + return None + raise + + def content(self, path, ref): + result = self.get(f"contents/{quote(path, safe='/')}?{urlencode({'ref': ref})}") + return json.loads(base64.b64decode(result["content"])) + + def commit_file(self, path, value, parent, message, base_tree=None): + blob = self.call("POST", "git/blobs", { + "content": json.dumps(value, indent=4, ensure_ascii=False) + "\n", "encoding": "utf-8"}) + tree = {"tree": [{"path": path, "mode": "100644", "type": "blob", "sha": blob["sha"]}]} + if base_tree: + tree["base_tree"] = base_tree + # Preserve executable mode of the existing list, if present. + current = self.get(f"git/trees/{base_tree}") + for item in current["tree"]: + if item["path"] == path: + tree["tree"][0]["mode"] = item["mode"] + tree = self.call("POST", "git/trees", tree) + return self.call("POST", "git/commits", { + "message": message, "tree": tree["sha"], "parents": [parent]})["sha"] + + +def allocation_request(api, event): + """Check both who requested allocation and the exact reviewed PR snapshot.""" + if os.environ["GITHUB_EVENT_NAME"] == "pull_request_target": + if event.get("action") != "labeled" or event["label"]["name"] != LABEL: + raise ValueError("Expected the ready-to-register label event") + number = event["pull_request"]["number"] + expected_head = event["pull_request"]["head"]["sha"] + else: + number = int(event["inputs"]["pr_number"]) + expected_head = None + if number < 1: + raise ValueError("Invalid PR number") + actor = os.environ["GITHUB_ACTOR"] + permission = api.get(f"collaborators/{quote(actor, safe='')}/permission")["permission"] + if permission not in ("admin", "maintain", "write"): + raise ValueError("Only maintainers with write permission can request allocation") + pr = api.get(f"pulls/{number}") + default = event["repository"]["default_branch"] + if pr["state"] != "open" or pr["base"]["ref"] != default: + raise ValueError("Source PR must be open and target the default branch") + if LABEL not in [label["name"] for label in pr["labels"]]: + raise ValueError("Source PR no longer has the ready-to-register label") + if expected_head and pr["head"]["sha"] != expected_head: + raise ValueError("Source changed after labeling; review it and reapply the label") + files = api.get(f"pulls/{number}/files?per_page=100") + if pr["changed_files"] != 1 or len(files) != 1 or files[0]["filename"] != LIST: + raise ValueError(f"Allocation PRs must change only {LIST}") + return pr + + +def persist_reservations(api, default, entries, source_pr): + """The non-force ref update is the lock: competing writers retry from state. + + A workflow concurrency group reduces collisions, but correctness does not + rely on GitHub scheduling or on an uninterrupted workflow run. + """ + for _ in range(8): + main_sha = api.get(f"git/ref/heads/{quote(default, safe='')}")["object"]["sha"] + published = api.content(LIST, main_sha) + schema = api.content(SCHEMA, main_sha) + state = api.optional(f"git/ref/heads/{STATE_BRANCH}") + state_sha = state["object"]["sha"] if state else None + ledger = api.content(STATE_FILE, state_sha) if state else {} + updated, allocated = reserve(ledger, published, entries, source_pr) + validate(published + allocated, schema, published) + if updated == ledger: + return main_sha, published, schema, allocated + sha = api.commit_file(STATE_FILE, updated, state_sha or main_sha, + f"Reserve identifiers for PR #{source_pr}") + try: + if state: + api.call("PATCH", f"git/refs/heads/{STATE_BRANCH}", {"sha": sha, "force": False}) + else: + api.call("POST", "git/refs", {"ref": f"refs/heads/{STATE_BRANCH}", "sha": sha}) + except HTTPError as error: + if error.code in (409, 422): + continue + raise + return main_sha, published, schema, allocated + raise ValueError("Concurrent allocation did not settle; rerun the workflow") + + +def prepare(api, event): + pr = allocation_request(api, event) + number, head = pr["number"], pr["head"]["sha"] + default = event["repository"]["default_branch"] + comparison = api.get(f"compare/{quote(default, safe='')}...{head}") + base_sha = comparison["merge_base_commit"]["sha"] + base = api.content(LIST, base_sha) + proposed = api.content(LIST, head) + # Validate with trusted schema, never one supplied by a contributor. + schema = api.content(SCHEMA, pr["base"]["sha"]) + validate(proposed, schema, base, submission=True) + new_entries = additions(base, proposed) + main_sha, published, schema, allocated = persist_reservations(api, default, new_entries, number) + final = published + allocated + validate(final, schema, published) + # Do not silently consume a different source revision during API requests. + current = api.get(f"pulls/{number}") + if current["head"]["sha"] != head or current["state"] != "open" or LABEL not in [x["name"] for x in current["labels"]]: + raise ValueError("Source PR changed or was withdrawn; reservations are retained; review and rerun") + branch = f"bot/register-pr-{number}-{head[:12]}" + existing = api.optional(f"git/ref/heads/{branch}") + if not existing: + tree = api.get(f"git/commits/{main_sha}")["tree"]["sha"] + sha = api.commit_file(LIST, final, main_sha, + f"Register algorithms from PR #{number}\n\nSource-PR: {pr['html_url']}\nSource-Commit: {head}", tree) + api.call("POST", "git/refs", {"ref": f"refs/heads/{branch}", "sha": sha}) + else: + # Never overwrite a maintainer's changes or rewrite a reviewed branch. + sha = existing["object"]["sha"] + actual = api.content(LIST, sha) + validate(actual, schema, published) + if actual != final: + raise ValueError("Prepared branch differs from the current list; rebase/review it manually") + rows = "\n".join(f"| `{e['alg']}` | {e['identifier']} |" for e in allocated) + body = (f"Registers the new algorithms submitted by @{pr['user']['login']} in #{number}, " + f"with automatically reserved identifiers.\n\nSource commit: `{head}`\n\n" + "| Algorithm | Identifier |\n| --- | --- |\n" + rows + + "\n\nOnly the algorithm list is copied onto the default branch. " + "Please complete normal technical review and merge this PR instead of the source PR. " + "After merging, close the source PR with a link to this registration. " + "This is a snapshot: later source changes need renewed review and allocation. " + "Reserved identifiers are never recycled.\n") + owner = api.repo.split('/')[0] + matches = api.get("pulls?" + urlencode({"state": "all", "head": f"{owner}:{branch}", "base": default})) + if matches: + integration = matches[0] + if integration["state"] != "open": + raise ValueError("The prepared PR is closed; reservations remain; reopen it for another attempt") + else: + integration = api.call("POST", "pulls", { + "title": f"Register algorithms from #{number} with assigned identifiers", + "body": body, "head": branch, "base": default}) + # GITHUB_TOKEN-generated events may need approval or not trigger CI. An + # explicit workflow_dispatch reliably starts the normal read-only checks. + api.call("POST", "actions/workflows/validate-json.yaml/dispatches", {"ref": branch}) + marker = "" + message = (f"{marker}\nPrepared registration: {integration['html_url']}\n\n" + f"Reviewed source: `{head}`\n\n| Algorithm | Identifier |\n| --- | --- |\n{rows}\n\n" + "Merge the prepared registration after review, then close this source PR. " + "Do not merge this submission with missing or provisional identifiers.") + # Idempotent notification, including pagination on long discussions. + page = 1 + while True: + comments = api.get(f"issues/{number}/comments?per_page=100&page={page}") + own = next((c for c in comments if c["body"].startswith(marker) + and c["user"]["login"] == "github-actions[bot]"), None) + if own: + api.call("PATCH", f"issues/comments/{own['id']}", {"body": message}) + break + if len(comments) < 100: + api.call("POST", f"issues/{number}/comments", {"body": message}) + break + page += 1 + print(integration["html_url"]) + if os.environ.get("GITHUB_STEP_SUMMARY"): + with open(os.environ["GITHUB_STEP_SUMMARY"], "a") as summary: + summary.write(message.replace(marker, "") + "\n") + + +if __name__ == "__main__": + with open(os.environ["GITHUB_EVENT_PATH"]) as source: + prepare(GitHub(), json.load(source)) diff --git a/.github/scripts/registry.py b/.github/scripts/registry.py new file mode 100644 index 0000000..c24a8b4 --- /dev/null +++ b/.github/scripts/registry.py @@ -0,0 +1,126 @@ +"""Validation shared by submission checks and the trusted identifier allocator.""" + +import copy +import json +import argparse +from pathlib import Path + +from jsonschema import Draft202012Validator, FormatChecker + +LIST = "softbinding-algorithm-list.json" +SCHEMA = "softbinding-algorithm-list.schema.json" + + +def validate(entries, schema, published=(), submission=False): + schema = copy.deepcopy(schema) + if submission: + schema["items"]["required"].remove("identifier") + Draft202012Validator.check_schema(schema) + Draft202012Validator(schema, format_checker=FormatChecker()).validate(entries) + by_alg = {} + by_id = {} + for entry in entries: + alg = entry["alg"] + if alg in by_alg: + raise ValueError(f"Duplicate alg: {alg}") + by_alg[alg] = entry + if "identifier" in entry: + identifier = entry["identifier"] + if identifier in by_id: + raise ValueError(f"Duplicate identifier: {identifier}") + by_id[identifier] = entry + for old in published: + new = by_alg.get(old["alg"]) + if new is None: + if old["identifier"] in by_id: + raise ValueError(f"Cannot rename published algorithm: {old['alg']}") + # The TWG may remove malicious/non-conformant entries. Their IDs + # remain reserved in the durable ledger and must not be reused. + continue + for field in ("identifier", "alg", "type"): + if new.get(field) != old[field]: + raise ValueError(f"Cannot change published {field} for {old['alg']}") + + +def additions(base, proposed): + """Only additions are copied into a privileged, bot-owned integration branch.""" + before = {entry["alg"]: entry for entry in base} + after = {entry["alg"]: entry for entry in proposed} + for alg, entry in before.items(): + if after.get(alg) != entry: + raise ValueError(f"Allocation PRs must only add entries; existing entry changed: {alg}") + result = [copy.deepcopy(e) for e in proposed if e["alg"] not in before] + if not result: + raise ValueError("No new algorithms to register") + return result + + +def reserve(ledger, published, entries, source_pr): + """Pure allocation: durable reservations survive closed PRs and repeated runs.""" + ledger = copy.deepcopy(ledger) + reservations = ledger.setdefault("algorithms", {}) + used = set() + for alg, record in reservations.items(): + identifier = record["identifier"] + if type(identifier) is not int or not 0 <= identifier <= 65535 or identifier in used: + raise ValueError(f"Invalid allocation ledger at {alg}") + used.add(identifier) + for entry in published: + alg, identifier = entry["alg"], entry["identifier"] + if alg in reservations: + if reservations[alg]["identifier"] != identifier: + raise ValueError(f"Published identifier disagrees with reservation for {alg}") + else: + if identifier in used: + raise ValueError(f"Published identifier collides with a reservation: {identifier}") + reservations[alg] = {"identifier": identifier, "source_pr": None} + used.add(identifier) + next_id = max(ledger.get("next_identifier", 0), max(used, default=-1) + 1) + published_algs = {entry["alg"] for entry in published} + result = copy.deepcopy(entries) + for entry in result: + alg = entry["alg"] + if alg in published_algs: + raise ValueError(f"Algorithm already published: {alg}") + if alg not in reservations: + if next_id > 65535: + raise ValueError("Identifier space exhausted (maximum 65535)") + reservations[alg] = {"identifier": next_id, "source_pr": source_pr} + next_id += 1 + record = reservations[alg] + if record["source_pr"] != source_pr: + raise ValueError(f"Algorithm is reserved by another PR: {alg}") + # Legacy submitter-selected numbers are deliberately replaced. + entry["identifier"] = record["identifier"] + ledger["next_identifier"] = next_id + return ledger, result + + +def validate_reservations(entries, published, ledger): + published_algs = {entry["alg"] for entry in published} + reservations = ledger.get("algorithms", {}) + for entry in entries: + record = reservations.get(entry["alg"]) + if record is not None and record["identifier"] != entry["identifier"]: + raise ValueError(f"Identifier disagrees with allocation for {entry['alg']}") + if entry["alg"] not in published_algs and record is None: + raise ValueError(f"No reserved identifier for {entry['alg']}; use ready-to-register") + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--submission", action="store_true") + parser.add_argument("--published", type=Path) + parser.add_argument("--ledger", type=Path) + args = parser.parse_args() + published = json.loads(args.published.read_text()) if args.published else [] + validate(json.loads(Path(LIST).read_text()), json.loads(Path(SCHEMA).read_text()), + published, args.submission) + if args.ledger: + validate_reservations(json.loads(Path(LIST).read_text()), published, + json.loads(args.ledger.read_text())) + print("Submission is valid" if args.submission else "Published list is valid") + + +if __name__ == "__main__": + main() diff --git a/.github/scripts/test_registry.py b/.github/scripts/test_registry.py new file mode 100644 index 0000000..e3253b2 --- /dev/null +++ b/.github/scripts/test_registry.py @@ -0,0 +1,302 @@ +import copy +import io +import json +import os +from pathlib import Path +import unittest +from unittest.mock import patch +from urllib.error import HTTPError + +from jsonschema import ValidationError + +from allocate_identifiers import LABEL, STATE_BRANCH, STATE_FILE, allocation_request, prepare +from registry import LIST, SCHEMA, additions, reserve, validate, validate_reservations + +ROOT = Path(__file__).resolve().parents[2] +SCHEMA_VALUE = json.loads((ROOT / SCHEMA).read_text()) + + +def entry(alg="com.example.first", identifier=1): + result = copy.deepcopy(SCHEMA_VALUE["examples"][0][0]) + result["alg"] = alg + if identifier is None: + result.pop("identifier") + else: + result["identifier"] = identifier + return result + + +class RegistryTests(unittest.TestCase): + def test_missing_id_only_allowed_for_new_submission(self): + old = entry() + proposed = [old, entry("com.example.new", None)] + validate(proposed, SCHEMA_VALUE, [old], submission=True) + with self.assertRaises(ValidationError): + validate(proposed, SCHEMA_VALUE, [old]) + proposed[0].pop("identifier") + with self.assertRaises(ValueError): + validate(proposed, SCHEMA_VALUE, [entry()], submission=True) + + def test_published_identity_cannot_change(self): + old = entry() + for field, value in [("identifier", 4), ("alg", "com.example.renamed"), ("type", "fingerprint")]: + changed = dict(old, **{field: value}) + with self.subTest(field=field), self.assertRaises(ValueError): + validate([changed], SCHEMA_VALUE, [old], submission=True) + # TWG removals remain possible; reserve() keeps the retired ID forever. + validate([], SCHEMA_VALUE, [old]) + + def test_duplicate_algs_and_ids_rejected(self): + for proposed in [[entry(), entry()], [entry(), entry("com.example.other")]]: + with self.assertRaises(ValueError): + validate(proposed, SCHEMA_VALUE, submission=True) + + def test_submission_still_checks_fields_and_formats(self): + for field, value in [("type", "unknown"), ("identifier", -1)]: + with self.assertRaises(ValidationError): + validate([dict(entry(), **{field: value})], SCHEMA_VALUE, submission=True) + bad = entry(identifier=None) + bad["entryMetadata"]["contact"] = "invalid" + with self.assertRaises(ValidationError): + validate([bad], SCHEMA_VALUE, submission=True) + + def test_allocation_is_idempotent_and_replaces_legacy_ids(self): + original = [entry("com.example.second", 1), entry("com.example.third", None)] + ledger, allocated = reserve({}, [entry()], original, 10) + self.assertEqual([e["identifier"] for e in allocated], [2, 3]) + self.assertEqual(reserve(ledger, [entry()], original, 10), (ledger, allocated)) + self.assertEqual(original[0]["identifier"], 1) + self.assertNotIn("identifier", original[1]) + + def test_reservations_survive_abandoned_prs_and_removed_entries(self): + ledger, _ = reserve({}, [entry()], [entry("com.example.second", None)], 10) + ledger, allocated = reserve(ledger, [], [entry("com.example.third", None)], 11) + self.assertEqual(allocated[0]["identifier"], 3) + self.assertEqual(ledger["algorithms"]["com.example.first"]["identifier"], 1) + with self.assertRaises(ValueError): + reserve(ledger, [], [entry("com.example.second", None)], 12) + + def test_manual_publication_cannot_take_a_reserved_id(self): + ledger, _ = reserve({}, [entry()], [entry("com.example.second", None)], 10) + with self.assertRaises(ValueError): + reserve(ledger, [entry(), entry("com.example.interloper", 2)], [], 11) + + def test_space_exhaustion_and_corrupt_ledger_fail_closed(self): + with self.assertRaises(ValueError): + reserve({}, [entry(identifier=65535)], [entry("com.example.new", None)], 10) + with self.assertRaises(ValueError): + reserve({"algorithms": {"a": {"identifier": 1}, "b": {"identifier": 1}}}, [], [], 10) + + def test_only_new_entries_are_copied(self): + old, new = entry(), entry("com.example.new", None) + self.assertEqual(additions([old], [old, new]), [new]) + with self.assertRaises(ValueError): + additions([old], [dict(old, type="fingerprint"), new]) + with self.assertRaises(ValueError): + additions([old], [old]) + + def test_new_published_entries_require_matching_reservations(self): + old, new = entry(), entry("com.example.new", 2) + with self.assertRaisesRegex(ValueError, "No reserved"): + validate_reservations([old, new], [old], {}) + ledger, allocated = reserve({}, [old], [new], 10) + validate_reservations([old] + allocated, [old], ledger) + with self.assertRaisesRegex(ValueError, "disagrees"): + validate_reservations([old, dict(new, identifier=3)], [old], ledger) + + +class FakeGitHub: + """In-memory API: exercises orchestration without any live mutations.""" + repo = "owner/registry" + + def __init__(self): + self.published = [entry()] + self.proposed = self.published + [entry("com.example.new", None)] + self.pr = {"number": 10, "state": "open", "base": {"ref": "main", "sha": "main1"}, + "head": {"sha": "a" * 40}, "labels": [{"name": LABEL}], "changed_files": 1, + "html_url": "https://github.com/owner/registry/pull/10", "user": {"login": "contributor"}} + self.refs = {"main": "main1"} + self.contents = {"main1": {LIST: self.published, SCHEMA: SCHEMA_VALUE}} + self.integrations = [] + self.comments = [] + self.dispatches = [] + self.permission = "write" + self.conflict_once = False + self.commit_count = 0 + self.withdraw_after_reserving = False + + def get(self, path): + result = self.optional(path) + if result is None: + raise AssertionError(f"Unexpected GET {path}") + return copy.deepcopy(result) + + def optional(self, path): + if path.startswith("collaborators/"): + return {"permission": self.permission} + if path == "pulls/10": + if self.withdraw_after_reserving and STATE_BRANCH in self.refs: + self.pr["labels"] = [] + return copy.deepcopy(self.pr) + if path.startswith("pulls/10/files"): + return [{"filename": LIST}] + if path.startswith("compare/"): + return {"merge_base_commit": {"sha": "base"}} + if path.startswith("git/ref/heads/"): + name = path.removeprefix("git/ref/heads/") + return {"object": {"sha": self.refs[name]}} if name in self.refs else None + if path.startswith("git/commits/"): + return {"tree": {"sha": "main-tree"}} + if path.startswith("pulls?"): + return self.integrations + if path.startswith("issues/10/comments?"): + return self.comments + raise AssertionError(f"Unexpected GET {path}") + + def content(self, path, ref): + if ref == "base": + return copy.deepcopy(self.published) + if ref == "a" * 40: + return copy.deepcopy(self.proposed) + return copy.deepcopy(self.contents[ref][path]) + + def commit_file(self, path, value, parent, message, base_tree=None): + self.commit_count += 1 + sha = f"commit{self.commit_count}" + self.contents[sha] = {path: copy.deepcopy(value)} + return sha + + def call(self, method, path, data): + if path == "git/refs": + name = data["ref"].removeprefix("refs/heads/") + if self.conflict_once and name == STATE_BRANCH: + self.conflict_once = False + ledger, _ = reserve({}, self.published, [entry("com.example.other", None)], 99) + self.contents["concurrent"] = {STATE_FILE: ledger} + self.refs[STATE_BRANCH] = "concurrent" + raise HTTPError("test", 422, "Reference already exists", {}, io.BytesIO()) + if name in self.refs: + raise AssertionError("Duplicate branch") + self.refs[name] = data["sha"] + elif path.startswith("git/refs/heads/"): + assert data["force"] is False + self.refs[path.removeprefix("git/refs/heads/")] = data["sha"] + elif path == "pulls": + pr = dict(data, number=11, state="open", html_url="https://github.com/owner/registry/pull/11") + self.integrations.append(pr) + return pr + elif path.endswith("/dispatches"): + self.dispatches.append(data) + elif path == "issues/10/comments": + self.comments.append(dict(data, id=20, user={"login": "github-actions[bot]"})) + elif path == "issues/comments/20": + self.comments[0].update(data) + else: + raise AssertionError(f"Unexpected {method} {path}") + + +class WorkflowTests(unittest.TestCase): + def setUp(self): + self.env = patch.dict(os.environ, {"GITHUB_EVENT_NAME": "pull_request_target", "GITHUB_ACTOR": "maintainer"}) + self.env.start() + self.addCleanup(self.env.stop) + self.api = FakeGitHub() + self.event = {"action": "labeled", "label": {"name": LABEL}, + "pull_request": copy.deepcopy(self.api.pr), "repository": {"default_branch": "main"}} + + def test_end_to_end_and_retry_do_not_duplicate_pr_or_comment(self): + prepare(self.api, self.event) + prepare(self.api, self.event) + self.assertEqual(len(self.api.integrations), 1) + self.assertEqual(len(self.api.comments), 1) + prepared = self.api.content(LIST, self.api.refs["bot/register-pr-10-aaaaaaaaaaaa"]) + self.assertEqual(prepared[-1]["identifier"], 2) + self.assertEqual(prepared[0], self.api.published[0]) + self.assertEqual(self.api.refs["main"], "main1") + self.assertEqual(len(self.api.dispatches), 2) + + def test_concurrent_allocator_retries_without_duplicate_id(self): + self.api.conflict_once = True + prepare(self.api, self.event) + prepared = self.api.content(LIST, self.api.refs["bot/register-pr-10-aaaaaaaaaaaa"]) + self.assertEqual(prepared[-1]["identifier"], 3) + + def test_nonmaintainer_cannot_trigger_allocation(self): + self.api.permission = "read" + with self.assertRaisesRegex(ValueError, "Only maintainers"): + prepare(self.api, self.event) + self.assertEqual(self.api.refs, {"main": "main1"}) + + def test_source_changed_after_labeling_is_rejected(self): + self.api.pr["head"]["sha"] = "b" * 40 + with self.assertRaisesRegex(ValueError, "Source changed"): + prepare(self.api, self.event) + + def test_code_changes_are_not_copied(self): + self.api.pr["changed_files"] = 2 + with self.assertRaisesRegex(ValueError, "must change only"): + prepare(self.api, self.event) + + def test_wrong_base_or_withdrawn_request_is_rejected(self): + for change in [lambda: self.api.pr.update(labels=[]), + lambda: self.api.pr["base"].update(ref="develop"), + lambda: self.api.pr.update(state="closed")]: + self.api = FakeGitHub() + change() + with self.assertRaises(ValueError): + allocation_request(self.api, self.event) + + def test_manual_retry_requires_current_label_and_maintainer(self): + with patch.dict(os.environ, {"GITHUB_EVENT_NAME": "workflow_dispatch"}): + event = dict(self.event, inputs={"pr_number": "10"}) + prepare(self.api, event) + self.api.pr["labels"] = [] + with self.assertRaises(ValueError): + prepare(self.api, event) + + def test_modified_prepared_branch_is_never_overwritten(self): + prepare(self.api, self.event) + sha = self.api.refs["bot/register-pr-10-aaaaaaaaaaaa"] + self.api.contents[sha][LIST][-1]["entryMetadata"]["description"] = "Maintainer edit" + with self.assertRaisesRegex(ValueError, "differs"): + prepare(self.api, self.event) + + def test_withdrawal_after_reservation_keeps_id_without_opening_pr(self): + self.api.withdraw_after_reserving = True + with self.assertRaisesRegex(ValueError, "withdrawn"): + prepare(self.api, self.event) + self.assertIn(STATE_BRANCH, self.api.refs) + self.assertFalse(self.api.integrations) + + def test_non_fast_forward_conflict_retries_from_winning_ledger(self): + from allocate_identifiers import persist_reservations + prepare(self.api, self.event) + original_call = self.api.call + conflict = True + + def competing_update(method, path, data): + nonlocal conflict + if method == "PATCH" and path == f"git/refs/heads/{STATE_BRANCH}" and conflict: + conflict = False + ref = self.api.refs[STATE_BRANCH] + ledger = self.api.contents[ref][STATE_FILE] + ledger, _ = reserve(ledger, self.api.published, [entry("com.example.competing", None)], 99) + self.api.contents["winner"] = {STATE_FILE: ledger} + self.api.refs[STATE_BRANCH] = "winner" + raise HTTPError("test", 422, "Not a fast forward", {}, io.BytesIO()) + return original_call(method, path, data) + + self.api.call = competing_update + _, _, _, allocated = persist_reservations(self.api, "main", [entry("com.example.next", None)], 12) + self.assertEqual(allocated[0]["identifier"], 4) + + def test_closed_prepared_pr_is_not_duplicated(self): + prepare(self.api, self.event) + self.api.integrations[0]["state"] = "closed" + with self.assertRaisesRegex(ValueError, "prepared PR is closed"): + prepare(self.api, self.event) + self.assertEqual(len(self.api.integrations), 1) + + +if __name__ == "__main__": + unittest.main() diff --git a/.github/workflows/allocate-identifiers.yml b/.github/workflows/allocate-identifiers.yml new file mode 100644 index 0000000..792bbc3 --- /dev/null +++ b/.github/workflows/allocate-identifiers.yml @@ -0,0 +1,45 @@ +name: Allocate algorithm identifiers + +on: + pull_request_target: + types: [labeled] + workflow_dispatch: + inputs: + pr_number: + description: 'Reviewed source PR with the ready-to-register label' + required: true + type: string + +permissions: + contents: write + pull-requests: write + issues: write + actions: write + +# Ref updates also handle simultaneous requests safely. GitHub may replace an +# older pending run in this group; reapply the label or dispatch it to retry. +concurrency: + group: sbr-identifier-allocator + cancel-in-progress: false + +jobs: + allocate: + if: >- + github.event_name == 'workflow_dispatch' || + github.event.label.name == 'ready-to-register' + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + # Never check out or execute code from the source PR. + - uses: actions/checkout@v4 + with: + ref: ${{ github.event.repository.default_branch }} + persist-credentials: false + - uses: actions/setup-python@v5 + with: + python-version: '3.12' + - run: python -m pip install jsonschema==4.26.0 + - name: Reserve IDs and prepare registration PR + env: + GH_TOKEN: ${{ github.token }} + run: python .github/scripts/allocate_identifiers.py diff --git a/.github/workflows/validate-json.yaml b/.github/workflows/validate-json.yaml index b53a482..afd422c 100644 --- a/.github/workflows/validate-json.yaml +++ b/.github/workflows/validate-json.yaml @@ -5,28 +5,61 @@ on: branches: [ main, develop ] pull_request: branches: [ main, develop ] + workflow_dispatch: + +permissions: + contents: read jobs: validate-json: runs-on: ubuntu-latest - steps: - - name: Checkout repository - uses: actions/checkout@v4 - - - name: Install sourcemeta json schema cli - uses: sourcemeta/jsonschema@main - - - name: Lint JSON files - run: | - echo "Linting softbinding-algorithm-list.schema.json..." - set -e # Exit on any error - jsonschema lint softbinding-algorithm-list.schema.json - echo "✓ softbinding-algorithm-list.schema.json passed linting" - - - name: Validate against schema - run: | - echo "Validating softbinding-algorithm-list.json against schema..." - set -e # Exit on any error - jsonschema validate softbinding-algorithm-list.schema.json softbinding-algorithm-list.json - echo "✓ softbinding-algorithm-list.json is valid against the schema" + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + persist-credentials: false + - uses: actions/setup-python@v5 + with: + python-version: '3.12' + - name: Install validator + run: python -m pip install jsonschema==4.26.0 + - name: Test allocation and validation + run: python -m unittest discover -s .github/scripts -p 'test_*.py' -v + - name: Validate submission and published identifiers + env: + EVENT: ${{ github.event_name }} + BASE_REF: ${{ github.base_ref || github.event.repository.default_branch }} + run: | + set -euo pipefail + git show "origin/$BASE_REF:softbinding-algorithm-list.json" > "$RUNNER_TEMP/published.json" + if [ "$EVENT" = pull_request ]; then + python .github/scripts/registry.py --submission --published "$RUNNER_TEMP/published.json" + else + python .github/scripts/registry.py --published "$RUNNER_TEMP/published.json" + fi + + # Make this required in branch protection. ID-less submissions pass + # validate-json but cannot merge; prepared registrations pass both checks. + publish-ready: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + persist-credentials: false + - uses: actions/setup-python@v5 + with: + python-version: '3.12' + - run: python -m pip install jsonschema==4.26.0 + - name: Require assigned IDs and preserve published entries + env: + BASE_REF: ${{ github.base_ref || github.event.repository.default_branch }} + run: | + set -euo pipefail + git show "origin/$BASE_REF:softbinding-algorithm-list.json" > "$RUNNER_TEMP/published.json" + if git show-ref --verify --quiet refs/remotes/origin/bot/identifier-allocations; then + git show origin/bot/identifier-allocations:identifier-allocations.json > "$RUNNER_TEMP/allocations.json" + else + echo '{}' > "$RUNNER_TEMP/allocations.json" + fi + python .github/scripts/registry.py --published "$RUNNER_TEMP/published.json" --ledger "$RUNNER_TEMP/allocations.json" diff --git a/README.md b/README.md index f47ff52..3abdf0b 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,7 @@ The soft binding assertion contains a field `alg` which uniquely identifies the ## Guidelines for submitting a new entry ### Pull request -Developers of soft binding algorithms may request these be added as new entries in the soft binding algorithm list. Developers may also request amendments to their entries. These requests are made by submitting a Pull Request (PR) that adds to, or edits, the [softbinding-algorithm-list JSON array](softbinding-algorithm-list.json) in this repository and following the [schema](softbinding-algorithm-list-schema.json). +Developers of soft binding algorithms may request these be added as new entries in the soft binding algorithm list. Developers may also request amendments to their entries. These requests are made by submitting a Pull Request (PR) that adds to, or edits, the [softbinding-algorithm-list JSON array](softbinding-algorithm-list.json) in this repository and following the [schema](softbinding-algorithm-list.schema.json). For new entries, omit `identifier`: the registration bot assigns it after maintainer review. All other required fields still apply. Keep existing identifiers when amending an entry. ### Selection rules @@ -16,14 +16,124 @@ The C2PA Technical Working Group will approve and merge PRs in accordance with i C2PA's Technical Working Group may also decide to remove malicious or non-conformant entries from the list of approved soft binding algorithms. For a PR (new entry or update) to be approved the following criteria are important: -- The entry shall conform with the [schema](softbinding-algorithm-list-schema.json) and shall include all the mandatory fields. +- The published entry shall conform with the [schema](softbinding-algorithm-list.schema.json) and shall include all mandatory fields. New-entry submissions may omit `identifier` until the registration bot assigns it. - The entry shall not appear to be malicious (e.g., spam) or harmful. - The PR shall be submitted by an individual affiliated with the company owning the submitted proprietary algorithm or a maintainer of the submitted open source algorithm or its fork. - The provided URLs shall successfully resolve (e.g., `softBindingResolutionApis`, `informationalUrl`). - `informationalUrl` shall reference documentation specific to the algorithm described by the entry. The referenced documentation shall provide a general description of the algorithm and its operation. - The algorithm covered by the entry shall support embedding, extracting, or both, of a soft binding identifier for the purpose of manifest recovery. -- When updating an entry, the fields: `identifier`, `alg` and `type` shall not be changed. +- When updating an entry, the fields: `identifier`, `alg` and `type` shall not be changed. +## Automatic identifier allocation +### Contributors +Add your new entries to `softbinding-algorithm-list.json`, leaving out +`identifier`. For example: +```json +{ + "alg": "com.example.watermark.1", + "type": "watermark", + "decodedMediaTypes": ["image"], + "entryMetadata": { + "description": "An image watermark carrying an identifier for manifest recovery", + "dateEntered": "2026-11-11T00:00:00Z", + "contact": "developer@example.com", + "informationalUrl": "https://example.com/watermark" + } +} +``` + +Use the actual date and algorithm details. One PR may add multiple entries. +Registration PRs must only change the algorithm list and must not modify existing +entries. Submit amendments to existing entries separately, preserving their +`identifier`, `alg`, and `type`. + +The `validate-json` check accepts new entries without identifiers. The separate +`publish-ready` check intentionally fails until identifiers have been reserved. +Do not merge an unallocated submission. Previously submitted provisional IDs +are accepted when valid and unique within the submission, but the bot replaces +them with its own reservations; contributors must not rely on those numbers. + +### Maintainers + +1. Complete the normal submission review, including affiliation, documentation, + URL resolution and support for manifest recovery. +2. Add the **`ready-to-register`** label. Only a label applied by someone with + repository write permission (or higher) authorizes allocation. +3. The bot permanently reserves one ID per new `alg` and opens a separate + registration PR from a repository-owned branch. It links that PR from the + source submission, lists the allocations and records the reviewed source SHA. +4. Review and merge the prepared registration PR after its checks pass. It + contains only the new entries, added to the current published list. Then + close the original submission with a link to the merged registration PR. + +The bot never merges a PR or changes a contributor's fork. The public schema +continues to require integer IDs in the range 0–65535. Published identifiers, +algorithm names and types cannot change. Entries can be marked +`"deprecated": true`; the TWG may also remove malicious or non-conformant +entries under the selection rules. Removed entries' IDs remain reserved. + +A prepared registration is a snapshot, not a live mirror of the source PR. +After source changes, review the new revision and remove/reapply the label. +Close any superseded registration PRs; the changed source receives a new +registration branch and the same reservations for unchanged algorithm names. +If other registrations merge first, update/rebase the prepared PR and rerun its +checks; the allocator never force-pushes or overwrites a prepared branch. + +For a failed or canceled run, use **Actions → Allocate algorithm identifiers → +Run workflow**, enter the source PR number and use the default branch. The label +must still be present. Reapplying the label also retries. Repeated runs reuse +reservations and the prepared PR. If the prepared PR was closed without merging, +reopen it before retrying. The workflow log explains rejected submissions. + +### Repository setup + +After merging the automation: + +- Create the `ready-to-register` label. +- Under **Settings → Actions → General → Workflow permissions**, enable + **Allow GitHub Actions to create and approve pull requests**. The bot creates + PRs but does not approve them. Organization policy must permit this setting. + No personal access token or additional secret is required. +- Require both `validate-json` and **`publish-ready`** in the default branch's + protection rule or ruleset, and require branches to be up to date before + merging. This prevents a submission with missing, conflicting or unreserved + IDs from being merged. Keep normal human review requirements. +- Protect the exact branch **`bot/identifier-allocations`** against deletion and + force-pushes, while allowing the Actions bot to create it and make normal + fast-forward updates. It is created on the first allocation. Exclude this + state branch from automatic branch cleanup and keep it in repository backups. + +`bot/identifier-allocations` contains `identifier-allocations.json`, the durable +allocation ledger. It is deliberately separate from the published list: closed, +failed and withdrawn registrations keep their reservations. Do not delete or +rewrite this ledger; restore it from backup if it is lost before running the +allocator again. Initial allocation imports the existing published IDs, then +assigns monotonically increasing IDs above the largest imported/reserved value. +Multiple-entry reservations are committed together. Concurrent writers use +non-force Git ref updates with retries, so they cannot reserve the same number. +A different PR cannot take another PR's reserved algorithm name. + +The allocator executes only code from the trusted default branch, treats the +source PR as JSON data, rejects changes to other files, and checks the source +SHA again before preparing the registration. Its workflow has narrowly scoped +write permissions. Validation workflows have read-only permissions. The bot +explicitly dispatches validation on the prepared branch, so checks also run when +bot-created PR events do not start workflows automatically. This uses +[GitHub's documented workflow-dispatch exception](https://docs.github.com/en/actions/how-tos/write-workflows/choose-when-workflows-run/trigger-a-workflow#triggering-a-workflow-from-a-workflow). + +### Local checks + +Use Python 3.12 or later: + +```sh +python -m pip install jsonschema==4.26.0 +python -m unittest discover -s .github/scripts -p 'test_*.py' -v +python .github/scripts/registry.py +``` + +For a new-entry submission, pass `--submission`. CI additionally compares the +submission with the target branch to protect published identity fields; the +strict `publish-ready` check verifies new IDs against the allocation ledger. From c984c894eea27610101e1c831b6e021aa35f4c9c Mon Sep 17 00:00:00 2001 From: Dominique Guinard Date: Mon, 16 Nov 2026 12:25:18 +0100 Subject: [PATCH 2/3] Replace registration bot with local maintainer ID assignment --- .github/scripts/allocate_identifiers.py | 215 ------------- .github/scripts/registry.py | 108 +++---- .github/scripts/test_registry.py | 336 ++++++--------------- .github/workflows/allocate-identifiers.yml | 45 --- .github/workflows/validate-json.yaml | 26 +- README.md | 156 +++------- 6 files changed, 187 insertions(+), 699 deletions(-) delete mode 100644 .github/scripts/allocate_identifiers.py delete mode 100644 .github/workflows/allocate-identifiers.yml diff --git a/.github/scripts/allocate_identifiers.py b/.github/scripts/allocate_identifiers.py deleted file mode 100644 index c9f652e..0000000 --- a/.github/scripts/allocate_identifiers.py +++ /dev/null @@ -1,215 +0,0 @@ -"""Reserve identifiers and open a data-only integration PR using GitHub's API. - -This script must be run from the trusted default branch, never from a fork. -No proposed code, workflow, schema, or git hooks are executed. -""" - -import base64 -import json -import os -from urllib.error import HTTPError -from urllib.parse import quote, urlencode -from urllib.request import Request, urlopen - -from registry import LIST, SCHEMA, additions, reserve, validate - -STATE_BRANCH = "bot/identifier-allocations" -STATE_FILE = "identifier-allocations.json" -LABEL = "ready-to-register" - - -class GitHub: - def __init__(self): - self.repo = os.environ["GITHUB_REPOSITORY"] - self.root = os.environ.get("GITHUB_API_URL", "https://api.github.com") - self.token = os.environ["GH_TOKEN"] - - def call(self, method, path, data=None): - request = Request( - f"{self.root}/repos/{self.repo}/{path}", - data=json.dumps(data).encode() if data is not None else None, - method=method, - headers={"Authorization": f"Bearer {self.token}", - "Accept": "application/vnd.github+json", - "Content-Type": "application/json", - "X-GitHub-Api-Version": "2022-11-28"}, - ) - with urlopen(request, timeout=60) as response: - body = response.read() - return json.loads(body) if body else None - - def get(self, path): - return self.call("GET", path) - - def optional(self, path): - try: - return self.get(path) - except HTTPError as error: - if error.code == 404: - return None - raise - - def content(self, path, ref): - result = self.get(f"contents/{quote(path, safe='/')}?{urlencode({'ref': ref})}") - return json.loads(base64.b64decode(result["content"])) - - def commit_file(self, path, value, parent, message, base_tree=None): - blob = self.call("POST", "git/blobs", { - "content": json.dumps(value, indent=4, ensure_ascii=False) + "\n", "encoding": "utf-8"}) - tree = {"tree": [{"path": path, "mode": "100644", "type": "blob", "sha": blob["sha"]}]} - if base_tree: - tree["base_tree"] = base_tree - # Preserve executable mode of the existing list, if present. - current = self.get(f"git/trees/{base_tree}") - for item in current["tree"]: - if item["path"] == path: - tree["tree"][0]["mode"] = item["mode"] - tree = self.call("POST", "git/trees", tree) - return self.call("POST", "git/commits", { - "message": message, "tree": tree["sha"], "parents": [parent]})["sha"] - - -def allocation_request(api, event): - """Check both who requested allocation and the exact reviewed PR snapshot.""" - if os.environ["GITHUB_EVENT_NAME"] == "pull_request_target": - if event.get("action") != "labeled" or event["label"]["name"] != LABEL: - raise ValueError("Expected the ready-to-register label event") - number = event["pull_request"]["number"] - expected_head = event["pull_request"]["head"]["sha"] - else: - number = int(event["inputs"]["pr_number"]) - expected_head = None - if number < 1: - raise ValueError("Invalid PR number") - actor = os.environ["GITHUB_ACTOR"] - permission = api.get(f"collaborators/{quote(actor, safe='')}/permission")["permission"] - if permission not in ("admin", "maintain", "write"): - raise ValueError("Only maintainers with write permission can request allocation") - pr = api.get(f"pulls/{number}") - default = event["repository"]["default_branch"] - if pr["state"] != "open" or pr["base"]["ref"] != default: - raise ValueError("Source PR must be open and target the default branch") - if LABEL not in [label["name"] for label in pr["labels"]]: - raise ValueError("Source PR no longer has the ready-to-register label") - if expected_head and pr["head"]["sha"] != expected_head: - raise ValueError("Source changed after labeling; review it and reapply the label") - files = api.get(f"pulls/{number}/files?per_page=100") - if pr["changed_files"] != 1 or len(files) != 1 or files[0]["filename"] != LIST: - raise ValueError(f"Allocation PRs must change only {LIST}") - return pr - - -def persist_reservations(api, default, entries, source_pr): - """The non-force ref update is the lock: competing writers retry from state. - - A workflow concurrency group reduces collisions, but correctness does not - rely on GitHub scheduling or on an uninterrupted workflow run. - """ - for _ in range(8): - main_sha = api.get(f"git/ref/heads/{quote(default, safe='')}")["object"]["sha"] - published = api.content(LIST, main_sha) - schema = api.content(SCHEMA, main_sha) - state = api.optional(f"git/ref/heads/{STATE_BRANCH}") - state_sha = state["object"]["sha"] if state else None - ledger = api.content(STATE_FILE, state_sha) if state else {} - updated, allocated = reserve(ledger, published, entries, source_pr) - validate(published + allocated, schema, published) - if updated == ledger: - return main_sha, published, schema, allocated - sha = api.commit_file(STATE_FILE, updated, state_sha or main_sha, - f"Reserve identifiers for PR #{source_pr}") - try: - if state: - api.call("PATCH", f"git/refs/heads/{STATE_BRANCH}", {"sha": sha, "force": False}) - else: - api.call("POST", "git/refs", {"ref": f"refs/heads/{STATE_BRANCH}", "sha": sha}) - except HTTPError as error: - if error.code in (409, 422): - continue - raise - return main_sha, published, schema, allocated - raise ValueError("Concurrent allocation did not settle; rerun the workflow") - - -def prepare(api, event): - pr = allocation_request(api, event) - number, head = pr["number"], pr["head"]["sha"] - default = event["repository"]["default_branch"] - comparison = api.get(f"compare/{quote(default, safe='')}...{head}") - base_sha = comparison["merge_base_commit"]["sha"] - base = api.content(LIST, base_sha) - proposed = api.content(LIST, head) - # Validate with trusted schema, never one supplied by a contributor. - schema = api.content(SCHEMA, pr["base"]["sha"]) - validate(proposed, schema, base, submission=True) - new_entries = additions(base, proposed) - main_sha, published, schema, allocated = persist_reservations(api, default, new_entries, number) - final = published + allocated - validate(final, schema, published) - # Do not silently consume a different source revision during API requests. - current = api.get(f"pulls/{number}") - if current["head"]["sha"] != head or current["state"] != "open" or LABEL not in [x["name"] for x in current["labels"]]: - raise ValueError("Source PR changed or was withdrawn; reservations are retained; review and rerun") - branch = f"bot/register-pr-{number}-{head[:12]}" - existing = api.optional(f"git/ref/heads/{branch}") - if not existing: - tree = api.get(f"git/commits/{main_sha}")["tree"]["sha"] - sha = api.commit_file(LIST, final, main_sha, - f"Register algorithms from PR #{number}\n\nSource-PR: {pr['html_url']}\nSource-Commit: {head}", tree) - api.call("POST", "git/refs", {"ref": f"refs/heads/{branch}", "sha": sha}) - else: - # Never overwrite a maintainer's changes or rewrite a reviewed branch. - sha = existing["object"]["sha"] - actual = api.content(LIST, sha) - validate(actual, schema, published) - if actual != final: - raise ValueError("Prepared branch differs from the current list; rebase/review it manually") - rows = "\n".join(f"| `{e['alg']}` | {e['identifier']} |" for e in allocated) - body = (f"Registers the new algorithms submitted by @{pr['user']['login']} in #{number}, " - f"with automatically reserved identifiers.\n\nSource commit: `{head}`\n\n" - "| Algorithm | Identifier |\n| --- | --- |\n" + rows + - "\n\nOnly the algorithm list is copied onto the default branch. " - "Please complete normal technical review and merge this PR instead of the source PR. " - "After merging, close the source PR with a link to this registration. " - "This is a snapshot: later source changes need renewed review and allocation. " - "Reserved identifiers are never recycled.\n") - owner = api.repo.split('/')[0] - matches = api.get("pulls?" + urlencode({"state": "all", "head": f"{owner}:{branch}", "base": default})) - if matches: - integration = matches[0] - if integration["state"] != "open": - raise ValueError("The prepared PR is closed; reservations remain; reopen it for another attempt") - else: - integration = api.call("POST", "pulls", { - "title": f"Register algorithms from #{number} with assigned identifiers", - "body": body, "head": branch, "base": default}) - # GITHUB_TOKEN-generated events may need approval or not trigger CI. An - # explicit workflow_dispatch reliably starts the normal read-only checks. - api.call("POST", "actions/workflows/validate-json.yaml/dispatches", {"ref": branch}) - marker = "" - message = (f"{marker}\nPrepared registration: {integration['html_url']}\n\n" - f"Reviewed source: `{head}`\n\n| Algorithm | Identifier |\n| --- | --- |\n{rows}\n\n" - "Merge the prepared registration after review, then close this source PR. " - "Do not merge this submission with missing or provisional identifiers.") - # Idempotent notification, including pagination on long discussions. - page = 1 - while True: - comments = api.get(f"issues/{number}/comments?per_page=100&page={page}") - own = next((c for c in comments if c["body"].startswith(marker) - and c["user"]["login"] == "github-actions[bot]"), None) - if own: - api.call("PATCH", f"issues/comments/{own['id']}", {"body": message}) - break - if len(comments) < 100: - api.call("POST", f"issues/{number}/comments", {"body": message}) - break - page += 1 - print(integration["html_url"]) - if os.environ.get("GITHUB_STEP_SUMMARY"): - with open(os.environ["GITHUB_STEP_SUMMARY"], "a") as summary: - summary.write(message.replace(marker, "") + "\n") - - -if __name__ == "__main__": - with open(os.environ["GITHUB_EVENT_PATH"]) as source: - prepare(GitHub(), json.load(source)) diff --git a/.github/scripts/registry.py b/.github/scripts/registry.py index c24a8b4..ce80a8b 100644 --- a/.github/scripts/registry.py +++ b/.github/scripts/registry.py @@ -1,8 +1,9 @@ -"""Validation shared by submission checks and the trusted identifier allocator.""" +"""Validate registry changes and assign new identifiers locally before merging.""" +import argparse import copy import json -import argparse +import subprocess from pathlib import Path from jsonschema import Draft202012Validator, FormatChecker @@ -34,91 +35,54 @@ def validate(entries, schema, published=(), submission=False): if new is None: if old["identifier"] in by_id: raise ValueError(f"Cannot rename published algorithm: {old['alg']}") - # The TWG may remove malicious/non-conformant entries. Their IDs - # remain reserved in the durable ledger and must not be reused. + # The TWG may remove malicious/non-conformant entries. continue for field in ("identifier", "alg", "type"): if new.get(field) != old[field]: raise ValueError(f"Cannot change published {field} for {old['alg']}") -def additions(base, proposed): - """Only additions are copied into a privileged, bot-owned integration branch.""" - before = {entry["alg"]: entry for entry in base} - after = {entry["alg"]: entry for entry in proposed} - for alg, entry in before.items(): - if after.get(alg) != entry: - raise ValueError(f"Allocation PRs must only add entries; existing entry changed: {alg}") - result = [copy.deepcopy(e) for e in proposed if e["alg"] not in before] - if not result: - raise ValueError("No new algorithms to register") - return result - - -def reserve(ledger, published, entries, source_pr): - """Pure allocation: durable reservations survive closed PRs and repeated runs.""" - ledger = copy.deepcopy(ledger) - reservations = ledger.setdefault("algorithms", {}) - used = set() - for alg, record in reservations.items(): - identifier = record["identifier"] - if type(identifier) is not int or not 0 <= identifier <= 65535 or identifier in used: - raise ValueError(f"Invalid allocation ledger at {alg}") - used.add(identifier) - for entry in published: - alg, identifier = entry["alg"], entry["identifier"] - if alg in reservations: - if reservations[alg]["identifier"] != identifier: - raise ValueError(f"Published identifier disagrees with reservation for {alg}") - else: - if identifier in used: - raise ValueError(f"Published identifier collides with a reservation: {identifier}") - reservations[alg] = {"identifier": identifier, "source_pr": None} - used.add(identifier) - next_id = max(ledger.get("next_identifier", 0), max(used, default=-1) + 1) - published_algs = {entry["alg"] for entry in published} +def assign_identifiers(entries, published): + """Replace new entries' provisional IDs with consecutive IDs above the base.""" result = copy.deepcopy(entries) + published_algs = {entry["alg"] for entry in published} + next_id = max((entry["identifier"] for entry in published), default=-1) + 1 for entry in result: - alg = entry["alg"] - if alg in published_algs: - raise ValueError(f"Algorithm already published: {alg}") - if alg not in reservations: + if entry["alg"] not in published_algs: if next_id > 65535: raise ValueError("Identifier space exhausted (maximum 65535)") - reservations[alg] = {"identifier": next_id, "source_pr": source_pr} + entry["identifier"] = next_id next_id += 1 - record = reservations[alg] - if record["source_pr"] != source_pr: - raise ValueError(f"Algorithm is reserved by another PR: {alg}") - # Legacy submitter-selected numbers are deliberately replaced. - entry["identifier"] = record["identifier"] - ledger["next_identifier"] = next_id - return ledger, result - - -def validate_reservations(entries, published, ledger): - published_algs = {entry["alg"] for entry in published} - reservations = ledger.get("algorithms", {}) - for entry in entries: - record = reservations.get(entry["alg"]) - if record is not None and record["identifier"] != entry["identifier"]: - raise ValueError(f"Identifier disagrees with allocation for {entry['alg']}") - if entry["alg"] not in published_algs and record is None: - raise ValueError(f"No reserved identifier for {entry['alg']}; use ready-to-register") + return result def main(): - parser = argparse.ArgumentParser() - parser.add_argument("--submission", action="store_true") - parser.add_argument("--published", type=Path) - parser.add_argument("--ledger", type=Path) + parser = argparse.ArgumentParser(description=__doc__) + mode = parser.add_mutually_exclusive_group() + mode.add_argument("--submission", action="store_true", + help="allow missing IDs for new entries") + mode.add_argument("--assign", action="store_true", + help="assign IDs to new entries and update the list locally") + parser.add_argument("--base-ref", default="origin/main", + help="freshly fetched target branch (default: origin/main)") args = parser.parse_args() - published = json.loads(args.published.read_text()) if args.published else [] - validate(json.loads(Path(LIST).read_text()), json.loads(Path(SCHEMA).read_text()), - published, args.submission) - if args.ledger: - validate_reservations(json.loads(Path(LIST).read_text()), published, - json.loads(args.ledger.read_text())) + published = json.loads(subprocess.check_output( + ["git", "show", f"{args.base_ref}:{LIST}"], text=True)) + schema = json.loads(Path(SCHEMA).read_text()) + entries = json.loads(Path(LIST).read_text()) + if args.assign: + # A current base must already be integrated before assigning final IDs. + subprocess.run(["git", "merge-base", "--is-ancestor", args.base_ref, "HEAD"], + check=True) + validate(published, schema) + entries = assign_identifiers(entries, published) + validate(entries, schema, published, args.submission) + if args.assign: + Path(LIST).write_text(json.dumps(entries, indent=4, ensure_ascii=False) + "\n") + published_algs = {old["alg"] for old in published} + for entry in entries: + if entry["alg"] not in published_algs: + print(f"{entry['alg']}: {entry['identifier']}") print("Submission is valid" if args.submission else "Published list is valid") diff --git a/.github/scripts/test_registry.py b/.github/scripts/test_registry.py index e3253b2..7f1a891 100644 --- a/.github/scripts/test_registry.py +++ b/.github/scripts/test_registry.py @@ -1,16 +1,14 @@ import copy -import io import json -import os from pathlib import Path +import subprocess +import sys +import tempfile import unittest -from unittest.mock import patch -from urllib.error import HTTPError from jsonschema import ValidationError -from allocate_identifiers import LABEL, STATE_BRANCH, STATE_FILE, allocation_request, prepare -from registry import LIST, SCHEMA, additions, reserve, validate, validate_reservations +from registry import LIST, SCHEMA, assign_identifiers, validate ROOT = Path(__file__).resolve().parents[2] SCHEMA_VALUE = json.loads((ROOT / SCHEMA).read_text()) @@ -43,7 +41,7 @@ def test_published_identity_cannot_change(self): changed = dict(old, **{field: value}) with self.subTest(field=field), self.assertRaises(ValueError): validate([changed], SCHEMA_VALUE, [old], submission=True) - # TWG removals remain possible; reserve() keeps the retired ID forever. + # TWG removals remain possible. validate([], SCHEMA_VALUE, [old]) def test_duplicate_algs_and_ids_rejected(self): @@ -60,242 +58,100 @@ def test_submission_still_checks_fields_and_formats(self): with self.assertRaises(ValidationError): validate([bad], SCHEMA_VALUE, submission=True) - def test_allocation_is_idempotent_and_replaces_legacy_ids(self): - original = [entry("com.example.second", 1), entry("com.example.third", None)] - ledger, allocated = reserve({}, [entry()], original, 10) - self.assertEqual([e["identifier"] for e in allocated], [2, 3]) - self.assertEqual(reserve(ledger, [entry()], original, 10), (ledger, allocated)) - self.assertEqual(original[0]["identifier"], 1) - self.assertNotIn("identifier", original[1]) - - def test_reservations_survive_abandoned_prs_and_removed_entries(self): - ledger, _ = reserve({}, [entry()], [entry("com.example.second", None)], 10) - ledger, allocated = reserve(ledger, [], [entry("com.example.third", None)], 11) - self.assertEqual(allocated[0]["identifier"], 3) - self.assertEqual(ledger["algorithms"]["com.example.first"]["identifier"], 1) - with self.assertRaises(ValueError): - reserve(ledger, [], [entry("com.example.second", None)], 12) - - def test_manual_publication_cannot_take_a_reserved_id(self): - ledger, _ = reserve({}, [entry()], [entry("com.example.second", None)], 10) - with self.assertRaises(ValueError): - reserve(ledger, [entry(), entry("com.example.interloper", 2)], [], 11) - - def test_space_exhaustion_and_corrupt_ledger_fail_closed(self): - with self.assertRaises(ValueError): - reserve({}, [entry(identifier=65535)], [entry("com.example.new", None)], 10) - with self.assertRaises(ValueError): - reserve({"algorithms": {"a": {"identifier": 1}, "b": {"identifier": 1}}}, [], [], 10) - - def test_only_new_entries_are_copied(self): - old, new = entry(), entry("com.example.new", None) - self.assertEqual(additions([old], [old, new]), [new]) - with self.assertRaises(ValueError): - additions([old], [dict(old, type="fingerprint"), new]) - with self.assertRaises(ValueError): - additions([old], [old]) - - def test_new_published_entries_require_matching_reservations(self): - old, new = entry(), entry("com.example.new", 2) - with self.assertRaisesRegex(ValueError, "No reserved"): - validate_reservations([old, new], [old], {}) - ledger, allocated = reserve({}, [old], [new], 10) - validate_reservations([old] + allocated, [old], ledger) - with self.assertRaisesRegex(ValueError, "disagrees"): - validate_reservations([old, dict(new, identifier=3)], [old], ledger) - - -class FakeGitHub: - """In-memory API: exercises orchestration without any live mutations.""" - repo = "owner/registry" - - def __init__(self): - self.published = [entry()] - self.proposed = self.published + [entry("com.example.new", None)] - self.pr = {"number": 10, "state": "open", "base": {"ref": "main", "sha": "main1"}, - "head": {"sha": "a" * 40}, "labels": [{"name": LABEL}], "changed_files": 1, - "html_url": "https://github.com/owner/registry/pull/10", "user": {"login": "contributor"}} - self.refs = {"main": "main1"} - self.contents = {"main1": {LIST: self.published, SCHEMA: SCHEMA_VALUE}} - self.integrations = [] - self.comments = [] - self.dispatches = [] - self.permission = "write" - self.conflict_once = False - self.commit_count = 0 - self.withdraw_after_reserving = False - - def get(self, path): - result = self.optional(path) - if result is None: - raise AssertionError(f"Unexpected GET {path}") - return copy.deepcopy(result) - - def optional(self, path): - if path.startswith("collaborators/"): - return {"permission": self.permission} - if path == "pulls/10": - if self.withdraw_after_reserving and STATE_BRANCH in self.refs: - self.pr["labels"] = [] - return copy.deepcopy(self.pr) - if path.startswith("pulls/10/files"): - return [{"filename": LIST}] - if path.startswith("compare/"): - return {"merge_base_commit": {"sha": "base"}} - if path.startswith("git/ref/heads/"): - name = path.removeprefix("git/ref/heads/") - return {"object": {"sha": self.refs[name]}} if name in self.refs else None - if path.startswith("git/commits/"): - return {"tree": {"sha": "main-tree"}} - if path.startswith("pulls?"): - return self.integrations - if path.startswith("issues/10/comments?"): - return self.comments - raise AssertionError(f"Unexpected GET {path}") - - def content(self, path, ref): - if ref == "base": - return copy.deepcopy(self.published) - if ref == "a" * 40: - return copy.deepcopy(self.proposed) - return copy.deepcopy(self.contents[ref][path]) - - def commit_file(self, path, value, parent, message, base_tree=None): - self.commit_count += 1 - sha = f"commit{self.commit_count}" - self.contents[sha] = {path: copy.deepcopy(value)} - return sha - - def call(self, method, path, data): - if path == "git/refs": - name = data["ref"].removeprefix("refs/heads/") - if self.conflict_once and name == STATE_BRANCH: - self.conflict_once = False - ledger, _ = reserve({}, self.published, [entry("com.example.other", None)], 99) - self.contents["concurrent"] = {STATE_FILE: ledger} - self.refs[STATE_BRANCH] = "concurrent" - raise HTTPError("test", 422, "Reference already exists", {}, io.BytesIO()) - if name in self.refs: - raise AssertionError("Duplicate branch") - self.refs[name] = data["sha"] - elif path.startswith("git/refs/heads/"): - assert data["force"] is False - self.refs[path.removeprefix("git/refs/heads/")] = data["sha"] - elif path == "pulls": - pr = dict(data, number=11, state="open", html_url="https://github.com/owner/registry/pull/11") - self.integrations.append(pr) - return pr - elif path.endswith("/dispatches"): - self.dispatches.append(data) - elif path == "issues/10/comments": - self.comments.append(dict(data, id=20, user={"login": "github-actions[bot]"})) - elif path == "issues/comments/20": - self.comments[0].update(data) - else: - raise AssertionError(f"Unexpected {method} {path}") + def test_assignment_replaces_provisional_ids_without_mutating_input(self): + old = entry(identifier=7) + proposed = [old, entry("com.example.second", 7), entry("com.example.third", None)] + assigned = assign_identifiers(proposed, [old]) + self.assertEqual([e["identifier"] for e in assigned], [7, 8, 9]) + self.assertEqual(assigned[0], old) + self.assertEqual(proposed[1]["identifier"], 7) + self.assertNotIn("identifier", proposed[2]) + validate(assigned, SCHEMA_VALUE, [old]) + self.assertEqual(assign_identifiers(assigned, [old]), assigned) + + def test_assignment_uses_maximum_in_unsorted_base(self): + published = [entry(identifier=10), entry("com.example.second", 2)] + assigned = assign_identifiers(published + [entry("com.example.new", None)], published) + self.assertEqual(assigned[-1]["identifier"], 11) + + def test_assignment_from_empty_list(self): + assigned = assign_identifiers([entry(identifier=None)], []) + self.assertEqual(assigned[0]["identifier"], 0) + + def test_identifier_limit(self): + published = [entry(identifier=65534)] + assigned = assign_identifiers(published + [entry("com.example.last", None)], published) + self.assertEqual(assigned[-1]["identifier"], 65535) + with self.assertRaisesRegex(ValueError, "exhausted"): + assign_identifiers(assigned + [entry("com.example.extra", None)], published) + + def test_assignment_recalculates_after_another_registration_merges(self): + old = entry() + pending = [old, entry("com.example.pending", 2)] + published = [old, entry("com.example.merged", 2)] + proposed = published + pending[1:] + with self.assertRaisesRegex(ValueError, "Duplicate identifier"): + validate(proposed, SCHEMA_VALUE, published) + assigned = assign_identifiers(proposed, published) + self.assertEqual(assigned[-1]["identifier"], 3) + validate(assigned, SCHEMA_VALUE, published) -class WorkflowTests(unittest.TestCase): +class CommandTests(unittest.TestCase): def setUp(self): - self.env = patch.dict(os.environ, {"GITHUB_EVENT_NAME": "pull_request_target", "GITHUB_ACTOR": "maintainer"}) - self.env.start() - self.addCleanup(self.env.stop) - self.api = FakeGitHub() - self.event = {"action": "labeled", "label": {"name": LABEL}, - "pull_request": copy.deepcopy(self.api.pr), "repository": {"default_branch": "main"}} - - def test_end_to_end_and_retry_do_not_duplicate_pr_or_comment(self): - prepare(self.api, self.event) - prepare(self.api, self.event) - self.assertEqual(len(self.api.integrations), 1) - self.assertEqual(len(self.api.comments), 1) - prepared = self.api.content(LIST, self.api.refs["bot/register-pr-10-aaaaaaaaaaaa"]) - self.assertEqual(prepared[-1]["identifier"], 2) - self.assertEqual(prepared[0], self.api.published[0]) - self.assertEqual(self.api.refs["main"], "main1") - self.assertEqual(len(self.api.dispatches), 2) - - def test_concurrent_allocator_retries_without_duplicate_id(self): - self.api.conflict_once = True - prepare(self.api, self.event) - prepared = self.api.content(LIST, self.api.refs["bot/register-pr-10-aaaaaaaaaaaa"]) - self.assertEqual(prepared[-1]["identifier"], 3) - - def test_nonmaintainer_cannot_trigger_allocation(self): - self.api.permission = "read" - with self.assertRaisesRegex(ValueError, "Only maintainers"): - prepare(self.api, self.event) - self.assertEqual(self.api.refs, {"main": "main1"}) - - def test_source_changed_after_labeling_is_rejected(self): - self.api.pr["head"]["sha"] = "b" * 40 - with self.assertRaisesRegex(ValueError, "Source changed"): - prepare(self.api, self.event) - - def test_code_changes_are_not_copied(self): - self.api.pr["changed_files"] = 2 - with self.assertRaisesRegex(ValueError, "must change only"): - prepare(self.api, self.event) - - def test_wrong_base_or_withdrawn_request_is_rejected(self): - for change in [lambda: self.api.pr.update(labels=[]), - lambda: self.api.pr["base"].update(ref="develop"), - lambda: self.api.pr.update(state="closed")]: - self.api = FakeGitHub() - change() - with self.assertRaises(ValueError): - allocation_request(self.api, self.event) - - def test_manual_retry_requires_current_label_and_maintainer(self): - with patch.dict(os.environ, {"GITHUB_EVENT_NAME": "workflow_dispatch"}): - event = dict(self.event, inputs={"pr_number": "10"}) - prepare(self.api, event) - self.api.pr["labels"] = [] - with self.assertRaises(ValueError): - prepare(self.api, event) - - def test_modified_prepared_branch_is_never_overwritten(self): - prepare(self.api, self.event) - sha = self.api.refs["bot/register-pr-10-aaaaaaaaaaaa"] - self.api.contents[sha][LIST][-1]["entryMetadata"]["description"] = "Maintainer edit" - with self.assertRaisesRegex(ValueError, "differs"): - prepare(self.api, self.event) - - def test_withdrawal_after_reservation_keeps_id_without_opening_pr(self): - self.api.withdraw_after_reserving = True - with self.assertRaisesRegex(ValueError, "withdrawn"): - prepare(self.api, self.event) - self.assertIn(STATE_BRANCH, self.api.refs) - self.assertFalse(self.api.integrations) - - def test_non_fast_forward_conflict_retries_from_winning_ledger(self): - from allocate_identifiers import persist_reservations - prepare(self.api, self.event) - original_call = self.api.call - conflict = True - - def competing_update(method, path, data): - nonlocal conflict - if method == "PATCH" and path == f"git/refs/heads/{STATE_BRANCH}" and conflict: - conflict = False - ref = self.api.refs[STATE_BRANCH] - ledger = self.api.contents[ref][STATE_FILE] - ledger, _ = reserve(ledger, self.api.published, [entry("com.example.competing", None)], 99) - self.api.contents["winner"] = {STATE_FILE: ledger} - self.api.refs[STATE_BRANCH] = "winner" - raise HTTPError("test", 422, "Not a fast forward", {}, io.BytesIO()) - return original_call(method, path, data) - - self.api.call = competing_update - _, _, _, allocated = persist_reservations(self.api, "main", [entry("com.example.next", None)], 12) - self.assertEqual(allocated[0]["identifier"], 4) - - def test_closed_prepared_pr_is_not_duplicated(self): - prepare(self.api, self.event) - self.api.integrations[0]["state"] = "closed" - with self.assertRaisesRegex(ValueError, "prepared PR is closed"): - prepare(self.api, self.event) - self.assertEqual(len(self.api.integrations), 1) + temporary = tempfile.TemporaryDirectory() + self.addCleanup(temporary.cleanup) + self.root = Path(temporary.name) + self.git("init", "-q") + self.git("config", "user.email", "test@example.com") + self.git("config", "user.name", "Registry test") + self.git("config", "commit.gpgsign", "false") + self.list = self.root / LIST + self.list.write_text(json.dumps([entry()])) + (self.root / SCHEMA).write_text(json.dumps(SCHEMA_VALUE)) + self.git("add", ".") + self.git("commit", "-qm", "Published list") + self.git("branch", "published") + self.list.write_text(json.dumps([entry(), entry("com.example.new", None)])) + + def git(self, *args): + return subprocess.run(["git", *args], cwd=self.root, check=True, + capture_output=True, text=True) + + def command(self, *args): + return subprocess.run([sys.executable, str(ROOT / ".github/scripts/registry.py"), + "--base-ref", "published", *args], cwd=self.root, + capture_output=True, text=True) + + def test_submission_then_assignment_then_strict_validation(self): + before = self.list.read_text() + self.assertEqual(self.command("--submission").returncode, 0) + self.assertEqual(self.list.read_text(), before) + self.assertNotEqual(self.command().returncode, 0) + result = self.command("--assign") + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn("com.example.new: 2", result.stdout) + self.assertEqual(self.command().returncode, 0) + assigned = self.list.read_text() + self.assertEqual(self.command("--assign").returncode, 0) + self.assertEqual(self.list.read_text(), assigned) + + def test_invalid_assignment_does_not_write(self): + proposed = json.loads(self.list.read_text()) + proposed[0]["type"] = "fingerprint" + self.list.write_text(json.dumps(proposed)) + before = self.list.read_text() + self.assertNotEqual(self.command("--assign").returncode, 0) + self.assertEqual(self.list.read_text(), before) + + def test_assignment_requires_integrated_base(self): + self.git("checkout", "-qb", "target") + self.git("commit", "--allow-empty", "-qm", "New target commit") + self.git("branch", "-f", "published") + self.git("checkout", "-") + before = self.list.read_text() + self.assertNotEqual(self.command("--assign").returncode, 0) + self.assertEqual(self.list.read_text(), before) if __name__ == "__main__": diff --git a/.github/workflows/allocate-identifiers.yml b/.github/workflows/allocate-identifiers.yml deleted file mode 100644 index 792bbc3..0000000 --- a/.github/workflows/allocate-identifiers.yml +++ /dev/null @@ -1,45 +0,0 @@ -name: Allocate algorithm identifiers - -on: - pull_request_target: - types: [labeled] - workflow_dispatch: - inputs: - pr_number: - description: 'Reviewed source PR with the ready-to-register label' - required: true - type: string - -permissions: - contents: write - pull-requests: write - issues: write - actions: write - -# Ref updates also handle simultaneous requests safely. GitHub may replace an -# older pending run in this group; reapply the label or dispatch it to retry. -concurrency: - group: sbr-identifier-allocator - cancel-in-progress: false - -jobs: - allocate: - if: >- - github.event_name == 'workflow_dispatch' || - github.event.label.name == 'ready-to-register' - runs-on: ubuntu-latest - timeout-minutes: 10 - steps: - # Never check out or execute code from the source PR. - - uses: actions/checkout@v4 - with: - ref: ${{ github.event.repository.default_branch }} - persist-credentials: false - - uses: actions/setup-python@v5 - with: - python-version: '3.12' - - run: python -m pip install jsonschema==4.26.0 - - name: Reserve IDs and prepare registration PR - env: - GH_TOKEN: ${{ github.token }} - run: python .github/scripts/allocate_identifiers.py diff --git a/.github/workflows/validate-json.yaml b/.github/workflows/validate-json.yaml index afd422c..d51c11c 100644 --- a/.github/workflows/validate-json.yaml +++ b/.github/workflows/validate-json.yaml @@ -5,7 +5,6 @@ on: branches: [ main, develop ] pull_request: branches: [ main, develop ] - workflow_dispatch: permissions: contents: read @@ -23,23 +22,22 @@ jobs: python-version: '3.12' - name: Install validator run: python -m pip install jsonschema==4.26.0 - - name: Test allocation and validation + - name: Test assignment and validation run: python -m unittest discover -s .github/scripts -p 'test_*.py' -v - name: Validate submission and published identifiers env: EVENT: ${{ github.event_name }} - BASE_REF: ${{ github.base_ref || github.event.repository.default_branch }} + BASE_REF: ${{ github.base_ref || github.ref_name }} run: | set -euo pipefail - git show "origin/$BASE_REF:softbinding-algorithm-list.json" > "$RUNNER_TEMP/published.json" if [ "$EVENT" = pull_request ]; then - python .github/scripts/registry.py --submission --published "$RUNNER_TEMP/published.json" + python .github/scripts/registry.py --submission --base-ref "origin/$BASE_REF" else - python .github/scripts/registry.py --published "$RUNNER_TEMP/published.json" + python .github/scripts/registry.py --base-ref "origin/$BASE_REF" fi - # Make this required in branch protection. ID-less submissions pass - # validate-json but cannot merge; prepared registrations pass both checks. + # Make both jobs required, with up-to-date branches. New submissions may + # omit IDs; a maintainer assigns them locally before merging the same PR. publish-ready: runs-on: ubuntu-latest steps: @@ -51,15 +49,9 @@ jobs: with: python-version: '3.12' - run: python -m pip install jsonschema==4.26.0 - - name: Require assigned IDs and preserve published entries + - name: Require complete, unique IDs and preserve published identity env: - BASE_REF: ${{ github.base_ref || github.event.repository.default_branch }} + BASE_REF: ${{ github.base_ref || github.ref_name }} run: | set -euo pipefail - git show "origin/$BASE_REF:softbinding-algorithm-list.json" > "$RUNNER_TEMP/published.json" - if git show-ref --verify --quiet refs/remotes/origin/bot/identifier-allocations; then - git show origin/bot/identifier-allocations:identifier-allocations.json > "$RUNNER_TEMP/allocations.json" - else - echo '{}' > "$RUNNER_TEMP/allocations.json" - fi - python .github/scripts/registry.py --published "$RUNNER_TEMP/published.json" --ledger "$RUNNER_TEMP/allocations.json" + python .github/scripts/registry.py --base-ref "origin/$BASE_REF" diff --git a/README.md b/README.md index 3abdf0b..ff99fc2 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,7 @@ The soft binding assertion contains a field `alg` which uniquely identifies the ## Guidelines for submitting a new entry ### Pull request -Developers of soft binding algorithms may request these be added as new entries in the soft binding algorithm list. Developers may also request amendments to their entries. These requests are made by submitting a Pull Request (PR) that adds to, or edits, the [softbinding-algorithm-list JSON array](softbinding-algorithm-list.json) in this repository and following the [schema](softbinding-algorithm-list.schema.json). For new entries, omit `identifier`: the registration bot assigns it after maintainer review. All other required fields still apply. Keep existing identifiers when amending an entry. +Developers of soft binding algorithms may request these be added as new entries in the soft binding algorithm list. Developers may also request amendments to their entries. These requests are made by submitting a Pull Request (PR) that adds to, or edits, the [softbinding-algorithm-list JSON array](softbinding-algorithm-list.json) in this repository and following the [schema](softbinding-algorithm-list.schema.json). For new entries, omit `identifier`: a maintainer assigns it locally before merge. All other required fields still apply. Keep existing identifiers when amending an entry. ### Selection rules @@ -16,7 +16,7 @@ The C2PA Technical Working Group will approve and merge PRs in accordance with i C2PA's Technical Working Group may also decide to remove malicious or non-conformant entries from the list of approved soft binding algorithms. For a PR (new entry or update) to be approved the following criteria are important: -- The published entry shall conform with the [schema](softbinding-algorithm-list.schema.json) and shall include all mandatory fields. New-entry submissions may omit `identifier` until the registration bot assigns it. +- The published entry shall conform with the [schema](softbinding-algorithm-list.schema.json) and shall include all mandatory fields. New-entry submissions may omit `identifier` until a maintainer assigns it. - The entry shall not appear to be malicious (e.g., spam) or harmful. - The PR shall be submitted by an individual affiliated with the company owning the submitted proprietary algorithm or a maintainer of the submitted open source algorithm or its fork. - The provided URLs shall successfully resolve (e.g., `softBindingResolutionApis`, `informationalUrl`). @@ -24,116 +24,52 @@ For a PR (new entry or update) to be approved the following criteria are importa - The algorithm covered by the entry shall support embedding, extracting, or both, of a soft binding identifier for the purpose of manifest recovery. - When updating an entry, the fields: `identifier`, `alg` and `type` shall not be changed. -## Automatic identifier allocation - -### Contributors - -Add your new entries to `softbinding-algorithm-list.json`, leaving out -`identifier`. For example: - -```json -{ - "alg": "com.example.watermark.1", - "type": "watermark", - "decodedMediaTypes": ["image"], - "entryMetadata": { - "description": "An image watermark carrying an identifier for manifest recovery", - "dateEntered": "2026-11-11T00:00:00Z", - "contact": "developer@example.com", - "informationalUrl": "https://example.com/watermark" - } -} -``` +## Assigning identifiers before merge + +Contributors add new entries without `identifier`; maintainers assign IDs locally +in the same PR after technical review. The public schema still requires IDs for +published entries. `validate-json` accepts ID-less new entries, while +`publish-ready` intentionally fails until IDs are assigned. Both checks reject +duplicate algorithm names or IDs and changes to published `identifier`, `alg`, +or `type` fields. Normal amendments and TWG removals remain possible. + +Maintainers process new registrations one at a time: + +1. Check out the contribution's PR branch in a local clone. Fetch the target + repository's current `main` and merge or rebase it into the PR branch. +2. Install the validator and assign IDs (replace `origin/main` if your target + repository uses another remote): + + ```sh + python3 -m pip install jsonschema==4.26.0 + python3 .github/scripts/registry.py --assign --base-ref origin/main + ``` + +3. Review the diff, commit the updated JSON, and push to the same PR branch. + If you cannot push to the contributor's branch, provide the assignment patch + for the contributor to commit. +4. Merge after normal review and both checks pass. If another registration + merges first, update the branch and rerun the command before merging. + +The command assigns consecutive IDs above the target list's highest ID to all +new entries, replacing any provisional IDs. Existing entries keep their IDs. +It requires the selected base to be an ancestor of the checked-out branch and +validates the complete result before writing. Always fetch before running it: +the command reads local Git refs and does not contact GitHub. IDs are provisional +until merged; there is no separate reservation ledger or bot-created PR. + +Require **`validate-json`** and **`publish-ready`** in the target branch's +protection rule or ruleset, together with **Require branches to be up to date +before merging**. Keep normal human review requirements. No label, bot secret, +write-enabled workflow, or state branch is needed. -Use the actual date and algorithm details. One PR may add multiple entries. -Registration PRs must only change the algorithm list and must not modify existing -entries. Submit amendments to existing entries separately, preserving their -`identifier`, `alg`, and `type`. - -The `validate-json` check accepts new entries without identifiers. The separate -`publish-ready` check intentionally fails until identifiers have been reserved. -Do not merge an unallocated submission. Previously submitted provisional IDs -are accepted when valid and unique within the submission, but the bot replaces -them with its own reservations; contributors must not rely on those numbers. - -### Maintainers - -1. Complete the normal submission review, including affiliation, documentation, - URL resolution and support for manifest recovery. -2. Add the **`ready-to-register`** label. Only a label applied by someone with - repository write permission (or higher) authorizes allocation. -3. The bot permanently reserves one ID per new `alg` and opens a separate - registration PR from a repository-owned branch. It links that PR from the - source submission, lists the allocations and records the reviewed source SHA. -4. Review and merge the prepared registration PR after its checks pass. It - contains only the new entries, added to the current published list. Then - close the original submission with a link to the merged registration PR. - -The bot never merges a PR or changes a contributor's fork. The public schema -continues to require integer IDs in the range 0–65535. Published identifiers, -algorithm names and types cannot change. Entries can be marked -`"deprecated": true`; the TWG may also remove malicious or non-conformant -entries under the selection rules. Removed entries' IDs remain reserved. - -A prepared registration is a snapshot, not a live mirror of the source PR. -After source changes, review the new revision and remove/reapply the label. -Close any superseded registration PRs; the changed source receives a new -registration branch and the same reservations for unchanged algorithm names. -If other registrations merge first, update/rebase the prepared PR and rerun its -checks; the allocator never force-pushes or overwrites a prepared branch. - -For a failed or canceled run, use **Actions → Allocate algorithm identifiers → -Run workflow**, enter the source PR number and use the default branch. The label -must still be present. Reapplying the label also retries. Repeated runs reuse -reservations and the prepared PR. If the prepared PR was closed without merging, -reopen it before retrying. The workflow log explains rejected submissions. - -### Repository setup - -After merging the automation: - -- Create the `ready-to-register` label. -- Under **Settings → Actions → General → Workflow permissions**, enable - **Allow GitHub Actions to create and approve pull requests**. The bot creates - PRs but does not approve them. Organization policy must permit this setting. - No personal access token or additional secret is required. -- Require both `validate-json` and **`publish-ready`** in the default branch's - protection rule or ruleset, and require branches to be up to date before - merging. This prevents a submission with missing, conflicting or unreserved - IDs from being merged. Keep normal human review requirements. -- Protect the exact branch **`bot/identifier-allocations`** against deletion and - force-pushes, while allowing the Actions bot to create it and make normal - fast-forward updates. It is created on the first allocation. Exclude this - state branch from automatic branch cleanup and keep it in repository backups. - -`bot/identifier-allocations` contains `identifier-allocations.json`, the durable -allocation ledger. It is deliberately separate from the published list: closed, -failed and withdrawn registrations keep their reservations. Do not delete or -rewrite this ledger; restore it from backup if it is lost before running the -allocator again. Initial allocation imports the existing published IDs, then -assigns monotonically increasing IDs above the largest imported/reserved value. -Multiple-entry reservations are committed together. Concurrent writers use -non-force Git ref updates with retries, so they cannot reserve the same number. -A different PR cannot take another PR's reserved algorithm name. - -The allocator executes only code from the trusted default branch, treats the -source PR as JSON data, rejects changes to other files, and checks the source -SHA again before preparing the registration. Its workflow has narrowly scoped -write permissions. Validation workflows have read-only permissions. The bot -explicitly dispatches validation on the prepared branch, so checks also run when -bot-created PR events do not start workflows automatically. This uses -[GitHub's documented workflow-dispatch exception](https://docs.github.com/en/actions/how-tos/write-workflows/choose-when-workflows-run/trigger-a-workflow#triggering-a-workflow-from-a-workflow). - -### Local checks - -Use Python 3.12 or later: +For local read-only checks and tests: ```sh -python -m pip install jsonschema==4.26.0 -python -m unittest discover -s .github/scripts -p 'test_*.py' -v -python .github/scripts/registry.py +python3 .github/scripts/registry.py --submission --base-ref origin/main +python3 .github/scripts/registry.py --base-ref origin/main +python3 -m unittest discover -s .github/scripts -p 'test_*.py' -v ``` -For a new-entry submission, pass `--submission`. CI additionally compares the -submission with the target branch to protect published identity fields; the -strict `publish-ready` check verifies new IDs against the allocation ledger. +The first command allows new entries without IDs; the second requires a complete +published list. The test suite covers validation, assignment, and the local CLI. From df06d10aaa3e02c35544ddc32f10e3a8f2d03cc2 Mon Sep 17 00:00:00 2001 From: Dominique Guinard Date: Mon, 16 Nov 2026 13:48:07 +0100 Subject: [PATCH 3/3] Simplifying docs --- README.md | 57 +++++++++---------------------------------------------- 1 file changed, 9 insertions(+), 48 deletions(-) diff --git a/README.md b/README.md index ff99fc2..67760b3 100644 --- a/README.md +++ b/README.md @@ -9,6 +9,15 @@ The soft binding assertion contains a field `alg` which uniquely identifies the ### Pull request Developers of soft binding algorithms may request these be added as new entries in the soft binding algorithm list. Developers may also request amendments to their entries. These requests are made by submitting a Pull Request (PR) that adds to, or edits, the [softbinding-algorithm-list JSON array](softbinding-algorithm-list.json) in this repository and following the [schema](softbinding-algorithm-list.schema.json). For new entries, omit `identifier`: a maintainer assigns it locally before merge. All other required fields still apply. Keep existing identifiers when amending an entry. +### Assigning identifiers before merge + +Contributors add new entries without `identifier`; maintainers assign IDs locally +in the same PR after technical review. The public schema still requires IDs for +published entries. `validate-json` accepts ID-less new entries, while +`publish-ready` intentionally fails until IDs are assigned. Both checks reject +duplicate algorithm names or IDs and changes to published `identifier`, `alg`, +or `type` fields. Normal amendments and deprecation remain possible. + ### Selection rules The C2PA Technical Working Group will approve and merge PRs in accordance with its prevailing processes for approving technical contributions to the C2PA specification. @@ -24,52 +33,4 @@ For a PR (new entry or update) to be approved the following criteria are importa - The algorithm covered by the entry shall support embedding, extracting, or both, of a soft binding identifier for the purpose of manifest recovery. - When updating an entry, the fields: `identifier`, `alg` and `type` shall not be changed. -## Assigning identifiers before merge - -Contributors add new entries without `identifier`; maintainers assign IDs locally -in the same PR after technical review. The public schema still requires IDs for -published entries. `validate-json` accepts ID-less new entries, while -`publish-ready` intentionally fails until IDs are assigned. Both checks reject -duplicate algorithm names or IDs and changes to published `identifier`, `alg`, -or `type` fields. Normal amendments and TWG removals remain possible. - -Maintainers process new registrations one at a time: - -1. Check out the contribution's PR branch in a local clone. Fetch the target - repository's current `main` and merge or rebase it into the PR branch. -2. Install the validator and assign IDs (replace `origin/main` if your target - repository uses another remote): - - ```sh - python3 -m pip install jsonschema==4.26.0 - python3 .github/scripts/registry.py --assign --base-ref origin/main - ``` - -3. Review the diff, commit the updated JSON, and push to the same PR branch. - If you cannot push to the contributor's branch, provide the assignment patch - for the contributor to commit. -4. Merge after normal review and both checks pass. If another registration - merges first, update the branch and rerun the command before merging. - -The command assigns consecutive IDs above the target list's highest ID to all -new entries, replacing any provisional IDs. Existing entries keep their IDs. -It requires the selected base to be an ancestor of the checked-out branch and -validates the complete result before writing. Always fetch before running it: -the command reads local Git refs and does not contact GitHub. IDs are provisional -until merged; there is no separate reservation ledger or bot-created PR. - -Require **`validate-json`** and **`publish-ready`** in the target branch's -protection rule or ruleset, together with **Require branches to be up to date -before merging**. Keep normal human review requirements. No label, bot secret, -write-enabled workflow, or state branch is needed. - -For local read-only checks and tests: - -```sh -python3 .github/scripts/registry.py --submission --base-ref origin/main -python3 .github/scripts/registry.py --base-ref origin/main -python3 -m unittest discover -s .github/scripts -p 'test_*.py' -v -``` -The first command allows new entries without IDs; the second requires a complete -published list. The test suite covers validation, assignment, and the local CLI.