From 34cb086ac1fbd98588c1f46e68358ce632a16da7 Mon Sep 17 00:00:00 2001 From: anthonyanderson Date: Sun, 29 Nov 2026 19:22:26 -0500 Subject: [PATCH] A mod can move to a new author key (key-handover.json) An update signed with another key than the installed mod's is still refused, unless the mod carries key-handover.json: steps, each signed by the key it leaves, that lead from the installed key to the release's. Signing handover adds a step, handover-check verifies a chain. The engine then installs it, says the key moved, and only the new key updates it from then on; automatic staging accepts a catalogue entry whose "key_from" names the installed key. catalog.py add takes the new key from such a zip (recording "key_from"), check --base allows the change only with it, and check --download verifies the handover. A key change is never an auto-merged bump. This is what lets each Open-HMG mod have its own key (docs/mod-repos.md). Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 4 + core/runtime/java/hmgapi/engine/Catalog.java | 14 ++- core/runtime/java/hmgapi/engine/Packages.java | 24 ++++- core/runtime/java/hmgapi/engine/Signing.java | 100 +++++++++++++++++- core/runtime/packages-test.sh | 19 ++++ core/runtime/signing-test.sh | 30 ++++++ docs/mod-reference.md | 32 ++++++ docs/mod-repos.md | 20 ++++ tools/catalog-test.sh | 30 ++++++ tools/catalog.py | 55 ++++++++-- tools/mkmodpkg.sh | 2 + 11 files changed, 317 insertions(+), 13 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a426e0cf..c10112d5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,10 @@ ## Unreleased +- **A mod can move to a new author key** without owners removing it: the old key signs + `key-handover.json` (`Signing handover`), and an update by the new key goes in only when + those steps lead from the installed key to it. The catalogue takes the new key the same way + (`"key_from"`), always through a maintainer. So each mod can have its own key. - **Dependencies are installed with a mod.** A mod's `requires` (copied into its catalogue entry by `catalog.py add`, and read again from the downloaded zip's `mod.json`) are met by what's installed, or by the catalogue's version, installed first; a required mod that's diff --git a/core/runtime/java/hmgapi/engine/Catalog.java b/core/runtime/java/hmgapi/engine/Catalog.java index 96ccf4b8..1bc52cc0 100644 --- a/core/runtime/java/hmgapi/engine/Catalog.java +++ b/core/runtime/java/hmgapi/engine/Catalog.java @@ -1532,6 +1532,18 @@ static String pure(Plan p, String id) { return null; } + /** + * The keys an entry's mod was handed over from ("key_from", catalog.py add writes it from the zip's + * key-handover.json): a hint only, since the catalogue isn't signed. The install checks the handover itself. + */ + @SuppressWarnings("unchecked") + static Set keyFrom(Map en) { + Set out = new HashSet(); + Object k = en == null ? null : en.get("key_from"); + if (k instanceof List) for (Object o : (List) k) out.add(String.valueOf(o).toLowerCase()); + return out; + } + /** * The automatic check's staging of one mod: only a pure update, signed with the installed key, into * /data/hmgapi/pending/ (engine apply puts it in place). null when staged, else why not. @@ -1542,7 +1554,7 @@ String stage(String id) throws Exception { if (why != null) return why; Step s = p.steps.get(0); String have = Packages.installedUuid(new File(e.data, "mods/" + id)); - if (have == null || !have.equalsIgnoreCase(String.valueOf(s.entry.get("uuid")))) { + if (have == null || !(have.equalsIgnoreCase(String.valueOf(s.entry.get("uuid"))) || keyFrom(s.entry).contains(have.toLowerCase()))) { return "the catalogue names another author key than the installed " + id + "'s: update it yourself"; } String off = offline(); diff --git a/core/runtime/java/hmgapi/engine/Packages.java b/core/runtime/java/hmgapi/engine/Packages.java index 256cc5b2..24403ff3 100644 --- a/core/runtime/java/hmgapi/engine/Packages.java +++ b/core/runtime/java/hmgapi/engine/Packages.java @@ -26,6 +26,12 @@ * the owner's settings and whether the mod is on. Files change only at the * next `engine apply`. --force: an older version, or (with * hmgapi.json overrides.allow_unsigned) an unsigned package, at the owner's risk. + * + * A new author key: an update signed with another key than the installed mod's goes + * in only when the mod's key-handover.json leads from the installed key to it, each + * step signed by the key it leaves (Signing.handoverChain). The installed key itself + * says what comes next, so nobody else can take a mod over; afterwards the new key + * is the installed one, and only it updates the mod. */ final class Packages { private Packages() {} @@ -120,8 +126,20 @@ static Verdict check(Engine e, File dir, String uuid, boolean force, boolean any File old = new File(installed, "mod.json"); v.installedVersion = old.isFile() ? String.valueOf(Json.object(Engine.read(old)).get("version")) : null; - // signature and author - Signing.Result sig = Signing.verify(dir, haveUuid); + // signature and author: the installed key, or a key it handed the mod over to + Signing.Result sig = Signing.verify(dir, null); + boolean moved = false; + if (sig.ok && haveUuid != null && !haveUuid.equalsIgnoreCase(sig.uuid)) { + String why = Signing.handoverChain(dir, sig.id, haveUuid, sig.uuid); + if (why == null) { + moved = true; + String who = trustedAuthor(e, sig.uuid); + v.notes.add("key " + v.id + " moves to author key " + sig.uuid + (who != null ? " (" + who + ")" : "") + + ", handed over by the installed key " + haveUuid + " (" + Signing.HANDOVER + "); its updates now come from the new key"); + } else { + Signing.fail(sig, "signed by a different author (uuid " + sig.uuid + ", installed mod has " + haveUuid + "); " + why); + } + } if (sig.ok) v.uuid = sig.uuid; if (!sig.ok) { boolean unsigned = !new File(dir, Signing.DIR + "/signature").isFile(); @@ -175,7 +193,7 @@ else if (!Version.satisfies(dv, d.range)) { } else { v.status = "new"; } - if (sig.ok && uuid != null && !uuid.equalsIgnoreCase(sig.uuid)) { + if (sig.ok && uuid != null && !uuid.equalsIgnoreCase(sig.uuid) && !(moved && uuid.equalsIgnoreCase(haveUuid))) { return refuse(v, v.id + " is signed by author key " + sig.uuid + ", not the expected " + uuid); } if (sig.ok && haveUuid == null) { // a first install: its key is recorded, and said diff --git a/core/runtime/java/hmgapi/engine/Signing.java b/core/runtime/java/hmgapi/engine/Signing.java index c04ab974..183a13be 100644 --- a/core/runtime/java/hmgapi/engine/Signing.java +++ b/core/runtime/java/hmgapi/engine/Signing.java @@ -28,6 +28,12 @@ * sign writes META-HMGAPI/manifest.json and META-HMGAPI/signature * sign-hmgapi the same for a HMG-API release (id "hmgapi", version from VERSION) * verify [] checks every file, the signature, and the UUID + * handover + * adds a step to /key-handover.json: the old key + * says the mod's updates now come from the new key + * handover-check + * verify, and that key-handover.json leads from that key to + * the one the folder is signed with * * A mod's UUID is derived from its author's public key (SHA-256 of the encoded * key, first 16 bytes, as a version-8 UUID), so only the key holder can sign a @@ -37,6 +43,15 @@ * manifest.json: {"format": 1, "id", "version", "uuid", "key": , "files": {"": "", ...}}. signature: base64 ECDSA * (DER) over the manifest's exact bytes. + * + * Moving a mod to a new key: an update signed with another key than the installed + * mod's is refused, unless the mod carries key-handover.json, where the installed + * key itself says which key comes next: {"format": 1, "steps": [{"id", "from", + * "from_key": , "to", "signature"}, ...]}, each signature + * the from key's ECDSA over handoverText(id, from, to). The steps chain (old to + * newer to newest), so a car that skipped a release still follows. The file is an + * ordinary file of the mod (in the manifest, so the new key signs over it too) and + * stays in every later release. */ public final class Signing { private Signing() {} @@ -61,12 +76,20 @@ public static void main(String[] a) throws Exception { } else if (a.length >= 3 && "sign-hmgapi".equals(a[0])) { File d = new File(a[1]); System.out.println(signAs(d, new File(a[2]), "hmgapi", Engine.read(new File(d, "VERSION")).trim())); + } else if (a.length >= 4 && "handover".equals(a[0])) { + System.out.println(handover(new File(a[1]), new File(a[2]), new File(a[3]))); + } else if (a.length >= 3 && "handover-check".equals(a[0])) { + Result r = verify(new File(a[1]), null); + String why = !r.ok ? r.error : handoverChain(new File(a[1]), r.id, a[2], r.uuid); + System.out.println(why == null ? "ok: " + r.id + " " + r.version + " key " + a[2] + " to " + r.uuid : "FAILED: " + why); + System.exit(why == null ? 0 : 1); } else if (a.length >= 2 && "verify".equals(a[0])) { Result r = verify(new File(a[1]), a.length > 2 ? a[2] : null); System.out.println(r.ok ? "ok: " + r.id + " " + r.version + " uuid " + r.uuid : "FAILED: " + r.error); System.exit(r.ok ? 0 : 1); } else { - System.err.println("usage: keygen | uuid | sign | verify [uuid]"); + System.err.println("usage: keygen | uuid | sign | verify [uuid]" + + " | handover | handover-check "); System.exit(2); } } @@ -127,6 +150,81 @@ public static String signAs(File mod, File keyFile, String id, String version) t return "signed " + id + " " + version + ": " + files.size() + " files, uuid " + man.get("uuid"); } + // ---- key handover + + static final String HANDOVER = "key-handover.json"; + + /** what the old key signs: the mod, the old key and the next one */ + static String handoverText(String id, String from, String to) { + return "HMG-API key handover\nid " + id + "\nfrom " + from + "\nto " + to + "\n"; + } + + /** Adds a step from oldKey to newKey (a key file or its .pub) to mod's key-handover.json. */ + @SuppressWarnings("unchecked") + public static String handover(File mod, File oldKey, File newKey) throws Exception { + String id = String.valueOf(Json.object(Engine.read(new File(mod, "mod.json"))).get("id")); + PublicKey oldPub = publicOf(oldKey); + String from = uuid(oldPub.getEncoded()), to = uuid(publicOf(newKey).getEncoded()); + if (from.equals(to)) throw new IOException("the old and new keys are the same key"); + PrivateKey priv = KeyFactory.getInstance("EC").generatePrivate(new PKCS8EncodedKeySpec(unb64(Engine.read(oldKey).trim()))); + Signature s = Signature.getInstance("SHA256withECDSA"); + s.initSign(priv); + s.update(handoverText(id, from, to).getBytes("UTF-8")); + File f = new File(mod, HANDOVER); + Map doc = f.isFile() ? Json.object(Engine.read(f)) : new LinkedHashMap(); + List steps = doc.get("steps") instanceof List ? (List) doc.get("steps") : new ArrayList(); + for (Object o : steps) { + if (o instanceof Map && from.equals(((Map) o).get("from"))) throw new IOException(HANDOVER + " already hands " + from + " over"); + } + Map step = new LinkedHashMap(); + step.put("id", id); + step.put("from", from); + step.put("from_key", b64(oldPub.getEncoded())); + step.put("to", to); + step.put("signature", b64(s.sign())); + steps.add(step); + Map out = new LinkedHashMap(); + out.put("format", 1L); + out.put("steps", steps); + Engine.write(f, Json.write(out) + "\n"); + return "key-handover " + id + ": " + from + " to " + to + " (" + steps.size() + (steps.size() == 1 ? " step)" : " steps)") + + "; sign the mod with the new key, and keep " + HANDOVER + " in every release"; + } + + /** + * null when mod's key-handover.json leads from key {@code from} to key {@code to} for mod {@code id}, + * each step signed by the key it leaves; else why not. + */ + @SuppressWarnings("unchecked") + public static String handoverChain(File mod, String id, String from, String to) { + try { + File f = new File(mod, HANDOVER); + if (!f.isFile()) return "no " + HANDOVER; + Object st = Json.object(Engine.read(f)).get("steps"); + List steps = st instanceof List ? (List) st : new ArrayList(); + String cur = from.toLowerCase(); + for (int hops = 0; hops < 16 && !cur.equalsIgnoreCase(to); hops++) { + Map next = null; + for (Object o : steps) { + if (o instanceof Map && cur.equals(((Map) o).get("from"))) next = (Map) o; + } + if (next == null) return HANDOVER + " has no step from key " + cur; + if (!id.equals(next.get("id"))) return HANDOVER + ": the step from " + cur + " is for " + next.get("id") + ", not " + id; + byte[] key = unb64(String.valueOf(next.get("from_key"))); + if (!cur.equals(uuid(key))) return HANDOVER + ": the step from " + cur + " carries another key"; + String nx = String.valueOf(next.get("to")); + Signature s = Signature.getInstance("SHA256withECDSA"); + s.initVerify(KeyFactory.getInstance("EC").generatePublic(new X509EncodedKeySpec(key))); + s.update(handoverText(id, cur, nx).getBytes("UTF-8")); + if (!s.verify(unb64(String.valueOf(next.get("signature"))))) return HANDOVER + ": the step from " + cur + " isn't signed by that key"; + cur = nx.toLowerCase(); + } + return cur.equalsIgnoreCase(to) ? null : HANDOVER + " doesn't lead to key " + to; + } catch (Exception x) { + return HANDOVER + ": " + x; + } + } + // ---- verify public static final class Result { diff --git a/core/runtime/packages-test.sh b/core/runtime/packages-test.sh index 11ca6b2b..e9b58ffe 100755 --- a/core/runtime/packages-test.sh +++ b/core/runtime/packages-test.sh @@ -135,4 +135,23 @@ ln -s $T/victim/top $R/data/hmgapi/mods/demo/filelink eng remove demo; check "remove a mod with symlinks in its folder" 0 $rc check "... the mod's folder is gone" no "$([ -e $R/data/hmgapi/mods/demo ] && echo yes || echo no)" check "... what the links pointed at is all still there" "keep keep" "$(cat $T/victim/sub/file $T/victim/top 2>/dev/null | tr '\n' ' ' | sed 's/ $//')" + +# a new author key: the installed key hands the mod over (key-handover.json, Signing handover) +mk 1.0.0; sig sign $T/m $T/author.key > /dev/null; pkg $T/m $T/k1.zip +eng install $T/k1.zip; check "key move: installed by the old key" 0 $rc +sig keygen $T/new.key > /dev/null; N=$(sig uuid $T/new.key) +mk 1.1.0; sig sign $T/m $T/new.key > /dev/null; pkg $T/m $T/k2.zip +eng install $T/k2.zip; check "a new key without a handover: refused" 3 $rc; has "... says why" "signed by a different author (uuid $N, installed mod has $U); no key-handover.json" "$out" +mk 1.1.0; sig handover $T/m $T/other.key $T/new.key.pub > /dev/null; sig sign $T/m $T/new.key > /dev/null; pkg $T/m $T/k3.zip +eng install $T/k3.zip; check "a handover from a key that isn't the installed one: refused" 3 $rc +mk 1.1.0; sig handover $T/m $T/author.key $T/new.key.pub > /dev/null; sig sign $T/m $T/new.key > /dev/null; pkg $T/m $T/k4.zip +eng install $T/k4.zip --uuid $U; check "handed over by the installed key (expected: the installed key, as release updates pass)" 0 $rc +has "... says the key moves" "key demo moves to author key $N, handed over by the installed key $U" "$out" +check "... the new key is the installed one" "$N" "$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["uuid"])' $R/data/hmgapi/mods/demo/META-HMGAPI/manifest.json)" +mk 1.2.0; sig sign $T/m $T/author.key > /dev/null; pkg $T/m $T/k5.zip +eng install $T/k5.zip; check "after the move, the old key: refused" 3 $rc +mk 1.2.0; sig handover $T/m $T/author.key $T/new.key.pub > /dev/null; sig sign $T/m $T/new.key > /dev/null; pkg $T/m $T/k6.zip +eng install $T/k6.zip --uuid $N; check "the new key's next release (expected: the catalogue's new key)" 0 $rc +hasnt "... no move this time" "moves to author key" "$out" +eng remove demo > /dev/null exit $fail diff --git a/core/runtime/signing-test.sh b/core/runtime/signing-test.sh index cea4f0cf..bbcb6baf 100644 --- a/core/runtime/signing-test.sh +++ b/core/runtime/signing-test.sh @@ -45,4 +45,34 @@ cp -r "$T/hello" "$T/t6"; S sign "$T/t6" "$T/forger.key" > /dev/null v "$T/t6" "$U"; check "update by another key refused" 1 $rc cp -r "$T/hello" "$T/t7"; sed 's/"version": "1.0.0"/"version": "9.9.9"/' "$T/t7/mod.json" > "$T/t7/mod.json.new" && mv "$T/t7/mod.json.new" "$T/t7/mod.json" v "$T/t7"; check "edited mod.json refused" 1 $rc + +# key handover: the installed key says which key the mod moves to (key-handover.json) +S keygen "$T/new.key" > /dev/null; S keygen "$T/newer.key" > /dev/null; N=$(S uuid "$T/new.key") +hc() { set +e; out=$(S handover-check "$@" 2>&1); rc=$?; set -e; } +cp -r mods/examples/hello "$T/h"; rm -rf "$T/h/META-HMGAPI" +has "handover" "key-handover hello: $U to $N (1 step)" "$(S handover "$T/h" "$T/author.key" "$T/new.key.pub")" +S sign "$T/h" "$T/new.key" > /dev/null +v "$T/h"; check "... the handover file is signed with the mod" 0 $rc +hc "$T/h" "$U"; check "handover-check: the old key to the new one" 0 $rc; has "says so" "ok: hello 1.0.0 key $U to $N" "$out" +hc "$T/h" "00000000-0000-8000-8000-000000000000"; check "... from a key it doesn't name: refused" 1 $rc +has "... says why" "has no step from key 00000000-0000-8000-8000-000000000000" "$out" +set +e; S handover "$T/h" "$T/author.key" "$T/newer.key" > /dev/null 2>&1; rc=$?; set -e +check "... the same old key can't hand over twice" 1 $rc +has "a second step" "(2 steps)" "$(S handover "$T/h" "$T/new.key" "$T/newer.key")" +S sign "$T/h" "$T/newer.key" > /dev/null +hc "$T/h" "$U"; check "a chain: old to new to newer" 0 $rc +hc "$T/h" "$N"; check "... and from the middle" 0 $rc +# a forger's step: their own signature, claiming to leave the real key +cp -r mods/examples/hello "$T/f"; rm -rf "$T/f/META-HMGAPI"; S handover "$T/f" "$T/forger.key" "$T/new.key.pub" > /dev/null +python3 - "$T/f/key-handover.json" "$U" "$(cat "$T/author.key.pub")" <<'P' +import json, sys +d = json.load(open(sys.argv[1])); d['steps'][0]['from'] = sys.argv[2]; d['steps'][0]['from_key'] = sys.argv[3].strip() +json.dump(d, open(sys.argv[1], 'w')) +P +S sign "$T/f" "$T/new.key" > /dev/null +hc "$T/f" "$U"; check "a step not signed by the key it leaves: refused" 1 $rc; has "... says why" "isn't signed by that key" "$out" +# another mod's handover doesn't move this one +cp -r "$T/h" "$T/o"; sed 's/"id": "hello"/"id": "other"/' "$T/o/mod.json" > "$T/o/mod.json.new" && mv "$T/o/mod.json.new" "$T/o/mod.json" +S sign "$T/o" "$T/newer.key" > /dev/null +hc "$T/o" "$U"; check "another mod's handover: refused" 1 $rc; has "... says why" "is for hello, not other" "$out" exit $fail diff --git a/docs/mod-reference.md b/docs/mod-reference.md index ae07beb8..ee9af76f 100644 --- a/docs/mod-reference.md +++ b/docs/mod-reference.md @@ -540,6 +540,38 @@ your source. Keep your key private and backed up: a lost key means a new UUID, and owners would have to remove the old mod before installing yours again. +### Moving to a new key + +A mod can move to a new author key without owners removing it, as long as you still +have the old key (a lost key can't be handed over). The old key signs a short +statement, `key-handover.json` at the top of your mod folder, naming the mod and the +key that comes next: + +``` +java -cp /lib/hmgapi-engine.jar hmgapi.engine.Signing keygen new.key +java -cp /lib/hmgapi-engine.jar hmgapi.engine.Signing handover old.key new.key.pub +``` + +Commit `key-handover.json`, sign the next release with the new key, and set +`"hmgapi"` to the HMG-API release that first reads handovers or newer (an older head +unit refuses an update by another key, whatever the file says). Then: + +- An installed copy signed by the old key takes the update: the install checks that + each step of `key-handover.json` is signed by the key it leaves, and that the steps + lead from the installed key to the one the release is signed with. It says the key + moved. From then on only the new key updates the mod; the old key no longer does. +- Keep `key-handover.json` in every later release, so a car that skipped the first + one still follows. A second move adds a step (`handover new.key + newer.key.pub`); the file chains them. +- In the catalogue, `tools/catalog.py add` takes the new key when the zip hands the + old one over, lists it in `maps/authors.json`, and records the old one in the + entry's `"key_from"`. CI checks the handover in the download. A key change is never + a plain version bump, so a maintainer merges it. +- A new key isn't on older HMG-API releases' trusted author list, but that only + matters for a first install: updates follow the handover. +- Nobody else can move your mod: a handover only counts when the installed key signed + it, and it names one mod id. + ### Updates from your own releases A mod the catalogue doesn't list (installed from USB or adb, private, or waiting for diff --git a/docs/mod-repos.md b/docs/mod-repos.md index d67f2b1d..a9c11433 100644 --- a/docs/mod-repos.md +++ b/docs/mod-repos.md @@ -135,6 +135,26 @@ four repo environments; each is `v*`-tag-only with Admin bypass. `maps/authors.json`: the key's `repos` gets the new repo URLs (the catalogue checks an entry's `repo` against them). +### Later: each mod its own key + +Decision B was the only way while a new key stranded installed cars. Key handovers +(`key-handover.json`, the mod reference's "Moving to a new key") remove that, so each +Open-HMG mod moves to its own key, one mod at a time: + +1. A HMG-API release that reads handovers is out (older units refuse the new key's + update whatever the file says, so each mod's `"hmgapi"` floor names that release). +2. For each of `wireless-carplay-aa`, `adb`, `adbd` and `nemesis-shortcut`, VysseCodes: + `Signing keygen` a key for that mod; `Signing handover + .pub` and commit `key-handover.json`; replace `MOD_KEY` (and + `.github/mod-key.pub`) in that repo's `release` environment; raise `"hmgapi"`. +3. Its next release goes into the catalogue by a maintainer's PR (`tools/catalog.py + add` takes the new key and writes `"key_from"`; not an auto-merged bump). +4. When all four have moved, the shared key `7251ce71-…` signs nothing new. Keep it + offline: it still signs further handovers, should a car still be on it. + +New Open-HMG mods (Phone Turn-by-Turn is the first) start with their own key and need +no handover. + ## 6. Core release bundling `tools/release-mods.txt` becomes a list of catalogue ids (`wireless-carplay-aa`, `adb`, diff --git a/tools/catalog-test.sh b/tools/catalog-test.sh index 4bedfce3..a83a042e 100755 --- a/tools/catalog-test.sh +++ b/tools/catalog-test.sh @@ -288,4 +288,34 @@ for v, r, want in [('1.1.0', '^1.0.0', True), ('2.0.0', '^1.0.0', False), ('0.3. assert s(v, r) == want, (v, r, want) P +# a new author key the old one hands over to (key-handover.json, Signing handover) +G checkout -q main 2>/dev/null; G checkout -q -- . +S keygen $T/n.key > /dev/null; UN=$(S uuid $T/n.key) +HD=https://github.com/example/hello/releases/download/v1.2.0/hello-1.2.0.zip +pkgn() { # pkgn : hello signed with the new key + rm -rf $T/hn; cp -r mods/examples/hello $T/hn; rm -rf $T/hn/META-HMGAPI + python3 - $T/hn/mod.json $1 <<'P' +import json, sys +m = json.load(open(sys.argv[1])); m['version'] = sys.argv[2]; m['authors'] = ['Test Author']; m['repo'] = 'https://github.com/example/hello' +json.dump(m, open(sys.argv[1], 'w')) +P + [ $2 = yes ] && S handover $T/hn $T/a.key $T/n.key.pub > /dev/null + S sign $T/hn $T/n.key > /dev/null + (cd $T/hn && rm -f $3 && zip -qr $3 .) +} +pkgn 1.2.0 no $T/hn0.zip +C add $T/hn0.zip --download $HD; check "add: a new key without a handover refused" 1 $rc; has "... says how" "unless the old key hands it over" "$out" +pkgn 1.2.0 yes $T/hn1.zip +C add $T/hn1.zip --download $HD; check "add: a new key the old one hands over to" 0 $rc; has "... says so" "hello: author key $UA hands over to $UN" "$out" +check "... the entry has the new key and where it came from" "$UN ['$UA']" "$(python3 -c 'import json,sys; e=json.load(open(sys.argv[1])); print(e["uuid"], e["key_from"])' $R/catalog/hello.json)" +has "... the new key is listed" "\"$UN\"" "$(cat $R/maps/authors.json)" +C check --base main; check "check --base: the key change with key_from" 0 $rc +cp $T/hn1.zip $T/dl/hello-1.2.0.zip +F check --download --base main; check "check --download: the zip's handover checked" 0 $rc; has "... says so" "handed over from $UA" "$out" +cp $T/hn0.zip $T/dl/hello-1.2.0.zip; J $R/catalog/hello.json "d['sha256']='$(sha256sum $T/hn0.zip | cut -d' ' -f1)'" +F check --download --base main; check "check --download: key_from but no handover in the zip refused" 1 $rc; has "... says why" "\"key_from\" names $UA" "$out" +J $R/catalog/hello.json "del d['key_from']" +C check --base main; check "check --base: a key change without key_from refused" 1 $rc; has "... says why" "unless its zip hands the old key over" "$out" +G checkout -q -- . + [ $fail = 0 ] && echo "catalog: all ok" || { echo "catalog: FAILED"; exit 1; } diff --git a/tools/catalog.py b/tools/catalog.py index fa10d0ed..80feefad 100755 --- a/tools/catalog.py +++ b/tools/catalog.py @@ -7,7 +7,8 @@ tools/catalog.py add --download [--repo ] write catalog/.json from a signed package (tools/mkmodpkg.sh) and list its - author key in maps/authors.json; an update keeps the entry's author key + author key in maps/authors.json; an update keeps the entry's author key, or moves + it to a new one the zip's key-handover.json leads to (recorded in "key_from") tools/catalog.py check [--download] [--base ] every entry well-formed and its key listed; --download fetches each zip, checks its SHA-256 and signature and that it is the mod and version the entry says; @@ -47,7 +48,7 @@ FINAL = re.compile(r'^\d+\.\d+\.\d+$') # what an entry's "version" is: no pre-releases (docs/releasing.md) HTTPS = re.compile(r'^https://[A-Za-z0-9.-]+(:\d+)?/[^\s<>()\[\]"\']*$') FIELDS = {'id', 'name', 'description', 'authors', 'license', 'uuid', 'version', 'repo', 'download', 'sha256', 'system', 'hmgapi', - 'requires', 'conflicts', 'wifi'} # requires/conflicts: as the zip's mod.json (HMG-API's catalogue installs requires first); + 'requires', 'conflicts', 'wifi', 'key_from'} # requires/conflicts: as the zip's mod.json (HMG-API's catalogue installs requires first); # wifi: {"hotspot": true} as mod.json (a chip the unit never powers will do, SystemCheck) # the only hosts the head unit downloads from (Http.HOSTS): a download anywhere else could never install GITHUB = {'github.com', 'api.github.com', 'raw.githubusercontent.com', 'objects.githubusercontent.com', @@ -135,6 +136,15 @@ def verify(moddir, uuid=None): return r.returncode == 0, (r.stdout + r.stderr).strip() +def handover(moddir, from_uuid): + """hmgapi.engine.Signing handover-check: moddir verifies, and its key-handover.json leads from + from_uuid to the key it's signed with (as the head unit checks an update by a new key)""" + verify(moddir) # the engine compiled + r = subprocess.run(['java', '-cp', _engine, 'hmgapi.engine.Signing', 'handover-check', moddir, from_uuid], + capture_output=True, text=True) + return r.returncode == 0, (r.stdout + r.stderr).strip() + + def package(zpath): """mod.json, the signed manifest and the SHA-256 of a package, after its signature checks""" work = tempfile.mkdtemp(prefix='catalog-pkg-') @@ -220,11 +230,23 @@ def cmd_add(a): if not authors: die('mod.json has no "authors"') path = os.path.join(CATALOG, mid + '.json') + key_from = [] if os.path.exists(path): old = load(path) - if old.get('uuid', '').lower() != uuid: - die(f'{mid} is in the catalogue under author key {old.get("uuid")}; this package is signed with {uuid}. ' - 'Only the same key updates a mod (owners would have to remove it first): pick a new id, or sign with the original key.') + key_from = [k for k in old.get('key_from') or [] if isinstance(k, str)] + was = old.get('uuid', '').lower() + if was != uuid: + work = tempfile.mkdtemp(prefix='catalog-handover-') + try: + ok, out = handover(unpack(a.zip, work), was) + finally: + shutil.rmtree(work, ignore_errors=True) + if not ok: + die(f'{mid} is in the catalogue under author key {was}; this zip is signed with {uuid} ({out}). ' + 'Only the same key updates a mod, unless the old key hands it over: key-handover.json in the mod, made with ' + 'Signing handover (the mod reference\'s "Moving to a new key").') + key_from.append(was) + print(f'{mid}: author key {was} hands over to {uuid} (key-handover.json)') if vkey(ver) < vkey(old.get('version', '0.0.0')): die(f'{mid} {ver} is older than the catalogue\'s {old.get("version")}') e = {'id': mid, 'name': mod.get('name', mid), 'description': mod.get('description', ''), 'authors': authors, @@ -238,6 +260,8 @@ def cmd_add(a): e[k] = mod[k] if isinstance(mod.get('wifi'), dict) and mod['wifi'].get('hotspot') is True: e['wifi'] = {'hotspot': True} # so the head unit judges "system" as the install will (an unpowered chip will do) + if key_from: + e['key_from'] = list(dict.fromkeys(key_from)) if not e['license']: del e['license'] os.makedirs(CATALOG, exist_ok=True) @@ -305,6 +329,9 @@ def check_entry(name, e, authors): why = dep_error(d) if why: say(f'"{k}": {why}') + if 'key_from' in e and (not isinstance(e['key_from'], list) or not e['key_from'] + or not all(isinstance(k, str) and UUID.match(k) and k != e.get('uuid') for k in e['key_from'])): + say('"key_from" is the list of earlier author key UUIDs (lowercase), not this one') if 'hmgapi' in e and range_error(e['hmgapi']): say(f'"hmgapi": {range_error(e["hmgapi"])}') if 'wifi' in e and e['wifi'] != {'hotspot': True}: @@ -357,8 +384,15 @@ def check_base(es, au, ref): changed.add(str(e.get('uuid', '')).lower()) if old is None: continue - if str(old.get('uuid', '')).lower() != str(e.get('uuid', '')).lower(): - p.append(f'catalog/{name}.json: the author key changed ({old.get("uuid")} to {e.get("uuid")}); only the same key updates a mod') + was = str(old.get('uuid', '')).lower() + if was != str(e.get('uuid', '')).lower(): + if was in (e.get('key_from') or []): + changed.add(was) # the old key's author entry may change too + else: + p.append(f'catalog/{name}.json: the author key changed ({old.get("uuid")} to {e.get("uuid")}); only the same key ' + 'updates a mod, unless its zip hands the old key over (key-handover.json, then "key_from" names the old key)') + elif (old.get('key_from') or []) != (e.get('key_from') or []): + p.append(f'catalog/{name}.json: "key_from" changed without a key change') if vkey(str(e.get('version', ''))) < vkey(str(old.get('version', ''))): p.append(f'catalog/{name}.json: version went back ({old.get("version")} to {e.get("version")})') r = subprocess.run(['git', '-C', REPO, 'ls-tree', '--name-only', ref, 'catalog/'], capture_output=True, text=True) @@ -486,7 +520,12 @@ def download(n, e, work): man = load(os.path.join(d, 'META-HMGAPI', 'manifest.json')) if (man['id'], man['version']) != (e['id'], e['version']): return None, f'catalog/{n}.json: the download is {man["id"]} {man["version"]}, the entry says {e["id"]} {e["version"]}' - print(f'ok {n} {e["version"]}: downloaded, SHA-256 and signature match (author key {e["uuid"]})') + for k in e.get('key_from') or []: # every earlier key leads here: cars still on it follow + ok, out = handover(d, k) + if not ok: + return None, f'catalog/{n}.json: "key_from" names {k}, but {out}' + print(f'ok {n} {e["version"]}: downloaded, SHA-256 and signature match (author key {e["uuid"]}' + + (f', handed over from {", ".join(e["key_from"])}' if e.get('key_from') else '') + ')') return z, None diff --git a/tools/mkmodpkg.sh b/tools/mkmodpkg.sh index 97b6cd51..2fae6330 100755 --- a/tools/mkmodpkg.sh +++ b/tools/mkmodpkg.sh @@ -3,6 +3,8 @@ # (its build.sh first, if it has one), signed with the author's key. # tools/mkmodpkg.sh mods/ # New key: java -cp out/engine-host hmgapi.engine.Signing keygen +# Moving a mod to a new key: hmgapi.engine.Signing handover +# (docs/mod-reference.md, "Moving to a new key") # In the mod SDK (bin/mkmodpkg.sh), the mod dir is relative to where it's run, the # package goes to $OUT/packages (default ./out), and the mod is built with # bin/build-mod.sh, or taken as built from HMGAPI_MOD_BUILD (build-mod.sh's out dir).