internal/deps/registry.go

545ba0bcdea3b534903bd78c918c0c025a97eda7
gitbay/internal/deps/registry.go

138 lines · 3787 bytes

8 symbols in this file
  1package deps
  2
  3import (
  4	"context"
  5	"encoding/json"
  6	"fmt"
  7	"io"
  8	"net/http"
  9	"regexp"
 10	"strings"
 11	"time"
 12)
 13
 14// Registry endpoints. Each is a fixed public host: unlike webhooks and
 15// mirrors, no part of the URL comes from user input except the package
 16// name, and safeName restricts that to characters that need no escaping in
 17// a URL path.
 18var endpoints = map[string]string{
 19	EcoGo:    "https://proxy.golang.org",
 20	EcoNPM:   "https://registry.npmjs.org",
 21	EcoCargo: "https://crates.io/api/v1/crates",
 22	EcoPyPI:  "https://pypi.org/pypi",
 23}
 24
 25// maxBody bounds a registry response. The npm packument is the large one,
 26// which is why the abbreviated metadata is requested.
 27const maxBody = 4 << 20
 28
 29// safeName is the shape a package name may have before it goes into a URL.
 30var safeName = regexp.MustCompile(`^@?[A-Za-z0-9][A-Za-z0-9._/@+-]*$`)
 31
 32// Client queries package registries. The zero value is not usable; call
 33// NewClient.
 34type Client struct {
 35	HTTP    *http.Client
 36	Hosts   map[string]string // overridden in tests
 37	OSV     string            // osvAPI unless overridden in tests
 38	Version string            // reported in User-Agent
 39}
 40
 41func NewClient(version string) *Client {
 42	return &Client{
 43		HTTP:    &http.Client{Timeout: 20 * time.Second},
 44		Hosts:   endpoints,
 45		Version: version,
 46	}
 47}
 48
 49// Latest returns the current release of one package. A prerelease is
 50// reported as no answer: nothing should be nudged onto an rc.
 51func (c *Client) Latest(ctx context.Context, eco, name string) (string, error) {
 52	base, ok := c.Hosts[eco]
 53	if !ok {
 54		return "", fmt.Errorf("unknown ecosystem %q", eco)
 55	}
 56	if !safeName.MatchString(name) || strings.Contains(name, "..") {
 57		return "", fmt.Errorf("unusable package name %q", name)
 58	}
 59	var path, accept string
 60	switch eco {
 61	case EcoGo:
 62		path = "/" + escapeModule(name) + "/@latest"
 63	case EcoNPM:
 64		path = "/" + name
 65		accept = "application/vnd.npm.install-v1+json" // dist-tags, not the full packument
 66	case EcoCargo:
 67		path = "/" + name
 68	case EcoPyPI:
 69		path = "/" + name + "/json"
 70	}
 71	body, err := c.get(ctx, base+path, accept)
 72	if err != nil {
 73		return "", err
 74	}
 75	var doc struct {
 76		Version  string            `json:"Version"`   // go
 77		DistTags map[string]string `json:"dist-tags"` // npm
 78		Crate    struct {
 79			MaxStableVersion string `json:"max_stable_version"`
 80		} `json:"crate"` // cargo
 81		Info struct {
 82			Version string `json:"version"`
 83		} `json:"info"` // pypi
 84	}
 85	if err := json.Unmarshal(body, &doc); err != nil {
 86		return "", fmt.Errorf("%s %s: %w", eco, name, err)
 87	}
 88	var latest string
 89	switch eco {
 90	case EcoGo:
 91		latest = doc.Version
 92	case EcoNPM:
 93		latest = doc.DistTags["latest"]
 94	case EcoCargo:
 95		latest = doc.Crate.MaxStableVersion
 96	case EcoPyPI:
 97		latest = doc.Info.Version
 98	}
 99	if latest == "" || IsPrerelease(latest) {
100		return "", nil
101	}
102	return latest, nil
103}
104
105func (c *Client) get(ctx context.Context, u, accept string) ([]byte, error) {
106	req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil)
107	if err != nil {
108		return nil, err
109	}
110	req.Header.Set("User-Agent", "gitbay/"+c.Version+" (+https://gitbay.org)")
111	if accept != "" {
112		req.Header.Set("Accept", accept)
113	}
114	resp, err := c.HTTP.Do(req)
115	if err != nil {
116		return nil, err
117	}
118	defer resp.Body.Close()
119	if resp.StatusCode != http.StatusOK {
120		return nil, fmt.Errorf("%s: %s", u, resp.Status)
121	}
122	return io.ReadAll(io.LimitReader(resp.Body, maxBody))
123}
124
125// escapeModule applies the module proxy's case encoding: an uppercase
126// letter becomes "!" followed by its lowercase form, so paths stay distinct
127// on case-insensitive filesystems.
128func escapeModule(path string) string {
129	var b strings.Builder
130	for _, r := range path {
131		if r >= 'A' && r <= 'Z' {
132			b.WriteByte('!')
133			r += 'a' - 'A'
134		}
135		b.WriteRune(r)
136	}
137	return b.String()
138}