Commit 9fcc512f24 for golang

commit 9fcc512f24a34669702c9fc592d9bc438a30e1ca
Author: Nicholas S. Husin <nsh@golang.org>
Date:   Mon Nov 30 17:41:43 2026 -0500

    cmd/go: require ML-DSA signature alongside Ed25519 for sum.golang.org

    Add the ML-DSA-44 verifier key for sum.golang.org alongside the existing
    Ed25519 key.

    When verifying lookups against sum.golang.org, cmd/go now runs two
    independent sumdb.Client instances: one for the ML-DSA-44 key and one
    for the Ed25519 key. We consider a SumDB record to be valid only if both
    clients verify signatures successfully.

    A user might upgrade their toolchain (which contains a new key) while
    having old cached SumDB responses that do not contain the signature
    corresponding to the new key. To support seamless transition, missing
    signatures for newer keys in cached SumDB responses is not treated as a
    hard failure, and will instead prompt reverification using a fresh SumDB
    response.

    Fixes #83639

    Change-Id: I48a2adea6cc31fa7d49f8820067d0bce6a6a6964
    Reviewed-on: https://go-review.googlesource.com/c/go/+/869785
    Reviewed-by: Michael Matloob <matloob@golang.org>
    Reviewed-by: Michael Matloob <matloob@google.com>
    LUCI-TryBot-Result: golang-scoped@luci-project-accounts.iam.gserviceaccount.com <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
    Reviewed-by: Nicholas Husin <husin@google.com>
    Reviewed-by: Damien Neil <dneil@google.com>
    Reviewed-by: Neal Patel <neal@golang.org>
    Reviewed-by: Neal Patel <nealpatel@google.com>
    Reviewed-by: Hyang-Ah Hana Kim <hyangah@gmail.com>

