使用不同的 GOPROXY 下载依赖时,依赖的 hash 校验无法通过。

问题复现与确认

# 新建一个测试项目
mkdir test
cd test
go mod init github.com/k8scat/test

# 查看当前的 GOPROXY
go env GOPROXY # https://proxy.golang.org,direct,这就是默认的 GOPROXY

# 下载依赖 github.com/zoom-lib-golang/zoom-lib-golang
go get github.com/zoom-lib-golang/zoom-lib-golang

# 查看此时的 go.sum
cat go.sum
# github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ=
# github.com/google/go-querystring v1.0.0 h1:Xkwi/a1rcvNg1PPYe5vI8GbeBY/jrVuDX5ASuANWTrk=
# github.com/google/go-querystring v1.0.0/go.mod h1:odCYkC5MyYFN7vkCjXpyrEuKhc/BUO6wN/zVPAxq5ck=
# github.com/zoom-lib-golang/zoom-lib-golang v1.0.1 h1:91bM5KretkLZcjc7iaeejb935IARtVOr/WWCCa5SkIU=
# github.com/zoom-lib-golang/zoom-lib-golang v1.0.1/go.mod h1:t3p44iNBETLiJzk0HTH42PumtcP3AHi+Pd/ZY0SPpng=
# gopkg.in/dgrijalva/jwt-go.v3 v3.2.0 h1:N46iQqOtHry7Hxzb9PGrP68oovQmj7EhudNoKHvbOvI=
# gopkg.in/dgrijalva/jwt-go.v3 v3.2.0/go.mod h1:hdNXC2Z9yC029rvsQ/on2ZNQ44Z2XToVhpXXbR+J05A=

# 清理一下缓存,准备使用其他 GOPROXY 下载上面的依赖
go clean -modcache

# 设置另一个 GOPROXY
export GOPROXY=https://goproxy.io,direct

# 重新下载上面的依赖
go get github.com/zoom-lib-golang/zoom-lib-golang
# 错误信息:
# verifying github.com/zoom-lib-golang/[email protected]/go.mod: checksum mismatch
#         downloaded: h1:Rg7IxW7rZUoP/T0YnpDtiypESDnadbv0YvxP0Gjdi6U=
#         go.sum:     h1:t3p44iNBETLiJzk0HTH42PumtcP3AHi+Pd/ZY0SPpng=

# SECURITY ERROR
# This download does NOT match an earlier download recorded in go.sum.
# The bits may have been replaced on the origin server, or an attacker may
# have intercepted the download attempt.

# For more information, see 'go help module-auth'.

# 删除 go.sum 试一下
go clean -modcache
rm -f go.sum

# 再次下载上面的依赖
go get github.com/zoom-lib-golang/zoom-lib-golang
# 错误信息:
# go: github.com/zoom-lib-golang/[email protected]: verifying go.mod: checksum mismatch
#         downloaded: h1:Rg7IxW7rZUoP/T0YnpDtiypESDnadbv0YvxP0Gjdi6U=
#         sum.golang.org: h1:t3p44iNBETLiJzk0HTH42PumtcP3AHi+Pd/ZY0SPpng=

# SECURITY ERROR
# This download does NOT match the one reported by the checksum server.
# The bits may have been replaced on the origin server, or an attacker may
# have intercepted the download attempt.

# For more information, see 'go help module-auth'.

出现的两个错误导致的原因分别是:

  1. go getgo.sum 文件存在的时候,则会使用 go.sum 里面记录的依赖 hash 和实际下载的依赖 hash 进行对比, 如果不匹配,则出现上面第一次的错误
  2. 如果 go.sum 不存在,则使用 GOSUMDB (默认是 sum.golang.org)对实际下载的依赖 hash 进行检查,如果不匹配,则出现上面第二次尝试时的错误

解决方案

  1. 关闭 GOSUMDB,即 export GOSUMDB=off
  2. 设置 GONOSUMDB,例如:export GONOSUMDB=*.corp.example.com,rsc.io/private

基于 sum.golang.org 查看依赖 hash:https://sum.golang.org/lookup/github.com/zoom-lib-golang/[email protected]

参考