636 lines
20 KiB
Go
636 lines
20 KiB
Go
// SPDX-License-Identifier: GPL-3.0-or-later
|
|
|
|
package selfupdate
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"crypto/sha256"
|
|
"crypto/x509"
|
|
"encoding/hex"
|
|
"encoding/json"
|
|
"fmt"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"os"
|
|
"os/exec"
|
|
"path/filepath"
|
|
"regexp"
|
|
"strings"
|
|
"sync"
|
|
"testing"
|
|
)
|
|
|
|
// ---------------------------------------------------------------------------------------------------------------------
|
|
// gpg fixtures: throwaway keys in a short temp GNUPGHOME (never the user's keyring)
|
|
|
|
func needGPG(t *testing.T) {
|
|
t.Helper()
|
|
if _, err := exec.LookPath("gpg"); err != nil {
|
|
t.Skip("gpg not installed")
|
|
}
|
|
}
|
|
|
|
type testKey struct {
|
|
home string
|
|
fpr string
|
|
pub []byte
|
|
}
|
|
|
|
func gpgRun(t *testing.T, home string, stdin []byte, args ...string) []byte {
|
|
t.Helper()
|
|
full := append([]string{"--batch", "--no-tty", "--homedir", home}, args...)
|
|
cmd := exec.Command("gpg", full...)
|
|
cmd.Stdin = bytes.NewReader(stdin)
|
|
out, err := cmd.Output()
|
|
if err != nil {
|
|
t.Fatalf("gpg %v: %v", args, err)
|
|
}
|
|
return out
|
|
}
|
|
|
|
var (
|
|
keyMu sync.Mutex
|
|
keyCache = map[string]*testKey{}
|
|
)
|
|
|
|
// TestMain removes the throwaway GNUPGHOMEs created by newKey.
|
|
func TestMain(m *testing.M) {
|
|
code := m.Run()
|
|
for _, k := range keyCache {
|
|
_ = exec.Command("gpgconf", "--homedir", k.home, "--kill", "all").Run()
|
|
_ = os.RemoveAll(k.home)
|
|
}
|
|
os.Exit(code)
|
|
}
|
|
|
|
// newKey returns a throwaway ed25519 signing key (generated once per uid, in its own short temp GNUPGHOME).
|
|
func newKey(t *testing.T, uid string) *testKey {
|
|
t.Helper()
|
|
needGPG(t)
|
|
keyMu.Lock()
|
|
defer keyMu.Unlock()
|
|
if k, ok := keyCache[uid]; ok {
|
|
return k
|
|
}
|
|
home, err := os.MkdirTemp("/tmp", "hubtk")
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
gpgRun(t, home, nil, "--passphrase", "", "--pinentry-mode", "loopback", "--quick-generate-key", uid, "ed25519", "sign", "never")
|
|
out := gpgRun(t, home, nil, "--list-keys", "--with-colons", "--fingerprint")
|
|
var fpr string
|
|
for _, line := range strings.Split(string(out), "\n") {
|
|
if strings.HasPrefix(line, "fpr:") {
|
|
fpr = strings.Split(line, ":")[9]
|
|
break
|
|
}
|
|
}
|
|
k := &testKey{home: home, fpr: fpr, pub: gpgRun(t, home, nil, "--armor", "--export", fpr)}
|
|
keyCache[uid] = k
|
|
return k
|
|
}
|
|
|
|
func (k *testKey) sign(t *testing.T, payload string) string {
|
|
t.Helper()
|
|
dir := t.TempDir()
|
|
p := filepath.Join(dir, "payload")
|
|
if err := os.WriteFile(p, []byte(payload), 0o600); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
gpgRun(t, k.home, nil, "--passphrase", "", "--pinentry-mode", "loopback", "--armor", "--detach-sign", "-o", filepath.Join(dir, "sig"), p)
|
|
sig, err := os.ReadFile(filepath.Join(dir, "sig"))
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
return string(sig)
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------------------------------------------------
|
|
// fake forge
|
|
|
|
const commitSHA = "0123456789abcdef0123456789abcdef01234567"
|
|
const tagSHA = "89abcdef0123456789abcdef0123456789abcdef"
|
|
|
|
type forge struct {
|
|
t *testing.T
|
|
srv *httptest.Server
|
|
key *testKey
|
|
tags []string // published tags offered by the release list
|
|
asset []byte // binary content for every tag
|
|
shaFor func(bin []byte) string
|
|
mutate func(f *forge, tag string, tagObj map[string]any, ref map[string]any)
|
|
redirect string // if set, binary download redirects here
|
|
hits []string
|
|
}
|
|
|
|
func script(version string) []byte {
|
|
return []byte("#!/bin/sh\necho 'hub " + version + "'\n")
|
|
}
|
|
|
|
func sum(b []byte) string { h := sha256.Sum256(b); return hex.EncodeToString(h[:]) }
|
|
|
|
func payloadFor(tag string) string {
|
|
return fmt.Sprintf("object %s\ntype commit\ntag %s\ntagger T <t@example.org> 1700000000 +0000\n\nhub %s\n", commitSHA, tag, tag)
|
|
}
|
|
|
|
func newForge(t *testing.T, key *testKey, tags ...string) *forge {
|
|
f := &forge{t: t, key: key, tags: tags, shaFor: sum}
|
|
f.srv = httptest.NewTLSServer(http.HandlerFunc(f.handle))
|
|
t.Cleanup(f.srv.Close)
|
|
return f
|
|
}
|
|
|
|
func (f *forge) goos() string { return "linux" }
|
|
func (f *forge) goarch() string { return "amd64" }
|
|
|
|
func (f *forge) releaseJSON(tag string) map[string]any {
|
|
ver := strings.TrimPrefix(tag, "v")
|
|
name := fmt.Sprintf("hub-%s-linux-amd64", ver)
|
|
bin := f.binFor(tag)
|
|
return map[string]any{
|
|
"tag_name": tag, "draft": false, "prerelease": false, "target_commitish": commitSHA,
|
|
"assets": []map[string]any{
|
|
{"name": name, "size": len(bin)},
|
|
{"name": name + ".sha256", "size": 64 + 2 + len(name) + 1},
|
|
},
|
|
}
|
|
}
|
|
|
|
func (f *forge) binFor(tag string) []byte {
|
|
if f.asset != nil {
|
|
return f.asset
|
|
}
|
|
return script(strings.TrimPrefix(tag, "v"))
|
|
}
|
|
|
|
func (f *forge) handle(w http.ResponseWriter, r *http.Request) {
|
|
f.hits = append(f.hits, r.URL.Path)
|
|
api := "/api/v1/repos/o/hub/"
|
|
write := func(v any) { _ = json.NewEncoder(w).Encode(v) }
|
|
switch {
|
|
case r.URL.Path == api+"releases":
|
|
var list []map[string]any
|
|
for _, tag := range f.tags {
|
|
list = append(list, f.releaseJSON(tag))
|
|
}
|
|
list = append(list, map[string]any{"tag_name": "v9.9.9", "draft": true, "prerelease": false}, map[string]any{"tag_name": "v8.8.8-rc.1", "draft": false, "prerelease": true})
|
|
write(list)
|
|
case strings.HasPrefix(r.URL.Path, api+"releases/tags/"):
|
|
write(f.releaseJSON(strings.TrimPrefix(r.URL.Path, api+"releases/tags/")))
|
|
case strings.HasPrefix(r.URL.Path, api+"git/refs/tags/"):
|
|
tag := strings.TrimPrefix(r.URL.Path, api+"git/refs/tags/")
|
|
ref := map[string]any{"ref": "refs/tags/" + tag, "object": map[string]any{"type": "tag", "sha": tagSHA}}
|
|
if f.mutate != nil {
|
|
f.mutate(f, tag, nil, ref)
|
|
}
|
|
write([]any{ref})
|
|
case strings.HasPrefix(r.URL.Path, api+"git/tags/"):
|
|
tag := f.tags[0]
|
|
if len(f.hits) > 0 {
|
|
tag = f.lastTag()
|
|
}
|
|
payload := payloadFor(tag)
|
|
obj := map[string]any{
|
|
"sha": tagSHA, "tag": tag, "object": map[string]any{"type": "commit", "sha": commitSHA},
|
|
"verification": map[string]any{"signature": f.key.sign(f.t, payload), "payload": payload},
|
|
}
|
|
if f.mutate != nil {
|
|
f.mutate(f, tag, obj, nil)
|
|
}
|
|
write(obj)
|
|
case strings.HasPrefix(r.URL.Path, "/o/hub/releases/download/"):
|
|
rest := strings.TrimPrefix(r.URL.Path, "/o/hub/releases/download/")
|
|
tag, name, _ := strings.Cut(rest, "/")
|
|
if strings.HasSuffix(name, ".sha256") {
|
|
bin := f.binFor(tag)
|
|
fmt.Fprintf(w, "%s %s\n", f.shaFor(bin), strings.TrimSuffix(name, ".sha256"))
|
|
return
|
|
}
|
|
if f.redirect != "" {
|
|
http.Redirect(w, r, f.redirect, http.StatusFound)
|
|
return
|
|
}
|
|
_, _ = w.Write(f.binFor(tag))
|
|
default:
|
|
http.NotFound(w, r)
|
|
}
|
|
}
|
|
|
|
func (f *forge) lastTag() string {
|
|
for i := len(f.hits) - 1; i >= 0; i-- {
|
|
if strings.HasPrefix(f.hits[i], "/api/v1/repos/o/hub/git/refs/tags/") {
|
|
return strings.TrimPrefix(f.hits[i], "/api/v1/repos/o/hub/git/refs/tags/")
|
|
}
|
|
}
|
|
return f.tags[0]
|
|
}
|
|
|
|
// updater returns an Updater wired to the fake forge with a running binary (version cur) in a temp dir.
|
|
func (f *forge) updater(t *testing.T, cur string, trusted ...string) (*Updater, string) {
|
|
t.Helper()
|
|
dir := t.TempDir()
|
|
exe := filepath.Join(dir, "hub")
|
|
if err := os.WriteFile(exe, script(cur), 0o755); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
u := New()
|
|
u.ForgeURL = f.srv.URL
|
|
u.Repo = "o/hub"
|
|
u.Current = cur
|
|
u.HTTP = f.srv.Client()
|
|
u.exe = exe
|
|
u.goos, u.goarch = f.goos(), f.goarch()
|
|
u.tmpBase = "/tmp"
|
|
if f.key != nil {
|
|
u.keys = f.key.pub
|
|
u.trusted = []string{f.key.fpr}
|
|
}
|
|
if len(trusted) > 0 {
|
|
u.trusted = trusted
|
|
}
|
|
return u, exe
|
|
}
|
|
|
|
func content(t *testing.T, path string) string {
|
|
t.Helper()
|
|
b, err := os.ReadFile(path)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
return string(b)
|
|
}
|
|
|
|
func wantErr(t *testing.T, err error, sub string) {
|
|
t.Helper()
|
|
if err == nil {
|
|
t.Fatalf("expected an error containing %q, got none", sub)
|
|
}
|
|
if !strings.Contains(err.Error(), sub) {
|
|
t.Fatalf("error %q does not contain %q", err, sub)
|
|
}
|
|
}
|
|
|
|
func notSwapped(t *testing.T, exe, cur string) {
|
|
t.Helper()
|
|
if got := content(t, exe); got != string(script(cur)) {
|
|
t.Errorf("binary was replaced: %q", got)
|
|
}
|
|
if _, err := os.Stat(exe + ".previous"); err == nil {
|
|
t.Error(".previous must not exist when nothing was swapped")
|
|
}
|
|
entries, _ := os.ReadDir(filepath.Dir(exe))
|
|
for _, e := range entries {
|
|
if strings.HasPrefix(e.Name(), ".hub-update-") {
|
|
t.Errorf("staging file left behind: %s", e.Name())
|
|
}
|
|
}
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------------------------------------------------
|
|
// tests
|
|
|
|
func TestPinnedFingerprintsAreInTheEmbeddedKeyFile(t *testing.T) {
|
|
needGPG(t)
|
|
home, err := os.MkdirTemp("/tmp", "hubpk")
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
defer os.RemoveAll(home)
|
|
defer exec.Command("gpgconf", "--homedir", home, "--kill", "all").Run()
|
|
keyFile := filepath.Join(home, "k.asc")
|
|
if err := os.WriteFile(keyFile, signersKey, 0o600); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
gpgRun(t, home, nil, "--import", keyFile)
|
|
out := string(gpgRun(t, home, nil, "--list-keys", "--with-colons", "--fingerprint"))
|
|
if len(PinnedFingerprints) != 2 || PinnedFingerprints[0] != "D66F93E5DAD777C373A0CB13083EB1C25C575E81" || PinnedFingerprints[1] != "C1E8284DAE319BA313FCB40038686EA797D7A8A7" {
|
|
t.Fatalf("pinned = %v", PinnedFingerprints)
|
|
}
|
|
for _, fp := range PinnedFingerprints {
|
|
if !strings.Contains(out, ":"+fp+":") {
|
|
t.Errorf("pinned %s is not in the embedded key file", fp)
|
|
}
|
|
}
|
|
if New().trusted[0] != PinnedFingerprints[0] || len(New().keys) == 0 {
|
|
t.Error("New must start from the pinned fingerprints and the embedded key")
|
|
}
|
|
}
|
|
|
|
func TestGoodSignedReleaseIsInstalledAtomicallyKeepingPrevious(t *testing.T) {
|
|
f := newForge(t, newKey(t, "Release <r@example.org>"), "v0.1.0", "v0.2.0")
|
|
u, exe := f.updater(t, "0.1.0")
|
|
res, err := u.Run(context.Background(), Options{})
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if !res.Updated || !res.Verified || res.Signer != f.key.fpr || res.Latest != "v0.2.0" {
|
|
t.Fatalf("result = %+v", res)
|
|
}
|
|
if got := content(t, exe); got != string(script("0.2.0")) {
|
|
t.Errorf("binary = %q", got)
|
|
}
|
|
if got := content(t, exe+".previous"); got != string(script("0.1.0")) {
|
|
t.Errorf(".previous = %q", got)
|
|
}
|
|
for _, p := range []string{exe, exe + ".previous"} {
|
|
if st, err := os.Stat(p); err != nil || st.Mode().Perm() != 0o755 {
|
|
t.Errorf("%s mode = %v %v", p, st, err)
|
|
}
|
|
}
|
|
// a second update replaces .previous with the then-running binary
|
|
f.tags = []string{"v0.3.0"}
|
|
u.Current = "0.2.0"
|
|
if _, err := u.Run(context.Background(), Options{}); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if got := content(t, exe+".previous"); got != string(script("0.2.0")) {
|
|
t.Errorf(".previous after second update = %q", got)
|
|
}
|
|
entries, _ := os.ReadDir(filepath.Dir(exe))
|
|
if len(entries) != 2 {
|
|
t.Errorf("directory holds %d entries, want hub and hub.previous only", len(entries))
|
|
}
|
|
}
|
|
|
|
func TestUpToDateDoesNothing(t *testing.T) {
|
|
f := newForge(t, newKey(t, "Release <r@example.org>"), "v0.2.0")
|
|
u, exe := f.updater(t, "0.2.0")
|
|
res, err := u.Run(context.Background(), Options{})
|
|
if err != nil || res.Updated || res.UpdateAvailable || !strings.Contains(res.Message, "up to date") {
|
|
t.Fatalf("res=%+v err=%v", res, err)
|
|
}
|
|
notSwapped(t, exe, "0.2.0")
|
|
}
|
|
|
|
func TestSignatureByUnpinnedKeyIsRefused(t *testing.T) {
|
|
pinned := newKey(t, "Pinned <p@example.org>")
|
|
other := newKey(t, "Other <o@example.org>")
|
|
f := newForge(t, other, "v0.2.0")
|
|
u, exe := f.updater(t, "0.1.0", pinned.fpr)
|
|
u.keys = append(append([]byte{}, pinned.pub...), other.pub...) // both keys are in the file; only one is pinned
|
|
_, err := u.Run(context.Background(), Options{})
|
|
wantErr(t, err, "signer_not_trusted")
|
|
notSwapped(t, exe, "0.1.0")
|
|
}
|
|
|
|
func TestPinnedFingerprintMissingFromKeyFileIsRefused(t *testing.T) {
|
|
pinned := newKey(t, "Pinned <p@example.org>")
|
|
other := newKey(t, "Other <o@example.org>")
|
|
f := newForge(t, other, "v0.2.0")
|
|
u, exe := f.updater(t, "0.1.0", pinned.fpr)
|
|
_, err := u.Run(context.Background(), Options{})
|
|
wantErr(t, err, "pinned_fingerprint_not_in_keys_file")
|
|
notSwapped(t, exe, "0.1.0")
|
|
}
|
|
|
|
func TestTamperedPayloadIsRefused(t *testing.T) {
|
|
f := newForge(t, newKey(t, "Release <r@example.org>"), "v0.2.0")
|
|
f.mutate = func(f *forge, tag string, obj, ref map[string]any) {
|
|
if obj != nil {
|
|
v := obj["verification"].(map[string]any)
|
|
v["payload"] = strings.Replace(v["payload"].(string), "hub v0.2.0", "hub v0.2.0 evil", 1)
|
|
}
|
|
}
|
|
u, exe := f.updater(t, "0.1.0")
|
|
_, err := u.Run(context.Background(), Options{})
|
|
wantErr(t, err, "signature_bad")
|
|
notSwapped(t, exe, "0.1.0")
|
|
}
|
|
|
|
func TestValidSignatureOverAnotherCommitIsRefused(t *testing.T) {
|
|
// A genuine signature over a payload that names a different commit than the API object: replay of an old tag.
|
|
f := newForge(t, newKey(t, "Release <r@example.org>"), "v0.2.0")
|
|
f.mutate = func(f *forge, tag string, obj, ref map[string]any) {
|
|
if obj != nil {
|
|
obj["object"] = map[string]any{"type": "commit", "sha": "ffffffffffffffffffffffffffffffffffffffff"}
|
|
}
|
|
}
|
|
u, exe := f.updater(t, "0.1.0")
|
|
_, err := u.Run(context.Background(), Options{})
|
|
wantErr(t, err, "signed payload does not name")
|
|
notSwapped(t, exe, "0.1.0")
|
|
}
|
|
|
|
func TestLightweightTagIsRefused(t *testing.T) {
|
|
f := newForge(t, newKey(t, "Release <r@example.org>"), "v0.2.0")
|
|
f.mutate = func(f *forge, tag string, obj, ref map[string]any) {
|
|
if ref != nil {
|
|
ref["object"] = map[string]any{"type": "commit", "sha": commitSHA}
|
|
}
|
|
}
|
|
u, exe := f.updater(t, "0.1.0")
|
|
_, err := u.Run(context.Background(), Options{})
|
|
wantErr(t, err, "not an annotated, signed tag")
|
|
notSwapped(t, exe, "0.1.0")
|
|
}
|
|
|
|
func TestUnsignedAnnotatedTagIsRefused(t *testing.T) {
|
|
f := newForge(t, newKey(t, "Release <r@example.org>"), "v0.2.0")
|
|
f.mutate = func(f *forge, tag string, obj, ref map[string]any) {
|
|
if obj != nil {
|
|
obj["verification"] = map[string]any{"signature": "", "payload": ""}
|
|
}
|
|
}
|
|
u, exe := f.updater(t, "0.1.0")
|
|
_, err := u.Run(context.Background(), Options{})
|
|
wantErr(t, err, "no signature or payload")
|
|
notSwapped(t, exe, "0.1.0")
|
|
}
|
|
|
|
func TestShaMismatchIsRefused(t *testing.T) {
|
|
f := newForge(t, newKey(t, "Release <r@example.org>"), "v0.2.0")
|
|
f.shaFor = func(b []byte) string { return sum([]byte("something else")) }
|
|
u, exe := f.updater(t, "0.1.0")
|
|
_, err := u.Run(context.Background(), Options{})
|
|
wantErr(t, err, "sha256 mismatch")
|
|
notSwapped(t, exe, "0.1.0")
|
|
}
|
|
|
|
func TestMalformedShaFileIsRefused(t *testing.T) {
|
|
f := newForge(t, newKey(t, "Release <r@example.org>"), "v0.2.0")
|
|
f.shaFor = func(b []byte) string { return strings.ToUpper(sum(b)) } // uppercase hex is not the strict format
|
|
u, exe := f.updater(t, "0.1.0")
|
|
_, err := u.Run(context.Background(), Options{})
|
|
wantErr(t, err, "is not `<64 hex>")
|
|
notSwapped(t, exe, "0.1.0")
|
|
}
|
|
|
|
func TestOversizeAssetIsRefused(t *testing.T) {
|
|
f := newForge(t, newKey(t, "Release <r@example.org>"), "v0.2.0")
|
|
u, exe := f.updater(t, "0.1.0")
|
|
u.maxBinary = 8 // the listed size (about 20 bytes) is over the limit
|
|
_, err := u.Run(context.Background(), Options{})
|
|
wantErr(t, err, "unacceptable size")
|
|
notSwapped(t, exe, "0.1.0")
|
|
}
|
|
|
|
func TestOversizeBodyIsRefusedEvenIfTheListingLies(t *testing.T) {
|
|
f := newForge(t, newKey(t, "Release <r@example.org>"), "v0.2.0")
|
|
u, exe := f.updater(t, "0.1.0")
|
|
u.maxBinary = int64(len(script("0.2.0")))
|
|
f.asset = append(script("0.2.0"), bytes.Repeat([]byte("x"), 64)...) // served body is longer than the cap
|
|
// the listing reports the longer size too, so make the listing small: patch via handler wrapper
|
|
orig := f.srv.Config.Handler
|
|
f.srv.Config.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
if strings.HasSuffix(r.URL.Path, "/releases") || strings.Contains(r.URL.Path, "/releases/tags/") {
|
|
rec := httptest.NewRecorder()
|
|
orig.ServeHTTP(rec, r)
|
|
body := regexp.MustCompile(`"size":\d+`).ReplaceAll(rec.Body.Bytes(), []byte(`"size":10`))
|
|
_, _ = w.Write(body)
|
|
return
|
|
}
|
|
orig.ServeHTTP(w, r)
|
|
})
|
|
_, err := u.Run(context.Background(), Options{})
|
|
if err == nil {
|
|
t.Fatal("expected an error")
|
|
}
|
|
notSwapped(t, exe, "0.1.0")
|
|
}
|
|
|
|
func TestDowngradeRefusedUnlessVersionIsGiven(t *testing.T) {
|
|
f := newForge(t, newKey(t, "Release <r@example.org>"), "v0.1.0")
|
|
u, exe := f.updater(t, "0.2.0")
|
|
_, err := u.Run(context.Background(), Options{})
|
|
wantErr(t, err, "refusing downgrade")
|
|
notSwapped(t, exe, "0.2.0")
|
|
|
|
res, err := u.Run(context.Background(), Options{Tag: "v0.1.0"})
|
|
if err != nil || !res.Updated {
|
|
t.Fatalf("explicit --version must be allowed: %+v %v", res, err)
|
|
}
|
|
if got := content(t, exe); got != string(script("0.1.0")) {
|
|
t.Errorf("binary = %q", got)
|
|
}
|
|
}
|
|
|
|
func TestNewBinaryReportingAnotherVersionIsNotSwapped(t *testing.T) {
|
|
f := newForge(t, newKey(t, "Release <r@example.org>"), "v0.2.0")
|
|
f.asset = script("0.9.9") // tag says 0.2.0, binary says 0.9.9; the sha file matches the served bytes
|
|
u, exe := f.updater(t, "0.1.0")
|
|
_, err := u.Run(context.Background(), Options{})
|
|
wantErr(t, err, `reports "hub 0.9.9"`)
|
|
notSwapped(t, exe, "0.1.0")
|
|
}
|
|
|
|
func TestNewBinaryThatDoesNotRunIsNotSwapped(t *testing.T) {
|
|
f := newForge(t, newKey(t, "Release <r@example.org>"), "v0.2.0")
|
|
f.asset = []byte("#!/bin/sh\nexit 3\n")
|
|
u, exe := f.updater(t, "0.1.0")
|
|
_, err := u.Run(context.Background(), Options{})
|
|
wantErr(t, err, "does not run")
|
|
notSwapped(t, exe, "0.1.0")
|
|
}
|
|
|
|
func TestRedirectToAnotherHostIsNotFollowed(t *testing.T) {
|
|
other := 0
|
|
evil := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
other++
|
|
_, _ = w.Write(script("0.2.0"))
|
|
}))
|
|
defer evil.Close()
|
|
f := newForge(t, newKey(t, "Release <r@example.org>"), "v0.2.0")
|
|
f.redirect = evil.URL + "/payload"
|
|
u, exe := f.updater(t, "0.1.0")
|
|
// the client trusts both test servers' certificates, so only the redirect policy can stop this
|
|
pool := f.srv.Client().Transport.(*http.Transport).TLSClientConfig.RootCAs
|
|
for _, c := range evil.TLS.Certificates {
|
|
for _, der := range c.Certificate {
|
|
if cert, err := x509.ParseCertificate(der); err == nil {
|
|
pool.AddCert(cert)
|
|
}
|
|
}
|
|
}
|
|
_, err := u.Run(context.Background(), Options{})
|
|
wantErr(t, err, "refusing redirect")
|
|
if other != 0 {
|
|
t.Errorf("the other host was contacted %d times", other)
|
|
}
|
|
notSwapped(t, exe, "0.1.0")
|
|
}
|
|
|
|
func TestPlainHTTPForgeIsRefused(t *testing.T) {
|
|
u := New()
|
|
u.ForgeURL = "http://forge.example.org"
|
|
_, err := u.Run(context.Background(), Options{Check: true})
|
|
wantErr(t, err, "https")
|
|
}
|
|
|
|
func TestMissingGPGIsRefusedWithAClearMessage(t *testing.T) {
|
|
f := newForge(t, nil, "v0.2.0")
|
|
u, exe := f.updater(t, "0.1.0")
|
|
u.gpg = "definitely-not-a-gpg-binary"
|
|
_, err := u.Run(context.Background(), Options{})
|
|
wantErr(t, err, "gpg not found")
|
|
notSwapped(t, exe, "0.1.0")
|
|
if len(f.hits) != 0 {
|
|
t.Errorf("the forge must not be contacted before gpg is known: %v", f.hits)
|
|
}
|
|
}
|
|
|
|
func TestCheckReportsWithoutVerifyingOrWriting(t *testing.T) {
|
|
f := newForge(t, nil, "v0.2.0")
|
|
u, exe := f.updater(t, "0.1.0")
|
|
u.gpg = "definitely-not-a-gpg-binary" // --check needs no gpg
|
|
res, err := u.Run(context.Background(), Options{Check: true})
|
|
if err != nil || !res.UpdateAvailable || res.Updated || res.Verified {
|
|
t.Fatalf("res=%+v err=%v", res, err)
|
|
}
|
|
notSwapped(t, exe, "0.1.0")
|
|
for _, h := range f.hits {
|
|
if strings.Contains(h, "/git/") || strings.Contains(h, "/download/") {
|
|
t.Errorf("--check fetched %s", h)
|
|
}
|
|
}
|
|
u.Current = "0.2.0"
|
|
res, err = u.Run(context.Background(), Options{Check: true})
|
|
if err != nil || res.UpdateAvailable {
|
|
t.Fatalf("up to date: %+v %v", res, err)
|
|
}
|
|
}
|
|
|
|
func TestDraftAndPrereleaseAreNeverOffered(t *testing.T) {
|
|
f := newForge(t, nil, "v0.2.0") // the fake list also holds a draft v9.9.9 and a prerelease v8.8.8-rc.1
|
|
u, _ := f.updater(t, "0.1.0")
|
|
res, err := u.Run(context.Background(), Options{Check: true})
|
|
if err != nil || res.Latest != "v0.2.0" {
|
|
t.Fatalf("res=%+v err=%v", res, err)
|
|
}
|
|
}
|
|
|
|
func TestDevBuildCountsAsOlderThanAnyRelease(t *testing.T) {
|
|
f := newForge(t, nil, "v0.0.1")
|
|
u, _ := f.updater(t, "0.0.0-dev+abc1234")
|
|
res, err := u.Run(context.Background(), Options{Check: true})
|
|
if err != nil || !res.UpdateAvailable {
|
|
t.Fatalf("res=%+v err=%v", res, err)
|
|
}
|
|
}
|
|
|
|
func TestBadVersionFlagIsRefused(t *testing.T) {
|
|
u := New()
|
|
for _, tag := range []string{"0.2.0", "v1.2", "v1.2.3-rc.1", "../x"} {
|
|
_, err := u.Run(context.Background(), Options{Tag: tag})
|
|
wantErr(t, err, "--version")
|
|
}
|
|
}
|
|
|
|
func TestVersionComparison(t *testing.T) {
|
|
a, _ := parseTag("v1.10.0")
|
|
b, _ := parseTag("v1.9.9")
|
|
if a.cmp(b) != 1 || b.cmp(a) != -1 || a.cmp(a) != 0 {
|
|
t.Error("numeric, not lexical, comparison expected")
|
|
}
|
|
if parseCurrent("0.0.0-dev+abc1234") != (version{}) || parseCurrent("1.2.3") != (version{1, 2, 3}) || parseCurrent("garbage") != (version{}) {
|
|
t.Error("parseCurrent")
|
|
}
|
|
}
|
|
|
|
func TestParsePayloadTakesHeaderOnly(t *testing.T) {
|
|
p := "object aaa\ntype commit\ntag v1.0.0\ntagger x\n\nobject injected\ntag v9.9.9\n"
|
|
got := parsePayload(p)
|
|
if got["object"] != "aaa" || got["tag"] != "v1.0.0" || got["type"] != "commit" {
|
|
t.Errorf("payload fields = %v", got)
|
|
}
|
|
}
|