diff --git a/.github/scripts/registry.py b/.github/scripts/registry.py new file mode 100644 index 0000000..ce80a8b --- /dev/null +++ b/.github/scripts/registry.py @@ -0,0 +1,90 @@ +"""Validate registry changes and assign new identifiers locally before merging.""" + +import argparse +import copy +import json +import subprocess +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. + continue + for field in ("identifier", "alg", "type"): + if new.get(field) != old[field]: + raise ValueError(f"Cannot change published {field} for {old['alg']}") + + +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: + if entry["alg"] not in published_algs: + if next_id > 65535: + raise ValueError("Identifier space exhausted (maximum 65535)") + entry["identifier"] = next_id + next_id += 1 + return result + + +def main(): + 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(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") + + +if __name__ == "__main__": + main() diff --git a/.github/scripts/test_registry.py b/.github/scripts/test_registry.py new file mode 100644 index 0000000..7f1a891 --- /dev/null +++ b/.github/scripts/test_registry.py @@ -0,0 +1,158 @@ +import copy +import json +from pathlib import Path +import subprocess +import sys +import tempfile +import unittest + +from jsonschema import ValidationError + +from registry import LIST, SCHEMA, assign_identifiers, validate + +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. + 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_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 CommandTests(unittest.TestCase): + def setUp(self): + 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__": + unittest.main() diff --git a/.github/workflows/validate-json.yaml b/.github/workflows/validate-json.yaml index b53a482..d51c11c 100644 --- a/.github/workflows/validate-json.yaml +++ b/.github/workflows/validate-json.yaml @@ -6,27 +6,52 @@ on: pull_request: branches: [ main, develop ] +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 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.ref_name }} + run: | + set -euo pipefail + if [ "$EVENT" = pull_request ]; then + python .github/scripts/registry.py --submission --base-ref "origin/$BASE_REF" + else + python .github/scripts/registry.py --base-ref "origin/$BASE_REF" + fi + + # 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: + - 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 complete, unique IDs and preserve published identity + env: + BASE_REF: ${{ github.base_ref || github.ref_name }} + run: | + set -euo pipefail + python .github/scripts/registry.py --base-ref "origin/$BASE_REF" diff --git a/README.md b/README.md index cb5edae..4ef2c6a 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,16 @@ 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`: 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 @@ -16,15 +25,13 @@ 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 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`). - when present, `softBindingResolutionApis` shall reference APIs implementing at least the mandatory endpoints of the [C2PA Soft Binding Resolution API specification](https://spec.c2pa.org/specifications/specifications/2.5/softbinding/Decoupled.html) - `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.