All checks were successful
release / build (push) Successful in 3m58s
self-update prints each step (checking releases, verifying signature, downloading with MB and percent, verifying sha256, replacing binary). Fleet commands show a spinner after 400 ms while an API call is in flight. Output goes to stderr on a terminal only; never with --json, TERM=dumb or HUB_NO_PROGRESS=1. stdout and exit codes are unchanged.
743 lines
22 KiB
Go
743 lines
22 KiB
Go
// SPDX-License-Identifier: GPL-3.0-or-later
|
|
|
|
// Package selfupdate implements `hub self-update`: find the newest published release on the configured forge,
|
|
// verify its signed annotated tag with the gpg CLI against pinned fingerprints, verify the asset sha256, check the
|
|
// new binary reports the tagged version, then atomically replace the running binary.
|
|
//
|
|
// The signature procedure is the one scripts/release_channel.py in the Security Hub repository uses: a fresh
|
|
// temporary GNUPGHOME, the embedded public key file imported, exactly one GOODSIG and one VALIDSIG, the signing
|
|
// fingerprint pinned, no BAD/ERR/EXP/REV status, and the signed payload consistent with the forge's API answer.
|
|
// Forgejo's own `verification.verified` flag is never used.
|
|
package selfupdate
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"crypto/sha256"
|
|
_ "embed"
|
|
"encoding/hex"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"net/url"
|
|
"os"
|
|
"os/exec"
|
|
"path/filepath"
|
|
"regexp"
|
|
"runtime"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
|
|
"git.trevon.dev/trevon/hub/internal/progress"
|
|
)
|
|
|
|
const (
|
|
// DefaultForgeURL and DefaultRepo name the public repository releases are read from (no token needed).
|
|
DefaultForgeURL = "https://git.trevon.dev"
|
|
DefaultRepo = "trevon/hub"
|
|
|
|
maxJSON = 1 << 20 // API answers
|
|
maxSHAFile = 1 << 10 // <asset>.sha256
|
|
maxBinary = 64 << 20 // release binary
|
|
gpgTimeout = 30 * time.Second
|
|
listLimit = 20
|
|
maxRedirects = 3
|
|
)
|
|
|
|
// PinnedFingerprints are the signing keys a release tag may carry. Review them in docs/releasing.md.
|
|
var PinnedFingerprints = []string{
|
|
"D66F93E5DAD777C373A0CB13083EB1C25C575E81",
|
|
"C1E8284DAE319BA313FCB40038686EA797D7A8A7",
|
|
}
|
|
|
|
//go:embed signers.asc
|
|
var signersKey []byte
|
|
|
|
var (
|
|
tagRe = regexp.MustCompile(`^v(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$`)
|
|
curRe = regexp.MustCompile(`^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)`)
|
|
hex40Re = regexp.MustCompile(`^[0-9a-f]{40}$`)
|
|
repoRe = regexp.MustCompile(`^[A-Za-z0-9._-]+/[A-Za-z0-9._-]+$`)
|
|
shaLine = `^([0-9a-f]{64}) %s\n?$`
|
|
gpgBad = map[string]bool{"BADSIG": true, "ERRSIG": true, "EXPSIG": true, "EXPKEYSIG": true, "REVKEYSIG": true}
|
|
statusRe = "[GNUPG:] "
|
|
)
|
|
|
|
// Error is a self-update failure. Transport errors (forge unreachable, bad HTTP) map to exit 3, all others to exit 2.
|
|
type Error struct {
|
|
Msg string
|
|
Transport bool
|
|
}
|
|
|
|
func (e *Error) Error() string { return e.Msg }
|
|
|
|
func fail(format string, args ...any) error { return &Error{Msg: fmt.Sprintf(format, args...)} }
|
|
func transport(format string, args ...any) error {
|
|
return &Error{Msg: fmt.Sprintf(format, args...), Transport: true}
|
|
}
|
|
|
|
// Options select the mode of Run.
|
|
type Options struct {
|
|
Check bool // report only
|
|
Tag string // vX.Y.Z; empty means the newest published release. A named tag may be older than the running one.
|
|
}
|
|
|
|
// Result is what Run reports.
|
|
type Result struct {
|
|
Current string `json:"current"`
|
|
Latest string `json:"latest"`
|
|
UpdateAvailable bool `json:"update_available"`
|
|
Updated bool `json:"updated"`
|
|
Verified bool `json:"verified"`
|
|
Signer string `json:"signer,omitempty"`
|
|
SHA256 string `json:"sha256,omitempty"`
|
|
Previous string `json:"previous,omitempty"`
|
|
Message string `json:"message"`
|
|
}
|
|
|
|
// Updater holds the settings. Use New and override ForgeURL, Repo, Current or HTTP. The unexported fields are the
|
|
// trust anchors and test hooks: nothing outside this package (and so no config file or flag) can change them.
|
|
type Updater struct {
|
|
ForgeURL string
|
|
Repo string
|
|
Current string // running version, e.g. "0.1.0" or "0.0.0-dev+abc1234"
|
|
HTTP *http.Client // nil: a default client; redirects are always restricted to the same https host
|
|
Progress progress.Reporter // nil: no progress output
|
|
|
|
trusted []string
|
|
keys []byte
|
|
gpg string
|
|
goos string
|
|
goarch string
|
|
exe string // path of the running binary; empty: os.Executable
|
|
maxBinary int64
|
|
run func(ctx context.Context, argv []string) (int, []byte, error)
|
|
tmpBase string
|
|
}
|
|
|
|
// New returns an Updater with the pinned fingerprints and embedded key file.
|
|
func New() *Updater {
|
|
return &Updater{
|
|
ForgeURL: DefaultForgeURL,
|
|
Repo: DefaultRepo,
|
|
trusted: PinnedFingerprints,
|
|
keys: signersKey,
|
|
gpg: "gpg",
|
|
goos: runtime.GOOS,
|
|
goarch: runtime.GOARCH,
|
|
maxBinary: maxBinary,
|
|
run: execRun,
|
|
}
|
|
}
|
|
|
|
type version [3]int
|
|
|
|
func parseTag(tag string) (version, bool) {
|
|
m := tagRe.FindStringSubmatch(tag)
|
|
if m == nil {
|
|
return version{}, false
|
|
}
|
|
return atoi3(m), true
|
|
}
|
|
|
|
func atoi3(m []string) version {
|
|
var v version
|
|
for i := 0; i < 3; i++ {
|
|
v[i], _ = strconv.Atoi(m[i+1])
|
|
}
|
|
return v
|
|
}
|
|
|
|
func parseCurrent(s string) version {
|
|
if m := curRe.FindStringSubmatch(s); m != nil {
|
|
return atoi3(m)
|
|
}
|
|
return version{}
|
|
}
|
|
|
|
func (a version) cmp(b version) int {
|
|
for i := 0; i < 3; i++ {
|
|
if a[i] != b[i] {
|
|
if a[i] < b[i] {
|
|
return -1
|
|
}
|
|
return 1
|
|
}
|
|
}
|
|
return 0
|
|
}
|
|
|
|
type release struct {
|
|
TagName string `json:"tag_name"`
|
|
Draft bool `json:"draft"`
|
|
Prerelease bool `json:"prerelease"`
|
|
TargetCommitish string `json:"target_commitish"`
|
|
Assets []asset `json:"assets"`
|
|
}
|
|
|
|
type asset struct {
|
|
Name string `json:"name"`
|
|
Size int64 `json:"size"`
|
|
}
|
|
|
|
// Run performs the check or the update.
|
|
func (u *Updater) Run(ctx context.Context, opt Options) (*Result, error) {
|
|
res, err := u.run1(ctx, opt)
|
|
if err != nil {
|
|
u.rep().Fail()
|
|
} else {
|
|
u.rep().Done()
|
|
}
|
|
return res, err
|
|
}
|
|
|
|
func (u *Updater) rep() progress.Reporter {
|
|
if u.Progress == nil {
|
|
return progress.Nop{}
|
|
}
|
|
return u.Progress
|
|
}
|
|
|
|
func (u *Updater) run1(ctx context.Context, opt Options) (*Result, error) {
|
|
base, err := u.baseURL()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if opt.Tag != "" {
|
|
if _, ok := parseTag(opt.Tag); !ok {
|
|
return nil, fail("--version must look like v1.2.3, got %q", opt.Tag)
|
|
}
|
|
}
|
|
if !opt.Check {
|
|
if _, err := exec.LookPath(u.gpg); err != nil {
|
|
return nil, fail("gpg not found: hub self-update verifies the signed release tag with the gpg CLI; install gnupg and retry")
|
|
}
|
|
}
|
|
u.rep().Step("checking releases")
|
|
rel, err := u.pickRelease(ctx, base, opt.Tag)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
latest, _ := parseTag(rel.TagName)
|
|
current := parseCurrent(u.Current)
|
|
res := &Result{Current: u.Current, Latest: rel.TagName}
|
|
order := latest.cmp(current)
|
|
res.UpdateAvailable = order > 0
|
|
if opt.Check {
|
|
switch {
|
|
case order > 0:
|
|
res.Message = fmt.Sprintf("update available: %s -> %s (not verified; run `hub self-update`)", u.Current, rel.TagName)
|
|
case order == 0:
|
|
res.Message = fmt.Sprintf("hub %s is up to date (latest %s)", u.Current, rel.TagName)
|
|
default:
|
|
res.Message = fmt.Sprintf("hub %s is newer than the latest published release %s", u.Current, rel.TagName)
|
|
}
|
|
return res, nil
|
|
}
|
|
if opt.Tag == "" {
|
|
switch {
|
|
case order == 0:
|
|
res.Message = fmt.Sprintf("hub %s is up to date (latest %s)", u.Current, rel.TagName)
|
|
return res, nil
|
|
case order < 0:
|
|
return nil, fail("refusing downgrade: latest published release %s is older than the running %s (use --version to install it anyway)", rel.TagName, u.Current)
|
|
}
|
|
}
|
|
return u.install(ctx, base, rel, res)
|
|
}
|
|
|
|
func (u *Updater) baseURL() (*url.URL, error) {
|
|
base, err := url.Parse(u.ForgeURL)
|
|
if err != nil || base.Scheme != "https" || base.Host == "" || base.User != nil || (base.Path != "" && base.Path != "/") {
|
|
return nil, fail("update_url must be a plain https://host address, got %q", u.ForgeURL)
|
|
}
|
|
if !repoRe.MatchString(u.Repo) {
|
|
return nil, fail("update_repo must look like owner/name, got %q", u.Repo)
|
|
}
|
|
return base, nil
|
|
}
|
|
|
|
func (u *Updater) client() *http.Client {
|
|
var c http.Client
|
|
if u.HTTP != nil {
|
|
c = *u.HTTP
|
|
}
|
|
// Never follow a redirect off the forge host, never downgrade to http, never loop.
|
|
c.CheckRedirect = func(req *http.Request, via []*http.Request) error {
|
|
if len(via) >= maxRedirects {
|
|
return errors.New("too many redirects")
|
|
}
|
|
if req.URL.Scheme != "https" || req.URL.Host != via[0].URL.Host {
|
|
return fmt.Errorf("refusing redirect to %s://%s", req.URL.Scheme, req.URL.Host)
|
|
}
|
|
return nil
|
|
}
|
|
return &c
|
|
}
|
|
|
|
// get fetches an https URL and returns at most limit bytes; a longer body is an error.
|
|
func (u *Updater) get(ctx context.Context, rawURL string, limit int64, timeout time.Duration) ([]byte, error) {
|
|
return u.getBody(ctx, rawURL, limit, timeout, 0)
|
|
}
|
|
|
|
// getBody is get with byte progress against the expected size (0: unknown) on the open step.
|
|
func (u *Updater) getBody(ctx context.Context, rawURL string, limit int64, timeout time.Duration, expect int64) ([]byte, error) {
|
|
ctx, cancel := context.WithTimeout(ctx, timeout)
|
|
defer cancel()
|
|
req, err := http.NewRequestWithContext(ctx, http.MethodGet, rawURL, nil)
|
|
if err != nil {
|
|
return nil, fail("bad url %s", rawURL)
|
|
}
|
|
if req.URL.Scheme != "https" {
|
|
return nil, fail("refusing non-https url %s", rawURL)
|
|
}
|
|
req.Header.Set("User-Agent", "hub-self-update")
|
|
resp, err := u.client().Do(req)
|
|
if err != nil {
|
|
return nil, transport("fetch %s: %v", req.URL.Redacted(), unwrapURLError(err))
|
|
}
|
|
defer resp.Body.Close()
|
|
if resp.StatusCode != http.StatusOK {
|
|
return nil, transport("fetch %s: HTTP %d", req.URL.Redacted(), resp.StatusCode)
|
|
}
|
|
var src io.Reader = resp.Body
|
|
if expect > 0 {
|
|
src = progress.NewReader(resp.Body, expect, u.rep())
|
|
}
|
|
body, err := io.ReadAll(io.LimitReader(src, limit+1))
|
|
if err != nil {
|
|
return nil, transport("fetch %s: %v", req.URL.Redacted(), err)
|
|
}
|
|
if int64(len(body)) > limit {
|
|
return nil, fail("fetch %s: body over %d bytes", req.URL.Redacted(), limit)
|
|
}
|
|
return body, nil
|
|
}
|
|
|
|
func unwrapURLError(err error) error {
|
|
var ue *url.Error
|
|
if errors.As(err, &ue) {
|
|
return ue.Err
|
|
}
|
|
return err
|
|
}
|
|
|
|
func (u *Updater) api(ctx context.Context, base *url.URL, path string, into any) error {
|
|
raw, err := u.get(ctx, base.String()+"/api/v1/repos/"+u.Repo+"/"+path, maxJSON, 30*time.Second)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if err := json.Unmarshal(raw, into); err != nil {
|
|
return fail("invalid JSON from %s", strings.SplitN(path, "?", 2)[0])
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func published(r release) bool {
|
|
_, ok := parseTag(r.TagName)
|
|
return ok && !r.Draft && !r.Prerelease
|
|
}
|
|
|
|
func (u *Updater) pickRelease(ctx context.Context, base *url.URL, tag string) (*release, error) {
|
|
if tag != "" {
|
|
var r release
|
|
if err := u.api(ctx, base, "releases/tags/"+url.PathEscape(tag), &r); err != nil {
|
|
return nil, err
|
|
}
|
|
if r.TagName != tag || !published(r) {
|
|
return nil, fail("release %s is not a published release", tag)
|
|
}
|
|
return &r, nil
|
|
}
|
|
var list []release
|
|
if err := u.api(ctx, base, "releases?limit="+strconv.Itoa(listLimit), &list); err != nil {
|
|
return nil, err
|
|
}
|
|
var best *release
|
|
var bestV version
|
|
for i := range list {
|
|
if !published(list[i]) {
|
|
continue
|
|
}
|
|
v, _ := parseTag(list[i].TagName)
|
|
if best == nil || v.cmp(bestV) > 0 {
|
|
best, bestV = &list[i], v
|
|
}
|
|
}
|
|
if best == nil {
|
|
return nil, fail("no published release found in %s", u.Repo)
|
|
}
|
|
return best, nil
|
|
}
|
|
|
|
func (u *Updater) install(ctx context.Context, base *url.URL, rel *release, res *Result) (*Result, error) {
|
|
tag := rel.TagName
|
|
ver := strings.TrimPrefix(tag, "v")
|
|
|
|
// 1. Tag signature, before anything else is downloaded.
|
|
u.rep().Step("verifying signature")
|
|
signer, err := u.verifyTag(ctx, base, rel)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
res.Signer, res.Verified = signer, true
|
|
|
|
// 2. Asset hash file, then the binary.
|
|
name := fmt.Sprintf("hub-%s-%s-%s", ver, u.goos, u.goarch)
|
|
listed := map[string]int64{}
|
|
for _, a := range rel.Assets {
|
|
listed[a.Name] = a.Size
|
|
}
|
|
size, ok := listed[name]
|
|
if !ok {
|
|
return nil, fail("release %s has no asset %s", tag, name)
|
|
}
|
|
shaSize, ok := listed[name+".sha256"]
|
|
if !ok {
|
|
return nil, fail("release %s has no asset %s.sha256", tag, name)
|
|
}
|
|
if shaSize <= 0 || shaSize > maxSHAFile {
|
|
return nil, fail("asset %s.sha256 has an unacceptable size (%d)", name, shaSize)
|
|
}
|
|
if size <= 0 || size > u.maxBinary {
|
|
return nil, fail("asset %s has an unacceptable size (%d, limit %d)", name, size, u.maxBinary)
|
|
}
|
|
dl := base.String() + "/" + u.Repo + "/releases/download/" + url.PathEscape(tag) + "/"
|
|
shaBody, err := u.get(ctx, dl+name+".sha256", maxSHAFile, 30*time.Second)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
m := regexp.MustCompile(fmt.Sprintf(shaLine, regexp.QuoteMeta(name))).FindSubmatch(shaBody)
|
|
if m == nil {
|
|
return nil, fail("asset %s.sha256 is not `<64 hex> %s`", name, name)
|
|
}
|
|
wantSum := string(m[1])
|
|
u.rep().Step(fmt.Sprintf("downloading %s (%.1f MB)", name, float64(size)/(1024*1024)))
|
|
bin, err := u.getBody(ctx, dl+name, u.maxBinary, 5*time.Minute, size)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
u.rep().Step("verifying sha256")
|
|
sum := sha256.Sum256(bin)
|
|
if got := hex.EncodeToString(sum[:]); got != wantSum {
|
|
return nil, fail("sha256 mismatch for %s: release says %s, downloaded %s", name, wantSum, got)
|
|
}
|
|
res.SHA256 = wantSum
|
|
|
|
// 3. Stage next to the running binary, prove it reports the tagged version, then swap.
|
|
u.rep().Step("replacing binary")
|
|
exe, err := u.executable()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
tmp, err := os.CreateTemp(filepath.Dir(exe), ".hub-update-*")
|
|
if err != nil {
|
|
return nil, fail("cannot stage the new binary next to %s: %v", exe, err)
|
|
}
|
|
tmpPath := tmp.Name()
|
|
cleanup := func() { _ = os.Remove(tmpPath) }
|
|
if _, err := tmp.Write(bin); err != nil {
|
|
_ = tmp.Close()
|
|
cleanup()
|
|
return nil, fail("write %s: %v", tmpPath, err)
|
|
}
|
|
if err := tmp.Sync(); err != nil {
|
|
_ = tmp.Close()
|
|
cleanup()
|
|
return nil, fail("sync %s: %v", tmpPath, err)
|
|
}
|
|
if err := tmp.Close(); err != nil {
|
|
cleanup()
|
|
return nil, fail("close %s: %v", tmpPath, err)
|
|
}
|
|
if err := os.Chmod(tmpPath, 0o755); err != nil {
|
|
cleanup()
|
|
return nil, fail("chmod %s: %v", tmpPath, err)
|
|
}
|
|
if err := u.checkVersion(ctx, tmpPath, ver); err != nil {
|
|
cleanup()
|
|
return nil, err
|
|
}
|
|
prev := exe + ".previous"
|
|
if err := keepPrevious(exe, prev); err != nil {
|
|
cleanup()
|
|
return nil, fail("cannot keep %s: %v", prev, err)
|
|
}
|
|
if err := os.Rename(tmpPath, exe); err != nil {
|
|
cleanup()
|
|
return nil, fail("replace %s: %v", exe, err)
|
|
}
|
|
res.Updated, res.Previous = true, prev
|
|
res.Message = fmt.Sprintf("updated hub %s -> %s (tag signed by %s, sha256 %s); previous binary kept at %s", u.Current, ver, signer, wantSum, prev)
|
|
return res, nil
|
|
}
|
|
|
|
func (u *Updater) executable() (string, error) {
|
|
exe := u.exe
|
|
if exe == "" {
|
|
p, err := os.Executable()
|
|
if err != nil {
|
|
return "", fail("cannot locate the running binary: %v", err)
|
|
}
|
|
exe = p
|
|
}
|
|
real, err := filepath.EvalSymlinks(exe)
|
|
if err != nil {
|
|
return "", fail("cannot resolve %s: %v", exe, err)
|
|
}
|
|
return real, nil
|
|
}
|
|
|
|
// checkVersion runs `<path> version` and requires exactly `hub <ver>`.
|
|
func (u *Updater) checkVersion(ctx context.Context, path, ver string) error {
|
|
ctx, cancel := context.WithTimeout(ctx, 15*time.Second)
|
|
defer cancel()
|
|
var out bytes.Buffer
|
|
cmd := exec.CommandContext(ctx, path, "version")
|
|
cmd.Stdout = &out
|
|
if err := cmd.Run(); err != nil {
|
|
return fail("the downloaded binary does not run (`version` failed: %v); nothing was replaced", err)
|
|
}
|
|
if got := strings.TrimSpace(out.String()); got != "hub "+ver {
|
|
return fail("the downloaded binary reports %q, expected %q; nothing was replaced", got, "hub "+ver)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// keepPrevious preserves the running binary as prev (hard link, or a copy when linking is impossible).
|
|
func keepPrevious(exe, prev string) error {
|
|
if err := os.Remove(prev); err != nil && !errors.Is(err, os.ErrNotExist) {
|
|
return err
|
|
}
|
|
if err := os.Link(exe, prev); err == nil {
|
|
return nil
|
|
}
|
|
in, err := os.Open(exe)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer in.Close()
|
|
out, err := os.OpenFile(prev, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o755)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if _, err := io.Copy(out, in); err != nil {
|
|
_ = out.Close()
|
|
return err
|
|
}
|
|
return out.Close()
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------------------------------------------------
|
|
// tag verification
|
|
|
|
func (u *Updater) verifyTag(ctx context.Context, base *url.URL, rel *release) (string, error) {
|
|
tag := rel.TagName
|
|
var refs []struct {
|
|
Ref string `json:"ref"`
|
|
Object struct {
|
|
Type string `json:"type"`
|
|
SHA string `json:"sha"`
|
|
} `json:"object"`
|
|
}
|
|
if err := u.api(ctx, base, "git/refs/tags/"+url.PathEscape(tag), &refs); err != nil {
|
|
return "", err
|
|
}
|
|
var matching []int
|
|
for i, r := range refs {
|
|
if r.Ref == "refs/tags/"+tag {
|
|
matching = append(matching, i)
|
|
}
|
|
}
|
|
if len(matching) != 1 || refs[matching[0]].Object.Type != "tag" || !hex40Re.MatchString(refs[matching[0]].Object.SHA) {
|
|
return "", fail("tag %s is not an annotated, signed tag object", tag)
|
|
}
|
|
tagSHA := refs[matching[0]].Object.SHA
|
|
var obj struct {
|
|
SHA string `json:"sha"`
|
|
Tag string `json:"tag"`
|
|
Object struct {
|
|
Type string `json:"type"`
|
|
SHA string `json:"sha"`
|
|
} `json:"object"`
|
|
Verification struct {
|
|
Signature string `json:"signature"`
|
|
Payload string `json:"payload"`
|
|
} `json:"verification"`
|
|
}
|
|
if err := u.api(ctx, base, "git/tags/"+tagSHA, &obj); err != nil {
|
|
return "", err
|
|
}
|
|
if obj.SHA != tagSHA || obj.Tag != tag {
|
|
return "", fail("tag object does not match the ref for %s", tag)
|
|
}
|
|
if obj.Object.Type != "commit" || !hex40Re.MatchString(obj.Object.SHA) {
|
|
return "", fail("tag %s does not point at a commit", tag)
|
|
}
|
|
sig, payload := obj.Verification.Signature, obj.Verification.Payload
|
|
if strings.TrimSpace(sig) == "" || payload == "" {
|
|
return "", fail("tag %s carries no signature or payload", tag)
|
|
}
|
|
signer, err := u.verifySignature(ctx, sig, payload)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
f := parsePayload(payload)
|
|
if f["object"] != obj.Object.SHA || f["type"] != "commit" || f["tag"] != tag {
|
|
return "", fail("signed payload does not name tag %s and commit %s", tag, obj.Object.SHA)
|
|
}
|
|
if t := rel.TargetCommitish; hex40Re.MatchString(t) && t != obj.Object.SHA {
|
|
return "", fail("release target commit %s differs from the signed tag's commit %s", t, obj.Object.SHA)
|
|
}
|
|
return signer, nil
|
|
}
|
|
|
|
// parsePayload reads the header lines (up to the first blank line) of a git tag object body.
|
|
func parsePayload(payload string) map[string]string {
|
|
head := strings.SplitN(payload, "\n\n", 2)[0]
|
|
out := map[string]string{}
|
|
for _, line := range strings.Split(head, "\n") {
|
|
k, v, _ := strings.Cut(line, " ")
|
|
if k == "object" || k == "type" || k == "tag" {
|
|
if _, seen := out[k]; !seen {
|
|
out[k] = v
|
|
}
|
|
}
|
|
}
|
|
return out
|
|
}
|
|
|
|
func execRun(ctx context.Context, argv []string) (int, []byte, error) {
|
|
ctx, cancel := context.WithTimeout(ctx, gpgTimeout)
|
|
defer cancel()
|
|
cmd := exec.CommandContext(ctx, argv[0], argv[1:]...)
|
|
var out bytes.Buffer
|
|
cmd.Stdout = &out
|
|
err := cmd.Run()
|
|
var ee *exec.ExitError
|
|
if errors.As(err, &ee) {
|
|
return ee.ExitCode(), out.Bytes(), nil
|
|
}
|
|
if err != nil {
|
|
return -1, out.Bytes(), err
|
|
}
|
|
return 0, out.Bytes(), nil
|
|
}
|
|
|
|
// verifySignature verifies a detached PGP signature over payload and returns the pinned fingerprint that signed it.
|
|
//
|
|
// Commands (HOME is a fresh 0700 directory under /tmp, because gpg-agent socket paths must be short):
|
|
//
|
|
// gpg --batch --no-tty --no-autostart --homedir HOME --import HOME/keys.asc
|
|
// gpg --batch --no-tty --no-autostart --homedir HOME --list-keys --with-colons --fingerprint
|
|
// gpg --batch --no-tty --no-autostart --homedir HOME --status-fd 1 --verify HOME/sig.asc HOME/payload
|
|
// gpgconf --homedir HOME --kill all
|
|
func (u *Updater) verifySignature(ctx context.Context, signature, payload string) (string, error) {
|
|
tmpBase := u.tmpBase
|
|
if tmpBase == "" {
|
|
tmpBase = "/tmp"
|
|
if st, err := os.Stat(tmpBase); err != nil || !st.IsDir() {
|
|
tmpBase = ""
|
|
}
|
|
}
|
|
home, err := os.MkdirTemp(tmpBase, "hubgpg")
|
|
if err != nil {
|
|
return "", fail("cannot create a temporary GNUPGHOME: %v", err)
|
|
}
|
|
defer func() {
|
|
_, _, _ = u.run(ctx, []string{"gpgconf", "--homedir", home, "--kill", "all"})
|
|
_ = os.RemoveAll(home)
|
|
}()
|
|
if err := os.Chmod(home, 0o700); err != nil {
|
|
return "", fail("cannot secure the temporary GNUPGHOME: %v", err)
|
|
}
|
|
keysPath := filepath.Join(home, "keys.asc")
|
|
sigPath, payloadPath := filepath.Join(home, "sig.asc"), filepath.Join(home, "payload")
|
|
for path, data := range map[string][]byte{
|
|
keysPath: u.keys,
|
|
sigPath: []byte(strings.TrimSpace(signature) + "\n"),
|
|
payloadPath: []byte(payload),
|
|
} {
|
|
if err := os.WriteFile(path, data, 0o600); err != nil {
|
|
return "", fail("write %s: %v", path, err)
|
|
}
|
|
}
|
|
base := []string{u.gpg, "--batch", "--no-tty", "--no-autostart", "--homedir", home}
|
|
rc, _, err := u.run(ctx, append(append([]string{}, base...), "--import", keysPath))
|
|
if err != nil || rc != 0 {
|
|
return "", fail("keys_import_failed: importing the embedded key file failed (rc=%d)", rc)
|
|
}
|
|
rc, out, err := u.run(ctx, append(append([]string{}, base...), "--list-keys", "--with-colons", "--fingerprint"))
|
|
if err != nil || rc != 0 {
|
|
return "", fail("listing the embedded keys failed (rc=%d)", rc)
|
|
}
|
|
known := map[string]bool{}
|
|
for _, line := range strings.Split(string(out), "\n") {
|
|
if strings.HasPrefix(line, "fpr:") {
|
|
if f := strings.Split(line, ":"); len(f) > 9 {
|
|
known[f[9]] = true
|
|
}
|
|
}
|
|
}
|
|
pinnedKnown := false
|
|
for _, t := range u.trusted {
|
|
if known[t] {
|
|
pinnedKnown = true
|
|
}
|
|
}
|
|
if !pinnedKnown {
|
|
return "", fail("pinned_fingerprint_not_in_keys_file: none of the pinned fingerprints is in the embedded key file")
|
|
}
|
|
rc, out, err = u.run(ctx, append(append([]string{}, base...), "--status-fd", "1", "--verify", sigPath, payloadPath))
|
|
if err != nil {
|
|
return "", fail("gpg --verify could not run: %v", err)
|
|
}
|
|
var words []string
|
|
var valid [][]string
|
|
for _, line := range strings.Split(string(out), "\n") {
|
|
if !strings.HasPrefix(line, statusRe) {
|
|
continue
|
|
}
|
|
f := strings.Split(strings.TrimRight(line[len(statusRe):], "\r"), " ")
|
|
words = append(words, f[0])
|
|
if f[0] == "VALIDSIG" {
|
|
valid = append(valid, f)
|
|
}
|
|
}
|
|
good := 0
|
|
for _, w := range words {
|
|
if gpgBad[w] {
|
|
return "", fail("signature_bad: gpg reported %s", w)
|
|
}
|
|
if w == "GOODSIG" {
|
|
good++
|
|
}
|
|
}
|
|
if rc != 0 || good != 1 || len(valid) != 1 {
|
|
return "", fail("signature_not_valid: rc=%d goodsig=%d validsig=%d", rc, good, len(valid))
|
|
}
|
|
// VALIDSIG <signing fpr> <date> <ts> <expire> <ver> <reserved> <pk-algo> <hash-algo> <class> <primary fpr>
|
|
f := valid[0]
|
|
signing, primary := "", ""
|
|
if len(f) > 1 {
|
|
signing = f[1]
|
|
}
|
|
if len(f) >= 11 {
|
|
primary = f[len(f)-1]
|
|
}
|
|
for _, cand := range []string{primary, signing} {
|
|
for _, t := range u.trusted {
|
|
if cand != "" && cand == t {
|
|
return cand, nil
|
|
}
|
|
}
|
|
}
|
|
who := primary
|
|
if who == "" {
|
|
who = signing
|
|
}
|
|
return "", fail("signer_not_trusted: tag signed by %s, which is not a pinned fingerprint", who)
|
|
}
|