release.go raw

   1  // Package release verifies and installs gateway binaries.
   2  //
   3  // A gateway that updates itself is a remote code execution channel, so the shape matters more
   4  // than the convenience: a release is a signed manifest that names each artifact by hash, the
   5  // download is verified before it is written next to the running binary, and the swap is a rename
   6  // so a failed download leaves the running gateway untouched. The previous binary is kept, so a
   7  // bad release is a rollback away.
   8  package release
   9  
  10  import (
  11  	"context"
  12  	"crypto/ed25519"
  13  	"crypto/sha256"
  14  	"encoding/hex"
  15  	"encoding/json"
  16  	"errors"
  17  	"fmt"
  18  	"io"
  19  	"net/http"
  20  	"os"
  21  	"path/filepath"
  22  	"strconv"
  23  	"strings"
  24  	"time"
  25  )
  26  
  27  // Errors a caller must treat as "do not swap the binary".
  28  var (
  29  	// ErrSignature is a manifest whose signature does not verify.
  30  	ErrSignature = errors.New("release: the manifest signature does not verify")
  31  	// ErrDigest is an artifact whose bytes do not hash to the manifest's digest.
  32  	ErrDigest = errors.New("release: the artifact does not match its digest")
  33  	// ErrVersion is a release that is not newer than what is running.
  34  	ErrVersion = errors.New("release: the release is not newer")
  35  	// ErrArch is a release with no artifact for this machine.
  36  	ErrArch = errors.New("release: no artifact for this platform")
  37  )
  38  
  39  // Artifact is one binary in a release.
  40  type Artifact struct {
  41  	OS     string `json:"os"`
  42  	Arch   string `json:"arch"`
  43  	URL    string `json:"url"`
  44  	SHA256 string `json:"sha256"`
  45  	Size   int64  `json:"size,omitempty"`
  46  }
  47  
  48  // Manifest is what a release publishes, from a URL the operator configured.
  49  type Manifest struct {
  50  	Version   string     `json:"version"`
  51  	Published string     `json:"published,omitempty"`
  52  	Artifacts []Artifact `json:"artifacts"`
  53  	// MinVersion refuses a downgrade below it: a release that requires a migration can say so.
  54  	MinVersion string `json:"min_version,omitempty"`
  55  	// Notes is shown to the operator before installing.
  56  	Notes string `json:"notes,omitempty"`
  57  }
  58  
  59  // Signed is the wire form: the manifest bytes and their signature over exactly those bytes.
  60  type Signed struct {
  61  	Manifest  json.RawMessage `json:"manifest"`
  62  	Signature string          `json:"signature"`
  63  }
  64  
  65  // Verify checks the signature and decodes the manifest. The signature covers the manifest bytes
  66  // as published, not a re-encoding, so what was signed is what is read.
  67  func Verify(signed []byte, public ed25519.PublicKey) (Manifest, []byte, error) {
  68  	var envelope Signed
  69  
  70  	if err := json.Unmarshal(signed, &envelope); err != nil {
  71  		return Manifest{}, nil, fmt.Errorf("release: the signed manifest is not JSON: %w", err)
  72  	}
  73  
  74  	signature, err := hex.DecodeString(strings.TrimSpace(envelope.Signature))
  75  
  76  	if err != nil || len(signature) != ed25519.SignatureSize {
  77  		return Manifest{}, nil, fmt.Errorf("%w: the signature is not %d bytes of hex",
  78  			ErrSignature, ed25519.SignatureSize)
  79  	}
  80  
  81  	if !ed25519.Verify(public, envelope.Manifest, signature) {
  82  		return Manifest{}, nil, ErrSignature
  83  	}
  84  
  85  	var manifest Manifest
  86  
  87  	if err := json.Unmarshal(envelope.Manifest, &manifest); err != nil {
  88  		return Manifest{}, nil, fmt.Errorf("release: the manifest is not JSON: %w", err)
  89  	}
  90  
  91  	if manifest.Version == "" {
  92  		return Manifest{}, nil, errors.New("release: the manifest has no version")
  93  	}
  94  
  95  	return manifest, envelope.Manifest, nil
  96  }
  97  
  98  // Fetch downloads the signed manifest from url.
  99  func Fetch(ctx context.Context, client *http.Client, url string) ([]byte, error) {
 100  	if client == nil {
 101  		client = &http.Client{Timeout: 20 * time.Second}
 102  	}
 103  
 104  	request, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
 105  
 106  	if err != nil {
 107  		return nil, err
 108  	}
 109  
 110  	response, err := client.Do(request)
 111  
 112  	if err != nil {
 113  		return nil, fmt.Errorf("release: fetch manifest: %w", err)
 114  	}
 115  
 116  	defer response.Body.Close()
 117  
 118  	if response.StatusCode != http.StatusOK {
 119  		return nil, fmt.Errorf("release: fetch manifest: HTTP %d", response.StatusCode)
 120  	}
 121  
 122  	return io.ReadAll(io.LimitReader(response.Body, 1<<20))
 123  }
 124  
 125  // Choose picks the artifact for this platform.
 126  func (m Manifest) Choose(goos, goarch string) (Artifact, error) {
 127  	for _, artifact := range m.Artifacts {
 128  		if artifact.OS == goos && artifact.Arch == goarch {
 129  			return artifact, nil
 130  		}
 131  	}
 132  
 133  	return Artifact{}, fmt.Errorf("%w: %s/%s", ErrArch, goos, goarch)
 134  }
 135  
 136  // Download fetches an artifact and verifies it against the manifest. It returns the bytes so the
 137  // caller can install them; nothing is written to the binary's directory until Install.
 138  func Download(ctx context.Context, client *http.Client, artifact Artifact) ([]byte, error) {
 139  	if client == nil {
 140  		client = &http.Client{Timeout: 2 * time.Minute}
 141  	}
 142  
 143  	request, err := http.NewRequestWithContext(ctx, http.MethodGet, artifact.URL, nil)
 144  
 145  	if err != nil {
 146  		return nil, err
 147  	}
 148  
 149  	response, err := client.Do(request)
 150  
 151  	if err != nil {
 152  		return nil, fmt.Errorf("release: download %s: %w", artifact.URL, err)
 153  	}
 154  
 155  	defer response.Body.Close()
 156  
 157  	if response.StatusCode != http.StatusOK {
 158  		return nil, fmt.Errorf("release: download %s: HTTP %d", artifact.URL, response.StatusCode)
 159  	}
 160  
 161  	// A ceiling so a hostile URL cannot fill the disk: 128 MiB is far above a static binary.
 162  	body, err := io.ReadAll(io.LimitReader(response.Body, 128<<20))
 163  
 164  	if err != nil {
 165  		return nil, fmt.Errorf("release: download %s: %w", artifact.URL, err)
 166  	}
 167  
 168  	sum := sha256.Sum256(body)
 169  
 170  	if !strings.EqualFold(hex.EncodeToString(sum[:]), artifact.SHA256) {
 171  		return nil, fmt.Errorf("%w: %s hashes to %x", ErrDigest, artifact.URL, sum)
 172  	}
 173  
 174  	if artifact.Size > 0 && int64(len(body)) != artifact.Size {
 175  		return nil, fmt.Errorf("%w: %s is %d bytes, the manifest says %d",
 176  			ErrDigest, artifact.URL, len(body), artifact.Size)
 177  	}
 178  
 179  	return body, nil
 180  }
 181  
 182  // Install stages the bytes beside path and renames them into place, keeping the previous binary as
 183  // path+".prev". A caller that cannot restart itself can still have installed the file.
 184  func Install(path string, body []byte) (previous string, err error) {
 185  	dir := filepath.Dir(path)
 186  
 187  	stage, err := os.CreateTemp(dir, ".nostrino-new-*")
 188  
 189  	if err != nil {
 190  		return "", fmt.Errorf("release: stage: %w", err)
 191  	}
 192  
 193  	stageName := stage.Name()
 194  
 195  	defer func() {
 196  		if err != nil {
 197  			os.Remove(stageName)
 198  		}
 199  	}()
 200  
 201  	if _, err = stage.Write(body); err != nil {
 202  		stage.Close()
 203  		return "", fmt.Errorf("release: write %s: %w", stageName, err)
 204  	}
 205  
 206  	if err = stage.Sync(); err != nil {
 207  		stage.Close()
 208  		return "", fmt.Errorf("release: fsync %s: %w", stageName, err)
 209  	}
 210  
 211  	if err = stage.Close(); err != nil {
 212  		return "", err
 213  	}
 214  
 215  	if err = os.Chmod(stageName, 0o755); err != nil {
 216  		return "", fmt.Errorf("release: chmod: %w", err)
 217  	}
 218  
 219  	// Keep the running binary so a release that will not start can be rolled back.
 220  	previous = path + ".prev"
 221  
 222  	if err = copyFile(path, previous); err != nil {
 223  		return "", fmt.Errorf("release: keep the previous binary: %w", err)
 224  	}
 225  
 226  	if err = os.Rename(stageName, path); err != nil {
 227  		return "", fmt.Errorf("release: install: %w", err)
 228  	}
 229  
 230  	return previous, nil
 231  }
 232  
 233  // Rollback puts the previous binary back.
 234  func Rollback(path string) error {
 235  	return os.Rename(path+".prev", path)
 236  }
 237  
 238  func copyFile(from, to string) error {
 239  	in, err := os.Open(from)
 240  
 241  	if err != nil {
 242  		return err
 243  	}
 244  
 245  	defer in.Close()
 246  
 247  	out, err := os.Create(to)
 248  
 249  	if err != nil {
 250  		return err
 251  	}
 252  
 253  	if _, err := io.Copy(out, in); err != nil {
 254  		out.Close()
 255  		return err
 256  	}
 257  
 258  	if err := out.Sync(); err != nil {
 259  		out.Close()
 260  		return err
 261  	}
 262  
 263  	return out.Close()
 264  }
 265  
 266  // Compare orders two version strings numerically per dotted field, so 0.2.10 is newer than 0.2.9.
 267  // A leading "v" and any pre-release suffix are ignored: a gateway wants a monotonic number, not a
 268  // full semver range.
 269  func Compare(a, b string) int {
 270  	split := func(text string) []int {
 271  		text = strings.TrimPrefix(strings.TrimSpace(text), "v")
 272  
 273  		if i := strings.IndexAny(text, "-+"); i >= 0 {
 274  			text = text[:i]
 275  		}
 276  
 277  		parts := strings.Split(text, ".")
 278  		out := make([]int, 0, len(parts))
 279  
 280  		for _, part := range parts {
 281  			value, err := strconv.Atoi(part)
 282  
 283  			if err != nil {
 284  				value = 0
 285  			}
 286  
 287  			out = append(out, value)
 288  		}
 289  
 290  		return out
 291  	}
 292  
 293  	left, right := split(a), split(b)
 294  
 295  	for i := 0; i < len(left) || i < len(right); i++ {
 296  		var l, r int
 297  
 298  		if i < len(left) {
 299  			l = left[i]
 300  		}
 301  
 302  		if i < len(right) {
 303  			r = right[i]
 304  		}
 305  
 306  		if l != r {
 307  			if l < r {
 308  				return -1
 309  			}
 310  
 311  			return 1
 312  		}
 313  	}
 314  
 315  	return 0
 316  }
 317  
 318  // Newer refuses a release that is not above the running version, or below a floor the release sets.
 319  func Newer(running string, manifest Manifest) error {
 320  	if Compare(manifest.Version, running) <= 0 {
 321  		return fmt.Errorf("%w: %s is not newer than %s", ErrVersion, manifest.Version, running)
 322  	}
 323  
 324  	if manifest.MinVersion != "" && Compare(running, manifest.MinVersion) < 0 {
 325  		return fmt.Errorf("%w: %s needs at least %s, this is %s",
 326  			ErrVersion, manifest.Version, manifest.MinVersion, running)
 327  	}
 328  
 329  	return nil
 330  }
 331  
 332  // SHA256Hex is the digest form a manifest publishes.
 333  func SHA256Hex(body []byte) (string, error) {
 334  	sum := sha256.Sum256(body)
 335  	return hex.EncodeToString(sum[:]), nil
 336  }
 337