diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index b9c169ebe..9af4bdc3c 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -126,7 +126,7 @@ jobs: env: GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} REF: ${{ needs.trigger-release.outputs.ref }} - ASSETS: 16 # what every release carries; a smaller count is still uploading + ASSETS: 17 # what every release carries; a smaller count is still uploading steps: - name: Wait for magpie-releases to publish every asset run: | diff --git a/docs/code-standards.md b/docs/code-standards.md index 68a5ac398..8fb3b2c7c 100644 --- a/docs/code-standards.md +++ b/docs/code-standards.md @@ -123,14 +123,14 @@ A release counts only when all of these hold: - A CI Test run on the tagged commit, or a later one containing it, finished green. A run cancelled by the next push is not a pass. - The tag `vX.Y.Z` is on `main`, an ancestor of `origin/main`. -- The release in `yetone/magpie-releases` has all 16 assets. +- The release in `yetone/magpie-releases` has all 17 assets. - That release is marked Latest, the highest version. Check `git tag` for the next free version first, because releases can be made from more than one place. `git fetch --tags` and check the commit isn't tagged already: on 10-12 two sessions tagged 396a6a3d4 a minute apart, and the lower v0.1.1192 became Latest. A tag is not a release: -check the release exists with its 16 assets before naming the version to +check the release exists with its 17 assets before naming the version to anyone, and file a release whose build failed instead of letting the next tag cover it. v0.1.1213 (hdiutil "Resource busy") and v0.1.1218 (notarising lost the network) were never published, and nobody noticed the first for diff --git a/docs/reference.md b/docs/reference.md index fcafa516b..b6c3196fc 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -3296,6 +3296,36 @@ downloads a new version in the background and installs it when you restart a terminal. Every release is on [yetone/magpie-releases](https://github.com/yetone/magpie-releases/releases). +### Signed releases + +usemagpie.ai's feed only carries a release; it is not what magpie trusts. From +v0.1.3862 on, release CI in `yetone/magpie-releases` signs each release's +`SHA256SUMS` with an ed25519 key and publishes the signature as +`SHA256SUMS.sig` (base64). The signed text is the line `magpie release +` followed by `SHA256SUMS`, so a signature is good for one version +only. The private key is the `UPDATE_SIGNING_KEY` secret of +`yetone/magpie-releases`, nowhere else. The public key is built into magpie +(`internal/update/signed.go`). + +The feed hands the app that `SHA256SUMS` and signature (`signed`). The app +checks the signature against its key, takes every file's SHA-256 from the +signed list, and refuses the update when the signature is missing or does not +match, or when the feed's own hash for a file differs from the signed one. +That holds for the Mac app, `magpie update`, the background update and the +Windows and Linux builds alike, so a changed feed, a mirror or a proxy can no +longer swap a file together with its hash. On the Mac the new app's signing +team is still checked too. + +Transition: a magpie that has the key refuses any release at or above +v0.1.3862 that is not signed. Releases below it were never signed, and a +magpie older than the key (it ignores `signed`) still updates by the feed's +SHA-256 as before, so nobody is cut off; the first update that lands on a +signed release is trusted that way once, and every one after it is verified. +`MAGPIE_UPDATE_FEED`, which points updates at a server of your own for +testing, lifts the requirement (a signature the server does give is still +checked). `install.sh` does not verify the signature: its first download is +trusted to the site over HTTPS and the SHA-256 the site gives. + ### Update channel magpie takes every version as it comes out unless you choose Stable, in diff --git a/internal/update/signed.go b/internal/update/signed.go new file mode 100644 index 000000000..8e4bcbf9c --- /dev/null +++ b/internal/update/signed.go @@ -0,0 +1,101 @@ +package update + +import ( + "crypto/ed25519" + "encoding/base64" + "encoding/hex" + "errors" + "fmt" + "os" + "strings" +) + +// A release's files are trusted by one signature, not by the feed's word. +// The feed (usemagpie.ai/api/latest) is only a courier: whoever can change +// its answer, the site, a proxy, a mirror, could swap a file and the hash +// beside it. Release CI signs "magpie release \n" followed by the +// release's SHA256SUMS with a private key that lives only as the +// UPDATE_SIGNING_KEY secret of yetone/magpie-releases; the feed carries the +// SHA256SUMS text and the signature (Release.Signed), and magpie checks it +// against signingKey, below, which is built into the binary. A file's hash is +// then the one the signed list gives, and a feed hash that differs is refused. +// +// Versions from firstSigned on must carry a valid signature. A build that +// holds the key is a release from firstSigned on and only moves to a newer +// one, so every update it takes is of the signed era; the older releases +// (and the first update into the signed era, taken by a binary that has no +// key yet) are checked by SHA-256 from the feed as before. + +// signingKey is the public half (base64, raw 32 bytes) of the release +// signing key. A var for tests. +var signingKey = "3XuYQEohIRDF+zxGQry1iXGZ1cfKYFX3vsST6GSSbYQ=" + +// firstSigned is the first release published with a SHA256SUMS.sig. +const firstSigned = "0.1.3862" + +// Signed is a release's SHA256SUMS as published and its ed25519 signature +// (base64). +type Signed struct { + Sums string `json:"sums"` + Sig string `json:"sig"` +} + +// signedRequired reports whether version must carry a valid signature. +// MAGPIE_UPDATE_FEED, which points updates at a server of one's own for +// testing, lifts the requirement (that server can't sign with our key); a +// signature it does give is still checked. +func signedRequired(version string) bool { + if os.Getenv("MAGPIE_UPDATE_FEED") != "" { + return false + } + return !Newer(firstSigned, version) +} + +// verify checks rel against the embedded key and, when it is signed, sets +// each asset's SHA256 to the signed list's and drops the files that list +// doesn't name. A release that must be signed and isn't, whose signature +// fails, or whose feed hash differs from the signed one is an error. +func (rel *Release) verify() error { + if rel.Signed == nil { + if signedRequired(rel.Version) { + return fmt.Errorf("release %s is not signed; not installed", rel.Version) + } + return nil + } + pub, err := base64.StdEncoding.DecodeString(signingKey) + if err != nil || len(pub) != ed25519.PublicKeySize { + return errors.New("update signing key is not valid") + } + sig, err := base64.StdEncoding.DecodeString(strings.TrimSpace(rel.Signed.Sig)) + if err != nil || len(sig) != ed25519.SignatureSize { + return fmt.Errorf("release %s: the signature is not valid; not installed", rel.Version) + } + msg := "magpie release " + rel.Version + "\n" + rel.Signed.Sums + if !ed25519.Verify(pub, []byte(msg), sig) { + return fmt.Errorf("release %s: the signature does not match; not installed", rel.Version) + } + sums := map[string]string{} + for _, line := range strings.Split(rel.Signed.Sums, "\n") { + f := strings.Fields(line) + if len(f) != 2 { + continue + } + if b, err := hex.DecodeString(f[0]); err != nil || len(b) != 32 { + continue + } + sums[strings.TrimPrefix(f[1], "*")] = strings.ToLower(f[0]) + } + for name, a := range rel.Assets { + want, ok := sums[name] + if !ok { + delete(rel.Assets, name) + continue + } + if a.SHA256 != "" && !strings.EqualFold(a.SHA256, want) { + return fmt.Errorf("release %s: the feed's checksum for %s is not the signed one; not installed", rel.Version, name) + } + a.SHA256 = want + rel.Assets[name] = a + } + return nil +} diff --git a/internal/update/signed_test.go b/internal/update/signed_test.go new file mode 100644 index 000000000..6a0499464 --- /dev/null +++ b/internal/update/signed_test.go @@ -0,0 +1,159 @@ +package update + +import ( + "context" + "crypto/ed25519" + "crypto/sha256" + "encoding/base64" + "encoding/hex" + "encoding/json" + "net/http" + "net/http/httptest" + "os" + "strings" + "testing" +) + +// signedRelease is a release of version v whose files are signed by a key +// made for the test, which becomes the embedded one. +func signedRelease(t *testing.T, v string, files map[string]string) *Release { + t.Helper() + pub, priv, _ := ed25519.GenerateKey(nil) + old := signingKey + signingKey = base64.StdEncoding.EncodeToString(pub) + t.Cleanup(func() { signingKey = old }) + t.Setenv("MAGPIE_UPDATE_FEED", "") + var sums strings.Builder + rel := &Release{Version: v, Assets: map[string]Asset{}} + for name, body := range files { + h := sha256.Sum256([]byte(body)) + sums.WriteString(hex.EncodeToString(h[:]) + " " + name + "\n") + rel.Assets[name] = Asset{URL: "https://x/" + name, SHA256: hex.EncodeToString(h[:])} + } + sig := ed25519.Sign(priv, []byte("magpie release "+v+"\n"+sums.String())) + rel.Signed = &Signed{Sums: sums.String(), Sig: base64.StdEncoding.EncodeToString(sig)} + return rel +} + +func TestSignedReleaseAccepted(t *testing.T) { + rel := signedRelease(t, "0.1.4000", map[string]string{"magpie-linux-amd64": "bin", "magpie-darwin-arm64.zip": "zip"}) + if err := rel.verify(); err != nil { + t.Fatal(err) + } + if len(rel.Assets) != 2 { + t.Fatalf("assets %v", rel.Assets) + } +} + +// A hash the feed gives for itself is replaced by the signed one, and a +// file the signed list doesn't name is dropped. +func TestSignedListGivesTheHash(t *testing.T) { + rel := signedRelease(t, "0.1.4000", map[string]string{"a": "1"}) + a := rel.Assets["a"] + a.SHA256 = "" + rel.Assets["a"] = a + rel.Assets["extra"] = Asset{URL: "https://evil/extra", SHA256: "00"} + if err := rel.verify(); err != nil { + t.Fatal(err) + } + h := sha256.Sum256([]byte("1")) + if rel.Assets["a"].SHA256 != hex.EncodeToString(h[:]) { + t.Fatalf("hash %q", rel.Assets["a"].SHA256) + } + if _, ok := rel.Assets["extra"]; ok { + t.Fatal("an unsigned file stayed") + } +} + +func TestTamperedReleaseRefused(t *testing.T) { + cases := map[string]func(*Release){ + "feed hash swapped": func(r *Release) { + a := r.Assets["a"] + a.SHA256 = strings.Repeat("ab", 32) + r.Assets["a"] = a + }, + "signed list swapped": func(r *Release) { + r.Signed.Sums = strings.Repeat("ab", 32) + " a\n" + }, + "signature flipped": func(r *Release) { + b, _ := base64.StdEncoding.DecodeString(r.Signed.Sig) + b[0] ^= 1 + r.Signed.Sig = base64.StdEncoding.EncodeToString(b) + }, + "signature garbage": func(r *Release) { r.Signed.Sig = "zz" }, + "other version": func(r *Release) { r.Version = "0.1.4001" }, + "signature dropped": func(r *Release) { r.Signed = nil }, + } + for name, tamper := range cases { + t.Run(name, func(t *testing.T) { + rel := signedRelease(t, "0.1.4000", map[string]string{"a": "1"}) + tamper(rel) + if err := rel.verify(); err == nil { + t.Fatal("accepted") + } + }) + } +} + +// Another key's signature is no signature. +func TestSignedByOtherKeyRefused(t *testing.T) { + rel := signedRelease(t, "0.1.4000", map[string]string{"a": "1"}) + pub, _, _ := ed25519.GenerateKey(nil) + signingKey = base64.StdEncoding.EncodeToString(pub) + if rel.verify() == nil { + t.Fatal("accepted") + } +} + +// Before the first signed release, no signature is asked for; a bad one +// there is still refused. +func TestUnsignedEraNeedsNoSignature(t *testing.T) { + t.Setenv("MAGPIE_UPDATE_FEED", "") + old := &Release{Version: "0.1.3000", Assets: map[string]Asset{"a": {SHA256: "ab"}}} + if err := old.verify(); err != nil { + t.Fatal(err) + } + if old.Assets["a"].SHA256 != "ab" { + t.Fatal("hash changed") + } + first := &Release{Version: firstSigned} + if first.verify() == nil { + t.Fatal("the first signed release passed unsigned") + } + if (&Release{Version: "0.2.0"}).verify() == nil { + t.Fatal("a later release passed unsigned") + } +} + +// The embedded key is the one release CI signs with: a sample signed by +// the private key (UPDATE_SIGNING_KEY) with openssl, as the workflow does. +func TestEmbeddedKeyVerifiesCIsSignature(t *testing.T) { + pub, _ := base64.StdEncoding.DecodeString(signingKey) + msg, err := os.ReadFile("testdata/signed-sample.msg") + if err != nil { + t.Fatal(err) + } + b, _ := os.ReadFile("testdata/signed-sample.sig") + sig, _ := base64.StdEncoding.DecodeString(strings.TrimSpace(string(b))) + if !ed25519.Verify(pub, msg, sig) { + t.Fatal("the embedded key does not verify CI's signature") + } +} + +// The feed path end to end: a tampered answer is an error, a signed one a release. +func TestLatestVerifiesTheFeed(t *testing.T) { + rel := signedRelease(t, "0.1.4000", map[string]string{"a": "1"}) + serve := func(r *Release) string { + s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { json.NewEncoder(w).Encode(r) })) + t.Cleanup(s.Close) + return s.URL + } + if _, err := latestAt(context.Background(), serve(rel), ""); err != nil { + t.Fatal(err) + } + bad := *rel + bad.Assets = map[string]Asset{"a": {URL: "https://evil/a", SHA256: strings.Repeat("cd", 32)}} + if _, err := latestAt(context.Background(), serve(&bad), ""); err == nil { + t.Fatal("a swapped hash was taken") + } +} diff --git a/internal/update/testdata/signed-sample.msg b/internal/update/testdata/signed-sample.msg new file mode 100644 index 000000000..0f04d97a2 --- /dev/null +++ b/internal/update/testdata/signed-sample.msg @@ -0,0 +1,2 @@ +magpie release 0.0.1-sample +abc file diff --git a/internal/update/testdata/signed-sample.sig b/internal/update/testdata/signed-sample.sig new file mode 100644 index 000000000..ab211c72d --- /dev/null +++ b/internal/update/testdata/signed-sample.sig @@ -0,0 +1 @@ +OT7nCVnsnONdQsBC4rfHcpqouwWLfavkbv3FCdPOBjGTBdHTefDVHQdZe8w1T5nOwlvA/S5a2EiI9zC9yOOcBQ== diff --git a/internal/update/update.go b/internal/update/update.go index 30594ccdb..0dbd2269a 100644 --- a/internal/update/update.go +++ b/internal/update/update.go @@ -58,6 +58,8 @@ type Release struct { Notes string `json:"notes"` // markdown URL string `json:"url"` // the release page Assets map[string]Asset `json:"assets"` // by file name + // Signed is what vouches for Assets' hashes (signed.go). + Signed *Signed `json:"signed,omitempty"` } // Asset is one downloadable file of a release. @@ -158,6 +160,9 @@ func latestAt(ctx context.Context, feed, lang string) (*Release, error) { if parse(r.Version) == nil { return nil, fmt.Errorf("update feed: no version") } + if err := r.verify(); err != nil { + return nil, fmt.Errorf("update feed: %w", err) + } r.Notes = InLang(r.Notes, lang) return &r, nil } diff --git a/site/worker.js b/site/worker.js index 42067e9dc..6e72acd0e 100644 --- a/site/worker.js +++ b/site/worker.js @@ -547,11 +547,13 @@ async function fromAPI(env, path = "releases/latest") { const gh = await res.json(); const tag = gh.tag_name; const listed = gh.assets.find((a) => a.name === "SHA256SUMS"); - const got = await checksums(tag, env, listed && listed.url); + const listedSig = gh.assets.find((a) => a.name === SIG); + const got = await checksums(tag, env, listed && listed.url, listedSig && listedSig.url); if (!got) return null; const rel = { version: tag.replace(/^v/, ""), notes: gh.body || "", url: gh.html_url, published: gh.published_at, assets: {} }; + if (got.signed) rel.signed = got.signed; for (const a of gh.assets) { - if (a.name === "SHA256SUMS") continue; + if (a.name === "SHA256SUMS" || a.name === SIG) continue; // api: the file's address in GitHub's API, which an app asks when // url is busy. With github.com's download address failing (504 for // hours on 2026-11-08), url is the site's /dl, which redirects @@ -650,6 +652,7 @@ async function fromSums(tag, entry) { const sums = got.sums; const url = `https://github.com/${REPO}/releases/tag/${tag}`; const rel = { version: tag.replace(/^v/, ""), notes: entry ? entry.notes : "", url, published: entry ? entry.published : null, assets: {} }; + if (got.signed) rel.signed = got.signed; for (const [name, sha256] of Object.entries(sums)) { rel.assets[name] = { url: `https://github.com/${REPO}/releases/download/${tag}/${name}`, size: 0, sha256 }; } @@ -1045,10 +1048,18 @@ function newer(a, b) { return x.pre > y.pre; } +// SIG is the signature of SHA256SUMS, a release asset (see signed below). +const SIG = "SHA256SUMS.sig"; + // checksums reads a release's SHA256SUMS: {sums: {file name: hash}, -// direct}, or null. direct says github.com's download address gave it; -// when that fails, viaAPI (the file's address in GitHub's API) is asked. -async function checksums(tag, env, viaAPI) { +// direct, signed}, or null. direct says github.com's download address gave +// it; when that fails, viaAPI (the file's address in GitHub's API) is asked. +// signed is {sums, sig}: SHA256SUMS as published and its ed25519 signature +// (base64, the release's SHA256SUMS.sig, viaAPISig in the API), or absent +// for a release with none. The site only carries them; the app checks the +// signature against the key it holds, so nothing here is trusted, this +// worker included. +async function checksums(tag, env, viaAPI, viaAPISig) { let r = null; try { r = await fetch(`https://github.com/${REPO}/releases/download/${tag}/SHA256SUMS`, { headers: UA }); @@ -1068,12 +1079,42 @@ async function checksums(tag, env, viaAPI) { } if (!r.ok) return null; } + const text = await r.text(); const sums = {}; - for (const line of (await r.text()).split("\n")) { + for (const line of text.split("\n")) { const [hash, name] = line.trim().split(/\s+\*?/); if (hash && name) sums[name] = hash; } - return { sums, direct }; + const out = { sums, direct }; + const sig = await signature(tag, env, direct, viaAPISig); + if (sig) out.signed = { sums: text, sig }; + return out; +} + +// signature is the release's SHA256SUMS.sig as the base64 line it holds, or +// "" when the release has none (every release before it was signed). +async function signature(tag, env, direct, viaAPI) { + let r = null; + if (direct) { + try { + r = await fetch(`https://github.com/${REPO}/releases/download/${tag}/${SIG}`, { headers: UA }); + } catch (e) { + console.log(SIG, e); + } + } + if (!r || !r.ok) { + const to = viaAPI && (await located(viaAPI, env)); + if (!to) return ""; + try { + r = await fetch(to, { headers: UA }); + } catch (e) { + console.log(SIG, "through the API", e); + return ""; + } + } + if (!r.ok) return ""; + const t = (await r.text()).trim(); + return /^[A-Za-z0-9+/=]{80,100}$/.test(t) ? t : ""; } // ---- icons ------------------------------------------------------------------ diff --git a/site/worker.test.mjs b/site/worker.test.mjs index 77032d2ba..1eba88d34 100644 --- a/site/worker.test.mjs +++ b/site/worker.test.mjs @@ -28,6 +28,7 @@ let apiDown = false, pagesDown = false; // API serves the same files (2026-11-08) let downloadsDown = false; const seen = []; +const SIG64 = "OT7nCVnsnONdQsBC4rfHcpqouwWLfavkbv3FCdPOBjGTBdHTefDVHQdZe8w1T5nOwlvA/S5a2EiI9zC9yOOcBQ=="; const FEED = ` @@ -87,11 +88,13 @@ globalThis.fetch = async (u, init = {}) => { const gh = (tag) => ({ tag_name: tag, body: BODIES[tag], html_url: "https://github.com/r/" + tag, published_at: "2026-10-01T00:00:00Z", draft: false, prerelease: false, assets: [ { name: "magpie-linux-amd64", size: 1, browser_download_url: "https://dl/x", url: "https://api.github.com/repos/yetone/magpie-releases/releases/assets/1" }, { name: "SHA256SUMS", size: 1, browser_download_url: "https://dl/sums", url: "https://api.github.com/repos/yetone/magpie-releases/releases/assets/2" }, + { name: "SHA256SUMS.sig", size: 88, browser_download_url: "https://dl/sig", url: "https://api.github.com/repos/yetone/magpie-releases/releases/assets/3" }, ] }); if (u.endsWith("/releases/tags/v0.1.3")) return Response.json(gh("v0.1.3")); if (u.endsWith("/releases/latest")) return Response.json(gh("v0.1.3")); if (u.includes("/releases?per_page=")) return Response.json(Object.keys(BODIES).map(gh)); if (u.endsWith("/SHA256SUMS")) return new Response("abc magpie-linux-amd64\n"); + if (u.endsWith("/SHA256SUMS.sig")) return new Response(SIG64 + "\n"); return new Response("not found", { status: 404 }); }; @@ -116,6 +119,15 @@ test("latest: the English alone without lang, the Chinese with zh", async () => assert.equal((await get("/api/latest")).body.notes, EN); }); +// The app checks the signature itself (internal/update/signed.go); the feed +// only carries the signed list and the signature, and never lists the +// signature as a file to download. +test("latest: carries SHA256SUMS and its signature, and the signature is no file", async () => { + const { body } = await get("/api/latest"); + assert.deepEqual(body.signed, { sums: "abc magpie-linux-amd64\n", sig: SIG64 }); + assert.deepEqual(Object.keys(body.assets), ["magpie-linux-amd64"]); +}); + test("notes: each release in the language, English where it has no Chinese", async () => { const zh = (await get("/api/notes?after=0.1.1&upto=0.1.3&lang=zh")).body.releases; assert.deepEqual(zh.map((r) => [r.version, r.notes]), [["0.1.3", ZH], ["0.1.2", BODIES["v0.1.2"]]]);