diff --git a/internal/handler/chef.go b/internal/handler/chef.go index 24fa1d8c..b7a77c46 100644 --- a/internal/handler/chef.go +++ b/internal/handler/chef.go @@ -1,39 +1,30 @@ package handler import ( - "bytes" "crypto/sha256" "encoding/hex" "encoding/json" "errors" - "fmt" "net/http" "net/url" - "path" "regexp" "strings" + + "github.com/git-pkgs/proxy/internal/metadata/chef" ) const ( chefEcosystem = "chef" - chefMountPath = "/chef" - chefAPIPath = "/api/v1" + chefAPIPath = chef.APIPath // chefUpstreamKeyLength is how much of the upstream URL's digest scopes // metadata cache keys and archive filenames: enough to keep two upstreams // apart. chefUpstreamKeyLength = 16 ) -var ( - // chefCookbookName matches Supermarket cookbook names: letters, digits, - // hyphens, underscores and dots, not starting with a dot. - chefCookbookName = regexp.MustCompile(`^[A-Za-z0-9_-][A-Za-z0-9_.-]*$`) - // chefVersion matches Chef cookbook versions, which have two or three - // numeric parts. - chefVersion = regexp.MustCompile(`^[0-9]+\.[0-9]+(\.[0-9]+)?$`) - - errChefDocument = errors.New("unexpected Chef Supermarket document") -) +// chefCookbookName matches Supermarket cookbook names: letters, digits, +// hyphens, underscores and dots, not starting with a dot. +var chefCookbookName = regexp.MustCompile(`^[A-Za-z0-9_-][A-Za-z0-9_.-]*$`) // ChefHandler serves a read-only Chef Supermarket at /chef. Berkshelf and // Policyfiles resolve dependencies against /universe and then download each @@ -167,127 +158,25 @@ func (h *ChefHandler) serveDocument(w http.ResponseWriter, r *http.Request, docu } // rewriteUniverse points every version's location_path and download_url at -// the proxy. The universe maps cookbook names to versions to their location -// and dependencies; dependencies and any other field are copied as they are. +// the proxy; see chef.RewriteUniverse. func (h *ChefHandler) rewriteUniverse(body []byte) ([]byte, error) { - var universe map[string]map[string]map[string]json.RawMessage - if err := json.Unmarshal(body, &universe); err != nil { - return nil, fmt.Errorf("%w: universe: %w", errChefDocument, err) - } - - locationPath, err := jsonString(h.apiURL()) - if err != nil { - return nil, err - } - for name, versions := range universe { - for version, entry := range versions { - if entry == nil { - continue - } - downloadURL, err := jsonString(h.downloadURL(name, version)) - if err != nil { - return nil, err - } - entry["location_path"] = locationPath - entry["download_url"] = downloadURL - } - } - return encodeChefJSON(universe) + return chef.RewriteUniverse(body, h.rewriteOptions()) } -// rewriteCookbook points a cookbook's version URLs at the proxy. +// rewriteCookbook points a cookbook's version URLs at the proxy; see +// chef.RewriteCookbook. func (h *ChefHandler) rewriteCookbook(name string, body []byte) ([]byte, error) { - var cookbook map[string]json.RawMessage - if err := json.Unmarshal(body, &cookbook); err != nil { - return nil, fmt.Errorf("%w: cookbook %s: %w", errChefDocument, name, err) - } - - if raw, ok := cookbook["latest_version"]; ok { - rewritten, err := h.rewriteVersionURL(name, raw) - if err != nil { - return nil, err - } - cookbook["latest_version"] = rewritten - } - if raw, ok := cookbook["versions"]; ok { - var versions []json.RawMessage - if err := json.Unmarshal(raw, &versions); err != nil { - return nil, fmt.Errorf("%w: cookbook %s versions: %w", errChefDocument, name, err) - } - for i, versionURL := range versions { - rewritten, err := h.rewriteVersionURL(name, versionURL) - if err != nil { - return nil, err - } - versions[i] = rewritten - } - encoded, err := encodeChefJSON(versions) - if err != nil { - return nil, err - } - cookbook["versions"] = encoded - } - return encodeChefJSON(cookbook) + return chef.RewriteCookbook(name, body, h.rewriteOptions()) } // rewriteVersion points a cookbook version's cookbook and file URLs at the -// proxy. +// proxy; see chef.RewriteVersion. func (h *ChefHandler) rewriteVersion(name, version string, body []byte) ([]byte, error) { - var document map[string]json.RawMessage - if err := json.Unmarshal(body, &document); err != nil { - return nil, fmt.Errorf("%w: cookbook %s version %s: %w", errChefDocument, name, version, err) - } - - if _, ok := document["cookbook"]; ok { - cookbookURL, err := jsonString(h.cookbookURL(name)) - if err != nil { - return nil, err - } - document["cookbook"] = cookbookURL - } - if _, ok := document["file"]; ok { - fileURL, err := jsonString(h.downloadURL(name, version)) - if err != nil { - return nil, err - } - document["file"] = fileURL - } - return encodeChefJSON(document) -} - -// rewriteVersionURL rewrites an upstream cookbook version URL, a JSON string -// ending in /versions/{version}, to the proxy. Anything else, such as null, -// is returned unchanged. -func (h *ChefHandler) rewriteVersionURL(name string, raw json.RawMessage) (json.RawMessage, error) { - var versionURL string - if err := json.Unmarshal(raw, &versionURL); err != nil { - return raw, nil //nolint:nilerr // not a string, so not a URL to rewrite - } - parsed, err := url.Parse(versionURL) - if err != nil { - return raw, nil //nolint:nilerr // not a URL, so nothing to rewrite - } - version, ok := normalizeChefVersion(path.Base(parsed.Path)) - if !ok { - return raw, nil - } - return jsonString(h.versionURL(name, version)) -} - -func (h *ChefHandler) apiURL() string { - return h.proxyURL + chefMountPath + chefAPIPath -} - -func (h *ChefHandler) cookbookURL(name string) string { - return h.apiURL() + "/cookbooks/" + url.PathEscape(name) -} - -func (h *ChefHandler) versionURL(name, version string) string { - return h.cookbookURL(name) + "/versions/" + url.PathEscape(version) + return chef.RewriteVersion(name, version, body, h.rewriteOptions()) } -func (h *ChefHandler) downloadURL(name, version string) string { - return h.versionURL(name, version) + "/download" +func (h *ChefHandler) rewriteOptions() chef.Options { + return chef.Options{ProxyURL: h.proxyURL} } func (h *ChefHandler) upstreamCookbookURL(name string) string { @@ -327,29 +216,14 @@ func chefVersionFromRequest(r *http.Request) (name, version string, ok bool) { return name, version, ok } -// normalizeChefVersion accepts a version in either form Supermarket serves -// (1.2.3, or 1_2_3 as Berkshelf writes it in URLs) and returns the dotted -// form. +// normalizeChefVersion returns a cookbook version in its dotted form; see +// chef.NormalizeVersion. func normalizeChefVersion(version string) (string, bool) { - version = strings.ReplaceAll(version, "_", ".") - if !chefVersion.MatchString(version) { - return "", false - } - return version, true + return chef.NormalizeVersion(version) } -func jsonString(s string) (json.RawMessage, error) { - return encodeChefJSON(s) -} - -// encodeChefJSON encodes v without escaping HTML characters, so dependency -// constraints such as ">= 1.0" keep their upstream spelling. +// encodeChefJSON encodes v without escaping HTML characters; see +// chef.EncodeJSON. func encodeChefJSON(v any) (json.RawMessage, error) { - var buf bytes.Buffer - enc := json.NewEncoder(&buf) - enc.SetEscapeHTML(false) - if err := enc.Encode(v); err != nil { - return nil, err - } - return bytes.TrimSuffix(buf.Bytes(), []byte("\n")), nil + return chef.EncodeJSON(v) } diff --git a/internal/metadata/chef/imports_test.go b/internal/metadata/chef/imports_test.go new file mode 100644 index 00000000..51f230ec --- /dev/null +++ b/internal/metadata/chef/imports_test.go @@ -0,0 +1,38 @@ +package chef + +import ( + "os/exec" + "slices" + "strings" + "testing" +) + +// TestPortableImports keeps the package free of the proxy's infrastructure: +// no handler, database, storage, metrics, HTTP or logging, so it builds for +// targets such as WASI where those are not available. +func TestPortableImports(t *testing.T) { + goTool, err := exec.LookPath("go") + if err != nil { + t.Skip("go tool not found") + } + out, err := exec.Command(goTool, "list", "-deps", "-f", "{{.Standard}} {{.ImportPath}}", ".").Output() + if err != nil { + t.Fatalf("go list: %v", err) + } + allowed := []string{ + "github.com/git-pkgs/proxy/internal/metadata/chef", + } + forbiddenStd := []string{"database/sql", "log/slog", "net", "net/http"} + for line := range strings.Lines(string(out)) { + standard, path, _ := strings.Cut(strings.TrimSpace(line), " ") + if standard == "true" { + if slices.Contains(forbiddenStd, path) { + t.Errorf("imports %s", path) + } + continue + } + if !slices.Contains(allowed, path) { + t.Errorf("imports %s, which is not on the portable list", path) + } + } +} diff --git a/internal/metadata/chef/metadata.go b/internal/metadata/chef/metadata.go new file mode 100644 index 00000000..b1442da4 --- /dev/null +++ b/internal/metadata/chef/metadata.go @@ -0,0 +1,191 @@ +// Package chef rewrites Chef Supermarket documents so every download +// location points at the proxy. It depends on nothing but the standard +// library, so it builds for targets such as WASI. +package chef + +import ( + "bytes" + "encoding/json" + "errors" + "fmt" + "net/url" + "path" + "regexp" + "strings" +) + +// MountPath and APIPath are where the proxy serves Chef Supermarket +// requests and its cookbook API under that. +const ( + MountPath = "/chef" + APIPath = "/api/v1" +) + +// ErrDocument is returned for a document that isn't the JSON shape +// Supermarket serves. +var ErrDocument = errors.New("unexpected Chef Supermarket document") + +// versionPattern matches Chef cookbook versions, which have two or three +// numeric parts. +var versionPattern = regexp.MustCompile(`^[0-9]+\.[0-9]+(\.[0-9]+)?$`) + +// Options are the inputs the rewrites take. +type Options struct { + // ProxyURL is the proxy's public URL, without a trailing slash. + ProxyURL string +} + +// RewriteUniverse points every version's location_path and download_url at +// the proxy. The universe maps cookbook names to versions to their location +// and dependencies; dependencies and any other field are copied as they are. +func RewriteUniverse(body []byte, opts Options) ([]byte, error) { + var universe map[string]map[string]map[string]json.RawMessage + if err := json.Unmarshal(body, &universe); err != nil { + return nil, fmt.Errorf("%w: universe: %w", ErrDocument, err) + } + + locationPath, err := jsonString(APIURL(opts.ProxyURL)) + if err != nil { + return nil, err + } + for name, versions := range universe { + for version, entry := range versions { + if entry == nil { + continue + } + downloadURL, err := jsonString(DownloadURL(opts.ProxyURL, name, version)) + if err != nil { + return nil, err + } + entry["location_path"] = locationPath + entry["download_url"] = downloadURL + } + } + return EncodeJSON(universe) +} + +// RewriteCookbook points a cookbook's version URLs at the proxy. +func RewriteCookbook(name string, body []byte, opts Options) ([]byte, error) { + var cookbook map[string]json.RawMessage + if err := json.Unmarshal(body, &cookbook); err != nil { + return nil, fmt.Errorf("%w: cookbook %s: %w", ErrDocument, name, err) + } + + if raw, ok := cookbook["latest_version"]; ok { + rewritten, err := RewriteVersionURL(name, raw, opts) + if err != nil { + return nil, err + } + cookbook["latest_version"] = rewritten + } + if raw, ok := cookbook["versions"]; ok { + var versions []json.RawMessage + if err := json.Unmarshal(raw, &versions); err != nil { + return nil, fmt.Errorf("%w: cookbook %s versions: %w", ErrDocument, name, err) + } + for i, versionURL := range versions { + rewritten, err := RewriteVersionURL(name, versionURL, opts) + if err != nil { + return nil, err + } + versions[i] = rewritten + } + encoded, err := EncodeJSON(versions) + if err != nil { + return nil, err + } + cookbook["versions"] = encoded + } + return EncodeJSON(cookbook) +} + +// RewriteVersion points a cookbook version's cookbook and file URLs at the +// proxy. +func RewriteVersion(name, version string, body []byte, opts Options) ([]byte, error) { + var document map[string]json.RawMessage + if err := json.Unmarshal(body, &document); err != nil { + return nil, fmt.Errorf("%w: cookbook %s version %s: %w", ErrDocument, name, version, err) + } + + if _, ok := document["cookbook"]; ok { + cookbookURL, err := jsonString(CookbookURL(opts.ProxyURL, name)) + if err != nil { + return nil, err + } + document["cookbook"] = cookbookURL + } + if _, ok := document["file"]; ok { + fileURL, err := jsonString(DownloadURL(opts.ProxyURL, name, version)) + if err != nil { + return nil, err + } + document["file"] = fileURL + } + return EncodeJSON(document) +} + +// RewriteVersionURL rewrites an upstream cookbook version URL, a JSON string +// ending in /versions/{version}, to the proxy. Anything else, such as null, +// is returned unchanged. +func RewriteVersionURL(name string, raw json.RawMessage, opts Options) (json.RawMessage, error) { + var versionURL string + if err := json.Unmarshal(raw, &versionURL); err != nil { + return raw, nil //nolint:nilerr // not a string, so not a URL to rewrite + } + parsed, err := url.Parse(versionURL) + if err != nil { + return raw, nil //nolint:nilerr // not a URL, so nothing to rewrite + } + version, ok := NormalizeVersion(path.Base(parsed.Path)) + if !ok { + return raw, nil + } + return jsonString(VersionURL(opts.ProxyURL, name, version)) +} + +// APIURL is the proxy's cookbook API root. +func APIURL(proxyURL string) string { + return proxyURL + MountPath + APIPath +} + +// CookbookURL is where the proxy serves a cookbook's document. +func CookbookURL(proxyURL, name string) string { + return APIURL(proxyURL) + "/cookbooks/" + url.PathEscape(name) +} + +// VersionURL is where the proxy serves a cookbook version's document. +func VersionURL(proxyURL, name, version string) string { + return CookbookURL(proxyURL, name) + "/versions/" + url.PathEscape(version) +} + +// DownloadURL is where the proxy serves a cookbook version's archive. +func DownloadURL(proxyURL, name, version string) string { + return VersionURL(proxyURL, name, version) + "/download" +} + +// NormalizeVersion accepts a version in either form Supermarket serves +// (1.2.3, or 1_2_3 as Berkshelf writes it in URLs) and returns the dotted +// form. +func NormalizeVersion(version string) (string, bool) { + version = strings.ReplaceAll(version, "_", ".") + if !versionPattern.MatchString(version) { + return "", false + } + return version, true +} + +func jsonString(s string) (json.RawMessage, error) { + return EncodeJSON(s) +} + +// EncodeJSON encodes v without escaping HTML characters, so dependency +// constraints such as ">= 1.0" keep their upstream spelling. +func EncodeJSON(v any) (json.RawMessage, error) { + var buf bytes.Buffer + enc := json.NewEncoder(&buf) + enc.SetEscapeHTML(false) + if err := enc.Encode(v); err != nil { + return nil, err + } + return bytes.TrimSuffix(buf.Bytes(), []byte("\n")), nil +} diff --git a/internal/metadata/chef/metadata_test.go b/internal/metadata/chef/metadata_test.go new file mode 100644 index 00000000..1cff2c72 --- /dev/null +++ b/internal/metadata/chef/metadata_test.go @@ -0,0 +1,172 @@ +package chef + +import ( + "encoding/json" + "errors" + "strings" + "testing" +) + +const proxy = "https://proxy.example" + +func decode(t *testing.T, b []byte) map[string]any { + t.Helper() + var m map[string]any + if err := json.Unmarshal(b, &m); err != nil { + t.Fatalf("decode %s: %v", b, err) + } + return m +} + +func TestRewriteUniverse(t *testing.T) { + body := []byte(`{"apt":{"7.4.0":{"location_type":"opscode","location_path":"https://supermarket.chef.io/api/v1","download_url":"https://supermarket.chef.io/api/v1/cookbooks/apt/versions/7.4.0/download","dependencies":{"compat_resource":">= 12.16.3"}},"7.3.0":null}}`) + out, err := RewriteUniverse(body, Options{ProxyURL: proxy}) + if err != nil { + t.Fatal(err) + } + entry := decode(t, out)["apt"].(map[string]any)["7.4.0"].(map[string]any) + if got := entry["location_path"]; got != proxy+"/chef/api/v1" { + t.Errorf("location_path = %v", got) + } + if got := entry["download_url"]; got != proxy+"/chef/api/v1/cookbooks/apt/versions/7.4.0/download" { + t.Errorf("download_url = %v", got) + } + if got := entry["location_type"]; got != "opscode" { + t.Errorf("location_type = %v", got) + } + if got := entry["dependencies"].(map[string]any)["compat_resource"]; got != ">= 12.16.3" { + t.Errorf("dependency = %v", got) + } + if !strings.Contains(string(out), `">= 12.16.3"`) { + t.Errorf("constraint not kept as written in %s", out) + } + if v, ok := decode(t, out)["apt"].(map[string]any)["7.3.0"]; !ok || v != nil { + t.Errorf("null entry = %v, %v", v, ok) + } +} + +func TestRewriteUniverseRefusesOtherShapes(t *testing.T) { + for _, body := range []string{`[]`, `{"apt":[]}`, `not json`} { + if _, err := RewriteUniverse([]byte(body), Options{ProxyURL: proxy}); !errors.Is(err, ErrDocument) { + t.Errorf("%s: err = %v", body, err) + } + } +} + +func TestRewriteCookbook(t *testing.T) { + body := []byte(`{"name":"apt","latest_version":"https://supermarket.chef.io/api/v1/cookbooks/apt/versions/7.4.0","versions":["https://supermarket.chef.io/api/v1/cookbooks/apt/versions/7_4_0","https://supermarket.chef.io/api/v1/cookbooks/apt/versions/latest",null],"description":""}`) + out, err := RewriteCookbook("apt", body, Options{ProxyURL: proxy}) + if err != nil { + t.Fatal(err) + } + m := decode(t, out) + if got := m["latest_version"]; got != proxy+"/chef/api/v1/cookbooks/apt/versions/7.4.0" { + t.Errorf("latest_version = %v", got) + } + versions := m["versions"].([]any) + if versions[0] != proxy+"/chef/api/v1/cookbooks/apt/versions/7.4.0" { + t.Errorf("versions[0] = %v", versions[0]) + } + if versions[1] != "https://supermarket.chef.io/api/v1/cookbooks/apt/versions/latest" { + t.Errorf("versions[1] = %v, want unchanged", versions[1]) + } + if versions[2] != nil { + t.Errorf("versions[2] = %v", versions[2]) + } + if !strings.Contains(string(out), `"description":""`) { + t.Errorf("description = %v in %s", m["description"], out) + } +} + +func TestRewriteCookbookWithoutVersionFields(t *testing.T) { + out, err := RewriteCookbook("apt", []byte(`{"name":"apt"}`), Options{ProxyURL: proxy}) + if err != nil { + t.Fatal(err) + } + if m := decode(t, out); len(m) != 1 || m["name"] != "apt" { + t.Errorf("got %s", out) + } +} + +func TestRewriteCookbookRefusesOtherShapes(t *testing.T) { + for _, body := range []string{`[]`, `{"versions":"x"}`} { + if _, err := RewriteCookbook("apt", []byte(body), Options{ProxyURL: proxy}); !errors.Is(err, ErrDocument) { + t.Errorf("%s: err = %v", body, err) + } + } +} + +func TestRewriteVersion(t *testing.T) { + body := []byte(`{"version":"7.4.0","cookbook":"https://supermarket.chef.io/api/v1/cookbooks/apt","file":"https://supermarket.chef.io/api/v1/cookbooks/apt/versions/7.4.0/download","license":"Apache-2.0"}`) + out, err := RewriteVersion("apt", "7.4.0", body, Options{ProxyURL: proxy}) + if err != nil { + t.Fatal(err) + } + m := decode(t, out) + if m["cookbook"] != proxy+"/chef/api/v1/cookbooks/apt" { + t.Errorf("cookbook = %v", m["cookbook"]) + } + if m["file"] != proxy+"/chef/api/v1/cookbooks/apt/versions/7.4.0/download" { + t.Errorf("file = %v", m["file"]) + } + if m["license"] != "Apache-2.0" { + t.Errorf("license = %v", m["license"]) + } +} + +func TestRewriteVersionAddsNoFields(t *testing.T) { + out, err := RewriteVersion("apt", "7.4.0", []byte(`{"version":"7.4.0"}`), Options{ProxyURL: proxy}) + if err != nil { + t.Fatal(err) + } + if m := decode(t, out); len(m) != 1 { + t.Errorf("got %s", out) + } + if _, err := RewriteVersion("apt", "7.4.0", []byte(`[]`), Options{ProxyURL: proxy}); !errors.Is(err, ErrDocument) { + t.Errorf("err = %v", err) + } +} + +func TestRewriteVersionURLLeavesOthersAlone(t *testing.T) { + for _, raw := range []string{`null`, `42`, `"%zz"`, `"https://x/versions/latest"`} { + out, err := RewriteVersionURL("apt", json.RawMessage(raw), Options{ProxyURL: proxy}) + if err != nil || string(out) != raw { + t.Errorf("%s: got %s, %v", raw, out, err) + } + } +} + +func TestURLsEscapeNames(t *testing.T) { + if got := DownloadURL(proxy, "a b", "1.0"); got != proxy+"/chef/api/v1/cookbooks/a%20b/versions/1.0/download" { + t.Errorf("DownloadURL = %s", got) + } + if got := VersionURL(proxy, "apt", "1/0"); got != proxy+"/chef/api/v1/cookbooks/apt/versions/1%2F0" { + t.Errorf("VersionURL = %s", got) + } +} + +func TestNormalizeVersion(t *testing.T) { + for in, want := range map[string]string{"1.2.3": "1.2.3", "1_2_3": "1.2.3", "1.2": "1.2", "10_0": "10.0"} { + if got, ok := NormalizeVersion(in); !ok || got != want { + t.Errorf("%s: got %s, %v", in, got, ok) + } + } + for _, in := range []string{"1", "1.2.3.4", "latest", "v1.2", "1.2.x", "", "1.2.3 "} { + if got, ok := NormalizeVersion(in); ok { + t.Errorf("%s: accepted as %s", in, got) + } + } +} + +func TestEncodeJSONKeepsHTMLCharacters(t *testing.T) { + out, err := EncodeJSON(map[string]string{"c": ">= 1.0 & <2"}) + if err != nil { + t.Fatal(err) + } + if string(out) != `{"c":">= 1.0 & <2"}` { + t.Errorf("got %s", out) + } + if _, err := EncodeJSON(func() {}); err == nil { + t.Error("encoded a func") + } +}