diff --git a/src/cmd/go/internal/modfetch/coderepo_test.go b/src/cmd/go/internal/modfetch/coderepo_test.go
index 04a821df09..09976732bb 100644
--- a/src/cmd/go/internal/modfetch/coderepo_test.go
+++ b/src/cmd/go/internal/modfetch/coderepo_test.go
@@ -58,6 +58,7 @@ func testMain(m *testing.M) (err error) {
 	if err := os.Mkdir(cfg.GOMODCACHE, 0o755); err != nil {
 		return err
 	}
+	cfg.SumdbDir = filepath.Join(dir, "sumdb")

 	srv, err := vcstest.NewServer()
 	if err != nil {
diff --git a/src/cmd/go/internal/modfetch/fetch_test.go b/src/cmd/go/internal/modfetch/fetch_test.go
index 4a941510e5..b3fb7b31df 100644
--- a/src/cmd/go/internal/modfetch/fetch_test.go
+++ b/src/cmd/go/internal/modfetch/fetch_test.go
@@ -7,14 +7,34 @@
 package modfetch

 import (
+	"bytes"
+	"context"
+	"crypto/fips140"
+	"crypto/mldsa"
+	"crypto/rand"
+	"crypto/sha256"
+	"encoding/base64"
+	"encoding/binary"
 	"errors"
+	"fmt"
+	"internal/testenv"
 	"io/fs"
+	"net/http"
+	"net/http/httptest"
 	"os"
 	"path/filepath"
+	"strings"
+	"sync"
+	"sync/atomic"
 	"testing"

+	"cmd/go/internal/cfg"
+
 	"golang.org/x/mod/module"
+	"golang.org/x/mod/sumdb"
 	"golang.org/x/mod/sumdb/dirhash"
+	"golang.org/x/mod/sumdb/note"
+	"golang.org/x/mod/sumdb/tlog"
 	modzip "golang.org/x/mod/zip"
 )

@@ -99,3 +119,382 @@ func TestUnzipVerify(t *testing.T) {
 		t.Errorf("haveZipHash after re-unpack: got (%v, %v), want (true, nil)", ok, err)
 	}
 }
+
+func TestKnownGOSUMDB(t *testing.T) {
+	for host, keys := range knownGOSUMDB {
+		if len(keys) == 0 {
+			t.Errorf("knownGOSUMDB[%q] has no keys", host)
+		}
+		for i, vkey := range keys {
+			v, err := note.NewVerifier(vkey)
+			if err != nil {
+				t.Errorf("knownGOSUMDB[%q][%d]: note.NewVerifier failed: %v", host, i, err)
+				continue
+			}
+			if v.Name() != host {
+				t.Errorf("knownGOSUMDB[%q][%d] name = %q, want %q", host, i, v.Name(), host)
+			}
+		}
+	}
+}
+
+// multiSignServer wraps sumdb.TestServer to sign tree heads with a
+// configurable list of note signers. Changing sumdb.TestServer requires a
+// proposal, so we do this for now.
+// TODO: support multiple signers in sumdb.TestServer.
+type multiSignServer struct {
+	*sumdb.TestServer
+	url      string
+	requests atomic.Int64
+
+	mu      sync.Mutex
+	signers []note.Signer
+}
+
+func (s *multiSignServer) Signed(ctx context.Context) ([]byte, error) {
+	msg, err := s.TestServer.Signed(ctx)
+	if err != nil {
+		return nil, err
+	}
+	text, _, _ := bytes.Cut(msg, []byte("\n\n"))
+	s.mu.Lock()
+	defer s.mu.Unlock()
+	return note.Sign(&note.Note{Text: string(text) + "\n"}, s.signers...)
+}
+
+func (s *multiSignServer) setSigners(signers ...note.Signer) {
+	s.mu.Lock()
+	defer s.mu.Unlock()
+	s.signers = signers
+}
+
+// mustMLDSA44TestKey generates an ML-DSA-44 note signer/verifier key pair
+// (note.GenerateKey only supports Ed25519).
+func mustMLDSA44TestKey(t *testing.T, name string) (skey, vkey string) {
+	t.Helper()
+	const algMLDSA44 = 6
+	priv, err := mldsa.GenerateKey(mldsa.MLDSA44())
+	if err != nil {
+		t.Fatal(err)
+	}
+	pub := append([]byte{algMLDSA44}, priv.PublicKey().Bytes()...)
+	seed := append([]byte{algMLDSA44}, priv.Bytes()...)
+	h := sha256.New()
+	fmt.Fprintf(h, "%s\n", name)
+	h.Write(pub)
+	hash := binary.BigEndian.Uint32(h.Sum(nil))
+	skey = fmt.Sprintf("PRIVATE+KEY+%s+%08x+%s", name, hash, base64.StdEncoding.EncodeToString(seed))
+	vkey = fmt.Sprintf("%s+%08x+%s", name, hash, base64.StdEncoding.EncodeToString(pub))
+	return skey, vkey
+}
+
+func TestSumDBKeyTransition(t *testing.T) {
+	if strings.HasPrefix(fips140.Version(), "v1.0.") {
+		t.Skipf("ML-DSA-44 is unavailable for GOFIPS140=%s", fips140.Version())
+	}
+	const name = "sum.example.com"
+	mustKeyPair := func(skey, vkey string) (note.Signer, note.Verifier) {
+		t.Helper()
+		s, err := note.NewSigner(skey)
+		if err != nil {
+			t.Fatal(err)
+		}
+		v, err := note.NewVerifier(vkey)
+		if err != nil {
+			t.Fatal(err)
+		}
+		return s, v
+	}
+	edSKey, edVKey, err := note.GenerateKey(rand.Reader, name)
+	if err != nil {
+		t.Fatal(err)
+	}
+	edSigner, edVerifier := mustKeyPair(edSKey, edVKey)
+	mlSKey, mlVKey := mustMLDSA44TestKey(t, name)
+	mlSigner, mlVerifier := mustKeyPair(mlSKey, mlVKey)
+
+	edKeys := []string{edVKey}
+	hybridKeys := []string{mlVKey, edVKey}
+	bothVerifiers := note.VerifierList(edVerifier, mlVerifier)
+
+	modA := module.Version{Path: "example.com/a", Version: "v1.0.0"}
+	modB := module.Version{Path: "example.com/b", Version: "v1.0.0"}
+	records := map[module.Version]string{
+		modA: "example.com/a v1.0.0 h1:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa=\nexample.com/a v1.0.0/go.mod h1:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb=\n",
+		modB: "example.com/b v1.0.0 h1:ccccccccccccccccccccccccccccccccccccccccccc=\nexample.com/b v1.0.0/go.mod h1:ddddddddddddddddddddddddddddddddddddddddddd=\n",
+	}
+
+	prevGOSUMDB := cfg.GOSUMDB
+	t.Cleanup(func() {
+		delete(knownGOSUMDB, name)
+		cfg.GOSUMDB = prevGOSUMDB
+		dbOnce = sync.Once{}
+	})
+
+	// cfg.SumdbDir and cfg.GOMODCACHE are temp dirs set by TestMain.
+	var (
+		latestPath = filepath.Join(cfg.SumdbDir, name, "latest")
+		cacheDir   = filepath.Join(cfg.GOMODCACHE, "cache/download/sumdb", name)
+	)
+	// clearCache makes the go command forget everything about the database.
+	clearCache := func(t *testing.T) {
+		t.Helper()
+		for _, dir := range []string{filepath.Dir(latestPath), cacheDir} {
+			if err := os.RemoveAll(dir); err != nil {
+				t.Fatal(err)
+			}
+		}
+	}
+	newServer := func(t *testing.T, recs map[module.Version]string, signers ...note.Signer) *multiSignServer {
+		t.Helper()
+		ops := &multiSignServer{
+			TestServer: sumdb.NewTestServer(edSKey, func(path, vers string) ([]byte, error) {
+				rec, ok := recs[module.Version{Path: path, Version: vers}]
+				if !ok {
+					return nil, fs.ErrNotExist
+				}
+				return []byte(rec), nil
+			}),
+			signers: signers,
+		}
+		h := sumdb.NewServer(ops)
+		srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+			ops.requests.Add(1)
+			h.ServeHTTP(w, r)
+		}))
+		t.Cleanup(srv.Close)
+		ops.url = srv.URL
+		return ops
+	}
+	// lookup looks up mod like a new go command whose knownGOSUMDB entry for
+	// the test database is keys. We need to use knownGOSUMDB since support for
+	// multiple keys is only available to knownGOSUMDB currently.
+	lookup := func(srv *multiSignServer, keys []string, mod module.Version) (string, []string, error) {
+		knownGOSUMDB[name] = keys
+		cfg.GOSUMDB = name + " " + srv.url
+		dbOnce = sync.Once{}
+		return lookupSumDB(mod)
+	}
+	mustLookup := func(t *testing.T, srv *multiSignServer, keys []string, mod module.Version) {
+		t.Helper()
+		if _, _, err := lookup(srv, keys, mod); err != nil {
+			t.Fatalf("lookupSumDB(%v) = %v, want nil", mod, err)
+		}
+	}
+	verifyDualSigned := func(t *testing.T, msg []byte) {
+		t.Helper()
+		n, err := note.Open(msg, bothVerifiers)
+		if err != nil {
+			t.Fatalf("note.Open: %v", err)
+		}
+		if len(n.Sigs) != 2 {
+			t.Errorf("verified %d signatures, want 2", len(n.Sigs))
+		}
+	}
+
+	t.Run("fresh_lookup", func(t *testing.T) {
+		clearCache(t)
+		srv := newServer(t, records, edSigner, mlSigner)
+
+		dbname, lines, err := lookup(srv, hybridKeys, modA)
+		if err != nil {
+			t.Fatalf("lookupSumDB(%v) = %v, want nil", modA, err)
+		}
+		if dbname != name {
+			t.Fatalf("dbname = %q, want %q", dbname, name)
+		}
+		if len(lines) != 1 || !strings.HasPrefix(lines[0], "example.com/a v1.0.0 h1:") {
+			t.Fatalf("lines = %v, want example.com/a hash", lines)
+		}
+		// Nothing is cached, so the record has to come from the server:
+		// one /lookup/ and one /tile/ request in total, not one of each
+		// per key.
+		if got := srv.requests.Swap(0); got != 2 {
+			t.Errorf("remote requests = %d, want 2", got)
+		}
+		latestData, err := os.ReadFile(latestPath)
+		if err != nil {
+			t.Fatal(err)
+		}
+		verifyDualSigned(t, latestData)
+
+		// A second go command finds the dual-signed record in its cache
+		// and does not ask the server again.
+		mustLookup(t, srv, hybridKeys, modA)
+		if got := srv.requests.Swap(0); got != 0 {
+			t.Errorf("remote requests on cache hit = %d, want 0", got)
+		}
+	})
+
+	t.Run("reject_incomplete_remote", func(t *testing.T) {
+		for _, tc := range []struct {
+			name      string
+			signers   []note.Signer
+			failedKey note.Verifier
+		}{
+			{"ed25519_only", []note.Signer{edSigner}, mlVerifier},
+			{"mldsa_only", []note.Signer{mlSigner}, edVerifier},
+		} {
+			t.Run(tc.name, func(t *testing.T) {
+				clearCache(t)
+				srv := newServer(t, records, tc.signers...)
+				wantKey := fmt.Sprintf("using key %s+%08x", tc.failedKey.Name(), tc.failedKey.KeyHash())
+				if _, _, err := lookup(srv, hybridKeys, modA); err == nil || !strings.Contains(err.Error(), wantKey) || !strings.Contains(err.Error(), "reading tree note") {
+					t.Fatalf("lookupSumDB(%v) = %v, want error mentioning %q and reading tree note", modA, err, wantKey)
+				}
+
+				// Neither /lookup/, /tile/, nor /latest should be persisted on failure.
+				if _, err := os.Stat(cacheDir); !errors.Is(err, fs.ErrNotExist) {
+					t.Errorf("modcache dir exists after failure (err=%v), want not exist", err)
+				}
+				if _, err := os.Stat(latestPath); !errors.Is(err, fs.ErrNotExist) {
+					t.Errorf("/latest exists after failure (err=%v), want not exist", err)
+				}
+
+				// Recover cleanly once the server serves dual-signed responses.
+				srv.setSigners(edSigner, mlSigner)
+				mustLookup(t, srv, hybridKeys, modA)
+			})
+		}
+	})
+
+	t.Run("upgrade_legacy_latest", func(t *testing.T) {
+		clearCache(t)
+		srv := newServer(t, records, edSigner)
+
+		// Seed an Ed25519-only /latest (N=1) via an older toolchain.
+		mustLookup(t, srv, edKeys, modA)
+
+		// A newer toolchain has no record for modB, so it asks the server
+		// (one /lookup/ and one /tile/). It checks the answer against the
+		// legacy /latest and then saves a dual-signed /latest.
+		srv.setSigners(edSigner, mlSigner)
+		srv.requests.Store(0)
+		mustLookup(t, srv, hybridKeys, modB)
+		if got := srv.requests.Swap(0); got != 2 {
+			t.Errorf("remote requests on upgrade = %d, want 2", got)
+		}
+		latestData, err := os.ReadFile(latestPath)
+		if err != nil {
+			t.Fatal(err)
+		}
+		verifyDualSigned(t, latestData)
+
+		// An older toolchain can still use the upgraded /latest and the
+		// cached record, so it does not ask the server.
+		mustLookup(t, srv, edKeys, modB)
+		if got := srv.requests.Swap(0); got != 0 {
+			t.Errorf("remote requests from older toolchain = %d, want 0", got)
+		}
+	})
+
+	t.Run("refresh_legacy_cached_lookup", func(t *testing.T) {
+		clearCache(t)
+		srv := newServer(t, records, edSigner)
+		mustLookup(t, srv, edKeys, modA)
+
+		// The cached /lookup/ has no ML-DSA signature, so a newer toolchain
+		// must not trust it: it fetches the record again (one /lookup/, the
+		// cached tile is reused) and saves the dual-signed response.
+		srv.setSigners(edSigner, mlSigner)
+		srv.requests.Store(0)
+		mustLookup(t, srv, hybridKeys, modA)
+		if got := srv.requests.Swap(0); got != 1 {
+			t.Errorf("remote requests on stale cache refresh = %d, want 1", got)
+		}
+		updated, err := os.ReadFile(filepath.Join(cacheDir, "lookup/example.com/a@v1.0.0"))
+		if err != nil {
+			t.Fatal(err)
+		}
+		_, _, treeMsg, err := tlog.ParseRecord(updated)
+		if err != nil {
+			t.Fatal(err)
+		}
+		verifyDualSigned(t, treeMsg)
+
+		// The next go command finds the dual-signed record in its cache
+		// and does not ask the server again.
+		mustLookup(t, srv, hybridKeys, modA)
+		if got := srv.requests.Swap(0); got != 0 {
+			t.Errorf("remote requests on cache hit = %d, want 0", got)
+		}
+	})
+
+	t.Run("detect_forked_latest", func(t *testing.T) {
+		forkedRecords := map[module.Version]string{
+			modA: "example.com/a v1.0.0 h1:zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz=\n",
+		}
+		for _, tc := range []struct {
+			name        string
+			seedSigners []note.Signer
+			seedKeys    []string
+		}{
+			{"legacy_ed25519", []note.Signer{edSigner}, edKeys},
+			{"dual_signed", []note.Signer{edSigner, mlSigner}, hybridKeys},
+		} {
+			t.Run(tc.name, func(t *testing.T) {
+				if os.Getenv("GO_TEST_SUMDB_FORK") == "" {
+					// The go command exits the process when it detects a
+					// fork, so the case below runs in a child: this test
+					// binary, re-run for just this case with
+					// GO_TEST_SUMDB_FORK=1. Here in the parent we only check
+					// that the child exits with SECURITY ERROR. The child
+					// exits without cleaning up, so give it its own temp dir.
+					tmp := t.TempDir()
+					cmd := testenv.Command(t, testenv.Executable(t), "-test.run=^"+t.Name()+"$")
+					cmd.Env = append(cmd.Environ(), "GO_TEST_SUMDB_FORK=1", "TMPDIR="+tmp, "TMP="+tmp)
+					if out, err := cmd.CombinedOutput(); err == nil || !bytes.Contains(out, []byte("SECURITY ERROR")) {
+						t.Fatalf("lookup after fork: err = %v, want exit with SECURITY ERROR\n%s", err, out)
+					}
+					return
+				}
+				clearCache(t)
+
+				// Seed a forked /latest (N=1, wrong hash for modA).
+				forked := newServer(t, forkedRecords, tc.seedSigners...)
+				mustLookup(t, forked, tc.seedKeys, modA)
+
+				// The honest server has a different record for modA, so its
+				// tree does not extend the forked /latest.
+				honest := newServer(t, records, edSigner, mlSigner)
+				if _, err := honest.Lookup(t.Context(), modA); err != nil {
+					t.Fatal(err)
+				}
+
+				// The go command must exit here with SECURITY ERROR, which
+				// the parent checks for. If this returned, the child would
+				// pass and the parent would fail.
+				lookup(honest, hybridKeys, modB)
+			})
+		}
+	})
+
+	t.Run("corrupted_latest", func(t *testing.T) {
+		clearCache(t)
+		srv := newServer(t, records, edSigner, mlSigner)
+
+		if err := os.MkdirAll(filepath.Dir(latestPath), 0o777); err != nil {
+			t.Fatal(err)
+		}
+		const corrupt = "not a valid signed tree head\n"
+		if err := os.WriteFile(latestPath, []byte(corrupt), 0o666); err != nil {
+			t.Fatal(err)
+		}
+
+		// The go command must fail on the unreadable /latest without hitting
+		// the server and must not overwrite it.
+		if _, _, err := lookup(srv, hybridKeys, modA); err == nil || !strings.Contains(err.Error(), "reading tree note") {
+			t.Fatalf("lookupSumDB(%v) = %v, want note verification error", modA, err)
+		}
+		if got := srv.requests.Load(); got != 0 {
+			t.Errorf("remote requests = %d, want 0", got)
+		}
+		got, err := os.ReadFile(latestPath)
+		if err != nil {
+			t.Fatal(err)
+		}
+		if string(got) != corrupt {
+			t.Errorf("corrupted /latest was overwritten: got %q, want %q", got, corrupt)
+		}
+	})
+}
diff --git a/src/cmd/go/internal/modfetch/key.go b/src/cmd/go/internal/modfetch/key.go
index 06f9989b9d..0b8da2d382 100644
--- a/src/cmd/go/internal/modfetch/key.go
+++ b/src/cmd/go/internal/modfetch/key.go
@@ -2,8 +2,82 @@
 // Use of this source code is governed by a BSD-style
 // license that can be found in the LICENSE file.

