// Package release verifies and installs gateway binaries. // // A gateway that updates itself is a remote code execution channel, so the shape matters more // than the convenience: a release is a signed manifest that names each artifact by hash, the // download is verified before it is written next to the running binary, and the swap is a rename // so a failed download leaves the running gateway untouched. The previous binary is kept, so a // bad release is a rollback away. package release import ( "context" "crypto/ed25519" "crypto/sha256" "encoding/hex" "encoding/json" "errors" "fmt" "io" "net/http" "os" "path/filepath" "strconv" "strings" "time" ) // Errors a caller must treat as "do not swap the binary". var ( // ErrSignature is a manifest whose signature does not verify. ErrSignature = errors.New("release: the manifest signature does not verify") // ErrDigest is an artifact whose bytes do not hash to the manifest's digest. ErrDigest = errors.New("release: the artifact does not match its digest") // ErrVersion is a release that is not newer than what is running. ErrVersion = errors.New("release: the release is not newer") // ErrArch is a release with no artifact for this machine. ErrArch = errors.New("release: no artifact for this platform") ) // Artifact is one binary in a release. type Artifact struct { OS string `json:"os"` Arch string `json:"arch"` URL string `json:"url"` SHA256 string `json:"sha256"` Size int64 `json:"size,omitempty"` } // Manifest is what a release publishes, from a URL the operator configured. type Manifest struct { Version string `json:"version"` Published string `json:"published,omitempty"` Artifacts []Artifact `json:"artifacts"` // MinVersion refuses a downgrade below it: a release that requires a migration can say so. MinVersion string `json:"min_version,omitempty"` // Notes is shown to the operator before installing. Notes string `json:"notes,omitempty"` } // Signed is the wire form: the manifest bytes and their signature over exactly those bytes. type Signed struct { Manifest json.RawMessage `json:"manifest"` Signature string `json:"signature"` } // Verify checks the signature and decodes the manifest. The signature covers the manifest bytes // as published, not a re-encoding, so what was signed is what is read. func Verify(signed []byte, public ed25519.PublicKey) (Manifest, []byte, error) { var envelope Signed if err := json.Unmarshal(signed, &envelope); err != nil { return Manifest{}, nil, fmt.Errorf("release: the signed manifest is not JSON: %w", err) } signature, err := hex.DecodeString(strings.TrimSpace(envelope.Signature)) if err != nil || len(signature) != ed25519.SignatureSize { return Manifest{}, nil, fmt.Errorf("%w: the signature is not %d bytes of hex", ErrSignature, ed25519.SignatureSize) } if !ed25519.Verify(public, envelope.Manifest, signature) { return Manifest{}, nil, ErrSignature } var manifest Manifest if err := json.Unmarshal(envelope.Manifest, &manifest); err != nil { return Manifest{}, nil, fmt.Errorf("release: the manifest is not JSON: %w", err) } if manifest.Version == "" { return Manifest{}, nil, errors.New("release: the manifest has no version") } return manifest, envelope.Manifest, nil } // Fetch downloads the signed manifest from url. func Fetch(ctx context.Context, client *http.Client, url string) ([]byte, error) { if client == nil { client = &http.Client{Timeout: 20 * time.Second} } request, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) if err != nil { return nil, err } response, err := client.Do(request) if err != nil { return nil, fmt.Errorf("release: fetch manifest: %w", err) } defer response.Body.Close() if response.StatusCode != http.StatusOK { return nil, fmt.Errorf("release: fetch manifest: HTTP %d", response.StatusCode) } return io.ReadAll(io.LimitReader(response.Body, 1<<20)) } // Choose picks the artifact for this platform. func (m Manifest) Choose(goos, goarch string) (Artifact, error) { for _, artifact := range m.Artifacts { if artifact.OS == goos && artifact.Arch == goarch { return artifact, nil } } return Artifact{}, fmt.Errorf("%w: %s/%s", ErrArch, goos, goarch) } // Download fetches an artifact and verifies it against the manifest. It returns the bytes so the // caller can install them; nothing is written to the binary's directory until Install. func Download(ctx context.Context, client *http.Client, artifact Artifact) ([]byte, error) { if client == nil { client = &http.Client{Timeout: 2 * time.Minute} } request, err := http.NewRequestWithContext(ctx, http.MethodGet, artifact.URL, nil) if err != nil { return nil, err } response, err := client.Do(request) if err != nil { return nil, fmt.Errorf("release: download %s: %w", artifact.URL, err) } defer response.Body.Close() if response.StatusCode != http.StatusOK { return nil, fmt.Errorf("release: download %s: HTTP %d", artifact.URL, response.StatusCode) } // A ceiling so a hostile URL cannot fill the disk: 128 MiB is far above a static binary. body, err := io.ReadAll(io.LimitReader(response.Body, 128<<20)) if err != nil { return nil, fmt.Errorf("release: download %s: %w", artifact.URL, err) } sum := sha256.Sum256(body) if !strings.EqualFold(hex.EncodeToString(sum[:]), artifact.SHA256) { return nil, fmt.Errorf("%w: %s hashes to %x", ErrDigest, artifact.URL, sum) } if artifact.Size > 0 && int64(len(body)) != artifact.Size { return nil, fmt.Errorf("%w: %s is %d bytes, the manifest says %d", ErrDigest, artifact.URL, len(body), artifact.Size) } return body, nil } // Install stages the bytes beside path and renames them into place, keeping the previous binary as // path+".prev". A caller that cannot restart itself can still have installed the file. func Install(path string, body []byte) (previous string, err error) { dir := filepath.Dir(path) stage, err := os.CreateTemp(dir, ".nostrino-new-*") if err != nil { return "", fmt.Errorf("release: stage: %w", err) } stageName := stage.Name() defer func() { if err != nil { os.Remove(stageName) } }() if _, err = stage.Write(body); err != nil { stage.Close() return "", fmt.Errorf("release: write %s: %w", stageName, err) } if err = stage.Sync(); err != nil { stage.Close() return "", fmt.Errorf("release: fsync %s: %w", stageName, err) } if err = stage.Close(); err != nil { return "", err } if err = os.Chmod(stageName, 0o755); err != nil { return "", fmt.Errorf("release: chmod: %w", err) } // Keep the running binary so a release that will not start can be rolled back. previous = path + ".prev" if err = copyFile(path, previous); err != nil { return "", fmt.Errorf("release: keep the previous binary: %w", err) } if err = os.Rename(stageName, path); err != nil { return "", fmt.Errorf("release: install: %w", err) } return previous, nil } // Rollback puts the previous binary back. func Rollback(path string) error { return os.Rename(path+".prev", path) } func copyFile(from, to string) error { in, err := os.Open(from) if err != nil { return err } defer in.Close() out, err := os.Create(to) if err != nil { return err } if _, err := io.Copy(out, in); err != nil { out.Close() return err } if err := out.Sync(); err != nil { out.Close() return err } return out.Close() } // Compare orders two version strings numerically per dotted field, so 0.2.10 is newer than 0.2.9. // A leading "v" and any pre-release suffix are ignored: a gateway wants a monotonic number, not a // full semver range. func Compare(a, b string) int { split := func(text string) []int { text = strings.TrimPrefix(strings.TrimSpace(text), "v") if i := strings.IndexAny(text, "-+"); i >= 0 { text = text[:i] } parts := strings.Split(text, ".") out := make([]int, 0, len(parts)) for _, part := range parts { value, err := strconv.Atoi(part) if err != nil { value = 0 } out = append(out, value) } return out } left, right := split(a), split(b) for i := 0; i < len(left) || i < len(right); i++ { var l, r int if i < len(left) { l = left[i] } if i < len(right) { r = right[i] } if l != r { if l < r { return -1 } return 1 } } return 0 } // Newer refuses a release that is not above the running version, or below a floor the release sets. func Newer(running string, manifest Manifest) error { if Compare(manifest.Version, running) <= 0 { return fmt.Errorf("%w: %s is not newer than %s", ErrVersion, manifest.Version, running) } if manifest.MinVersion != "" && Compare(running, manifest.MinVersion) < 0 { return fmt.Errorf("%w: %s needs at least %s, this is %s", ErrVersion, manifest.Version, manifest.MinVersion, running) } return nil } // SHA256Hex is the digest form a manifest publishes. func SHA256Hex(body []byte) (string, error) { sum := sha256.Sum256(body) return hex.EncodeToString(sum[:]), nil }