+//go:build !cmd_go_bootstrap
+
 package modfetch

-var knownGOSUMDB = map[string]string{
-	"sum.golang.org": "sum.golang.org+033de0ae+Ac4zctda0e5eza+HJyk9SxEdh+s3Ux18htTTAD8OuAn8",
+import (
+	"crypto/fips140"
+	"strings"
+)
+
+// knownGOSUMDB maps known checksum database names to their verifier keys. Each
+// key in the slice performs independent sequential verification of every
+// lookup. If any verification by a single key fails, subsequent verifications
+// are not done, and we consider the whole process a failure.
+//
+// The order of keys in the slice matters: newer keys must be at the front of
+// the slice, while older keys must be at the end of the slice.
+//
+// When verifying the checksum of a module, the Go toolchain queries SumDB's
+// /lookup/ endpoint and verifies the signatures in the response using the keys
+// it has. Assuming that the signature is valid, it will cache the /lookup/
+// response on-disk. If the signed tree head in the /lookup/ response is also
+// the highest it has seen, the tree head will additionally be cached as a
+// /latest file.
+//
+// When future module checksum verification occurs, these caches come into
+// play. The toolchain always verifies the signature that is already in the
+// cache, which can avoid extraneous SumDB queries in some cases. On receiving
+// a response from SumDB, the toolchain also looks at its existing /latest
+// cache to ensure that the tree is still consistent and has not diverged from
+// the last time a module checksum verification occurred.
+//
+// This caching behavior introduces an edge case: a user might update their Go
+// toolchain to a newer version which includes a new key, but has stale
+// /lookup/ and /latest caches that do not yet include the signature
+// corresponding to the new key. To handle this, we must do our sequential
+// verification from the newest key to the oldest key, and treat them slightly
+// differently.
+//
+// For signature verification of cached /lookup/ and /latest, the oldest key
+// must treat failure as a hard failure. However, any other key treats a
+// missing signature as a cache miss (since it might just be a stale cache
+// written by an older toolchain): starting with an empty /latest, or doing a
+// fresh /lookup/ against the SumDB.
+//
+// Similarly, updating the on-disk caches (/latest, /lookup/, and /tile/) must
+// be left to the oldest key, after it has finished verifying the signature of
+// the cached /latest and the consistency of the cached tree against the newly
+// fetched tree. For /lookup/ and /tile/, newer keys pass freshly fetched
+// responses in memory so we do not write unverified responses to disk before
+// all keys have verified them, while still avoiding duplicate HTTP calls.
+//
+// This is unfortunately somewhat convoluted, but doing this gives us the
+// following desired properties:
+//   - We only accept SumDB records that contain signatures for ALL keys.
+//   - When a user has a cached /latest that does not contain the newest key, we
+//     do not have to throw it out and skip the tree consistency check in trying
+//     to transition to additionally use the newest key.
+//   - The addition of new keys does not require users to clean their mod cache
+//     and manually delete their cached /latest files (which is not cleared by
+//     "go clean -modcache").
+//
+// This setup would also work reasonably well if we ever decide to start
+// rotating our keys at some point in the future.
+var knownGOSUMDB = map[string][]string{
+	"sum.golang.org": {
+		// ML-DSA-44 key, required alongside Ed25519 for post-quantum security.
+		// In use since Go 1.28, and backported to Go 1.27.5 and Go 1.26.12.
+		"sum.golang.org+c987407f+BjyK38Wvx91l/CPqPVRHgDgf+rabx7zGT36P7NdCmNXM6+rCZk6v9WdNxHntHWHwZAB5lDBTv3uxgOl8mpeDbKX/VXY991yo62slcnoNhfjIR6gT5oxK2KxOwZMDeLPhvh+G0Ny8ehSKrRvZYZ2XNZUvEUmN/jU++vV+/Ts035az2yRTt4s0Io1LKK+tvfQ22T6734wPEDrV1ZcPwQv9kADPjQn/FxUowpn3OMdmQP0IG0rfhZEXCoG84/xd0ayEOl8nldLxfLsPxXbN2QbRKRiDj4A44F+BuaoxAd8WHtt51U7ilFG5QMn23Vgmx2DBnG47TWo2RRCdpWax88SQEmMYJHP1t7n7ktqBNWstR3G90hYoVYuX9cxOcjy+p2aUHTtCAvQ+MKGJX3q5eOnHipOfI7sLCI8IC3QeTwVld5nXqXe/6OH+txkT1OASnZuHQHI81J8HresXzyszoINLcRDPFRUpan9Q1hZFpn0luDhA1x2jmby5Y7Gl7wHM/xACBy3GRI2XRwJQhnaEOLJS6cuAp4SYyjyK835rlHMqfJOx6qm/Qy2TBhaDiyS9r+JH3nKb+xVVn6rGL+38XN7uNVPnjQMKcwv3d5uNuRtuozRUTeEQ1DvVJn18iT6tq8pae6CIQCbu2aIinDD5WaKylu7hy4DZDzZEhZwzzliTsNL2tIdApwTwF/k2D6/Q1KvV/xdxBkMn+Q8vTbX9ls30vdDrqnGDpdlxVY3dNJBNsVzA5PrpSlaSnNBlxS8ZXM1xJA+HYzqHXxY6rVxL3Sd4A83htY3vAPF00JdFqvI7NUMmAyoIE0Bpa0rWlcoW/6+AO30z0B3GGnAMiz/j99ZdfD6bOktFDs+ARSqI22hFe7kUR7lpjYe7dGV/0LlOBODY6d+8zQ/4c1PujCsngXPteB2iyxWiBzcpFIXl+MRSPUC4QWLMuiyz6+6h5ldC0Ojkfoi+Xrrdnywjmfc3IxWVxIioOl6EepIJ8Eu/y4YL2Bw4VlFiJCMeMOboBEQbkf2VI90K+u8CC6KHwg4QPIa3HSChFtvQJemiT9RyiR6bXJLNtY15HhSLsxLCxwgvtcUP5U7i5xiM+f4SrXykb7fCbCKOu9BidtYHsiDKfu6xKnopDSpCP4qv+eo38lfyJx1hqXhwH3Wlp+GAX2tTkFlhcIkhRSwrMN86OFuRMsMhPLVGuVNJM8knVMmIDKrneM5J05H4gCzzFGKg9ybW+3sZGLHw4bCphv4qI+QxE3OqQ7jhtmor4mZi2RVerllNHbGkqeBXUuEYry+ibkhyGT6+VnF11+EIiFq0KJK7JuDQOC/916vHbLQrSAQOG5eci5sb+tUodS3ISLnKCYMVzPbjRYfU2f1N0XrWZGsxb4UXeAm7YVBQMvXiJQY7krMXFURBc+6KuN4/VBNjgjZIj+XhG78EjKni4wLiAn1SGV0AQQyhSrjjkSRu8C3tLmxRKmsqyepm/GAQdAGO6+M43eER2JwDgGQLXGUdF3WZ/ziBkIaTGE2mp84yXdeFjqArBQ8TPtdwwCHyvpx7MuFd2IZRx1K/oFX9JwWOkcE1N7V3tXpKZKwcar715OdvGYKDQlcqz7uZRgjU+LRv4FqEjTmRccsYX52nkhYNXHOYyAdODq1SkFErCYwIpf+HxaJRWDG/ovO8nUnYB6umC/vnJ4KUoFRxFtflXquGP6EwsEQAamWlWXsgvd3vsEkpT7UB+N4TGfL9Z7yLydgU2LaKunwRAtA=",
+		// Ed25519 key, in use since Go 1.13.
+		"sum.golang.org+033de0ae+Ac4zctda0e5eza+HJyk9SxEdh+s3Ux18htTTAD8OuAn8",
+	},
+}
+
+func init() {
+	// ML-DSA-44 is unavailable in FIPS 140-3 Go Cryptographic Module v1.0.x.
+	if strings.HasPrefix(fips140.Version(), "v1.0.") {
+		knownGOSUMDB["sum.golang.org"] = knownGOSUMDB["sum.golang.org"][1:]
+	}
 }
diff --git a/src/cmd/go/internal/modfetch/sumdb.go b/src/cmd/go/internal/modfetch/sumdb.go
index 6fb435b010..0d6f911027 100644
--- a/src/cmd/go/internal/modfetch/sumdb.go
+++ b/src/cmd/go/internal/modfetch/sumdb.go
@@ -17,6 +17,7 @@ import (
 	"net/url"
 	"os"
 	"path/filepath"
+	"slices"
 	"strings"
 	"sync"
 	"time"
@@ -29,6 +30,7 @@ import (
 	"golang.org/x/mod/module"
 	"golang.org/x/mod/sumdb"
 	"golang.org/x/mod/sumdb/note"
+	"golang.org/x/mod/sumdb/tlog"
 )

 // useSumDB reports whether to use the Go checksum database for the given module.
@@ -69,23 +71,41 @@ func useSumDB(mod module.Version) bool {
 // along with the name of the database.
 func lookupSumDB(mod module.Version) (dbname string, lines []string, err error) {
 	dbOnce.Do(func() {
-		dbName, db, dbErr = dbDial()
+		dbName, dbs, dbErr = dbDial()
 	})
 	if dbErr != nil {
 		return "", nil, dbErr
 	}
-	lines, err = db.Lookup(mod.Path, mod.Version)
-	return dbName, lines, err
+	if len(dbs) == 0 {
+		return dbName, nil, fmt.Errorf("no checksum database verifiers for %s", dbName)
+	}
+	for i, db := range dbs {
+		l, err := db.Lookup(mod.Path, mod.Version)
+		if err != nil {
+			if len(dbs) > 1 {
+				return dbName, nil, fmt.Errorf("using key %s: %w", db.keyID, err)
+			}
+			return dbName, nil, err
+		}
+		if i == 0 {
+			lines = l
+			continue
+		}
+		if !slices.Equal(lines, l) {
+			return dbName, nil, fmt.Errorf("inconsistent checksum database responses for %s@%s", mod.Path, mod.Version)
+		}
+	}
+	return dbName, lines, nil
 }

 var (
 	dbOnce sync.Once
 	dbName string
-	db     *sumdb.Client
+	dbs    []*dbClient
 	dbErr  error
 )

-func dbDial() (dbName string, db *sumdb.Client, err error) {
+func dbDial() (dbName string, dbs []*dbClient, err error) {
 	// $GOSUMDB can be "key" or "key url",
 	// and the key can be a full verifier key
 	// or a host on our list of known keys.
@@ -103,19 +123,18 @@ func dbDial() (dbName string, db *sumdb.Client, err error) {
 		return "", nil, fmt.Errorf("checksum database disabled by GOSUMDB=off")
 	}

-	key := strings.Fields(gosumdb)
-	if len(key) >= 1 {
-		if k := knownGOSUMDB[key[0]]; k != "" {
-			key[0] = k
-		}
-	}
-	if len(key) == 0 {
+	fields := strings.Fields(gosumdb)
+	if len(fields) == 0 {
 		return "", nil, fmt.Errorf("missing GOSUMDB")
 	}
-	if len(key) > 2 {
+	if len(fields) > 2 {
 		return "", nil, fmt.Errorf("invalid GOSUMDB: too many fields")
 	}
-	vkey, err := note.NewVerifier(key[0])
+	keys, ok := knownGOSUMDB[fields[0]]
+	if !ok {
+		keys = []string{fields[0]}
+	}
+	vkey, err := note.NewVerifier(keys[len(keys)-1])
 	if err != nil {
 		return "", nil, fmt.Errorf("invalid GOSUMDB: %v", err)
 	}
@@ -129,30 +148,87 @@ func dbDial() (dbName string, db *sumdb.Client, err error) {

 	// Determine how to get to database.
 	var base *url.URL
-	if len(key) >= 2 {
+	if len(fields) >= 2 {
 		// Use explicit alternate URL listed in $GOSUMDB,
 		// bypassing both the default URL derivation and any proxies.
-		u, err := url.Parse(key[1])
+		u, err := url.Parse(fields[1])
 		if err != nil {
 			return "", nil, fmt.Errorf("invalid GOSUMDB URL: %v", err)
 		}
 		base = u
 	}

-	return name, sumdb.NewClient(&dbClient{key: key[0], name: name, direct: direct, base: base}), nil
+	dbs, err = newDBClients(&dbBase{name: name, direct: direct, base: base}, keys)
+	if err != nil {
+		return "", nil, err
+	}
+	return name, dbs, nil
 }

-type dbClient struct {
-	key    string
+// newDBClients returns one dbClient per key in keys, in sequential
+// verification order (newest to oldest). Clients for newer keys must run first
+// so they can potentially refresh stale cached /lookup/ responses that do not
+// include all the signatures. This avoids duplicative HTTP calls to SumDB.
+//
+// TODO: GOSUMDB env variable currently does not support specifying multiple
+// keys. Adding support for this seems reasonable.
+func newDBClients(shared *dbBase, keys []string) ([]*dbClient, error) {
+	clients := make([]*dbClient, len(keys))
+	for i, k := range keys {
+		v, err := note.NewVerifier(k)
+		if err != nil {
+			return nil, fmt.Errorf("invalid GOSUMDB: %v", err)
+		}
+		c := &dbClient{
+			dbBase:      shared,
+			key:         k,
+			keyID:       fmt.Sprintf("%s+%08x", v.Name(), v.KeyHash()),
+			verifiers:   note.VerifierList(v),
+			isOldestKey: i == len(keys)-1,
+		}
+		c.Client = sumdb.NewClient(c)
+		clients[i] = c
+	}
+	return clients, nil
+}
+
+// dbBase holds state shared across dbClients for the same database, such as
+// proxy probing (/supported) and in-memory caching of freshly fetched
+// responses between clients.
+type dbBase struct {
 	name   string
 	direct *url.URL

 	once    sync.Once
 	base    *url.URL
 	baseErr error
+
+	// remoteCache maps cache file names (c.name + path) to /lookup/ and /tile/
+	// responses verified by newer keys, so the oldest key can reuse them
+	// without duplicate HTTP calls and persist them to disk only after all
+	// keys have verified them.
+	remoteCache sync.Map // map[string][]byte
+}
+
+type dbClient struct {
+	*sumdb.Client
+	*dbBase
+	key       string
+	keyID     string
+	verifiers note.Verifiers
+	// isOldestKey is true for the oldest / final key in keys.
+	// The oldest key runs last, owns writing on-disk caches (/latest,
+	// /lookup/, and /tile/), and verifies /latest and /lookup/ normally.
+	// Newer keys run first, treat missing signatures in cached /latest and
+	// /lookup/ as cache misses, and pass freshly fetched responses to
+	// subsequent clients via remoteCache instead of writing to disk.
+	isOldestKey bool
 }

 func (c *dbClient) ReadRemote(path string) ([]byte, error) {
+	if v, ok := c.remoteCache.Load(c.name + path); ok {
+		return v.([]byte), nil
+	}
 	c.once.Do(c.initBase)
 	if c.baseErr != nil {
 		return nil, c.baseErr
@@ -173,7 +249,7 @@ func (c *dbClient) ReadRemote(path string) ([]byte, error) {
 // so this work is delayed until we need to download something from
 // the database. If everything we need is in the local cache and
 // c.ReadRemote is never called, we will never do this work.
-func (c *dbClient) initBase() {
+func (c *dbBase) initBase() {
 	if c.base != nil {
 		return
 	}
@@ -243,15 +319,29 @@ func (c *dbClient) ReadConfig(file string) (data []byte, err error) {
 		// the first time we connect to a given database.
 		return []byte{}, nil
 	}
+	if err == nil && !c.isOldestKey && c.missingTreeNoteSig(data) {
+		// A cached /latest written by an older toolchain may not contain the
+		// signature of newer keys. Therefore, for all keys that are not the
+		// oldest key that we support, treat a missing signature as empty here.
+		// The oldest key that we support is responsible for checking the
+		// cached tree consistency against the newly fetched tree from SumDB.
+		return []byte{}, nil
+	}
 	return data, err
 }

 // WriteConfig rewrites the latest tree head.
-func (*dbClient) WriteConfig(file string, old, new []byte) error {
+func (c *dbClient) WriteConfig(file string, old, new []byte) error {
 	if file == "key" {
 		// Should not happen.
 		return fmt.Errorf("cannot write key")
 	}
+	// The oldest key is the only one required to check the consistency of
+	// cached /latest against the newly fetched tree. It is therefore the only
+	// one that should update the cached /latest.
+	if !c.isOldestKey {
+		return nil
+	}
 	if cfg.SumdbDir == "" {
 		return fmt.Errorf("could not locate sumdb file: missing $GOPATH: %s",
 			cfg.GoPathError)
@@ -285,8 +375,14 @@ func (*dbClient) WriteConfig(file string, old, new []byte) error {
 // ReadCache reads cached lookups or tiles from
 // GOPATH/pkg/mod/cache/download/sumdb,
 // which will be deleted by "go clean -modcache".
-func (*dbClient) ReadCache(file string) ([]byte, error) {
+func (c *dbClient) ReadCache(file string) ([]byte, error) {
 	targ := filepath.Join(cfg.GOMODCACHE, "cache/download/sumdb", file)
+	// A newer key fetched a fresh response into remoteCache.
+	// Treat it as a cache miss so sumdb.Client reads it via ReadRemote
+	// and so the oldest key updates the cache on-disk after verification.
+	if _, ok := c.remoteCache.Load(file); ok {
+		return nil, &fs.PathError{Op: "read", Path: targ, Err: fs.ErrNotExist}
+	}
 	data, err := lockedfile.Read(targ)
 	// lockedfile.Write does not atomically create the file with contents.
 	// There is a moment between file creation and locking the file for writing,
@@ -295,14 +391,38 @@ func (*dbClient) ReadCache(file string) ([]byte, error) {
 	if err == nil && len(data) == 0 {
 		err = &fs.PathError{Op: "read", Path: targ, Err: fs.ErrNotExist}
 	}
+	if err == nil && !c.isOldestKey && strings.HasPrefix(file, c.name+"/lookup/") {
+		// Cached /lookup response from older toolchains may only carry the
+		// oldest key's signature. For keys that are not the oldest supported
+		// key, treat a missing signature as a cache miss, so re-verification
+		// can be done against a fresh /lookup response.
+		if _, _, treeMsg, err := tlog.ParseRecord(data); err == nil && c.missingTreeNoteSig(treeMsg) {
+			return nil, &fs.PathError{Op: "read", Path: targ, Err: fs.ErrNotExist}
+		}
+	}
 	return data, err
 }

+// missingTreeNoteSig reports whether msg is a syntactically valid note
+// that has no signature from c.key.
+func (c *dbClient) missingTreeNoteSig(msg []byte) bool {
+	_, err := note.Open(msg, c.verifiers)
+	_, ok := errors.AsType[*note.UnverifiedNoteError](err)
+	return ok
+}
+
 // WriteCache updates cached lookups or tiles.
-func (*dbClient) WriteCache(file string, data []byte) {
+func (c *dbClient) WriteCache(file string, data []byte) {
+	if !c.isOldestKey {
+		// Hold verified responses in memory for subsequent clients instead of
+		// writing to disk before every key has verified them.
+		c.remoteCache.Store(file, data)
+		return
+	}
 	targ := filepath.Join(cfg.GOMODCACHE, "cache/download/sumdb", file)
 	os.MkdirAll(filepath.Dir(targ), 0777)
 	lockedfile.Write(targ, bytes.NewReader(data), 0666)
+	c.remoteCache.Delete(file)
 }

 func (*dbClient) Log(msg string) {