From e6272369fd4e0bee92d48e5ec9c6438dc907606a Mon Sep 17 00:00:00 2001 From: Simon Chrzanowski Date: Mon, 23 Nov 2026 17:20:40 +0100 Subject: [PATCH] Extract portable OCI metadata transformations Part of #501. The tag list and referrers Link rewrite, manifest Accept negotiation and the references a manifest names move out of internal/handler into internal/metadata/oci, which takes its inputs explicitly and builds for wasip1. The handler keeps fetching, token auth, coalescing and caching, with its functions as thin wrappers. --- internal/handler/container.go | 3 +- internal/handler/container_image_refs.go | 34 +--- internal/handler/container_manifest.go | 154 ++------------- internal/handler/container_mirror.go | 31 +-- internal/handler/container_tags.go | 50 +---- internal/metadata/oci/accept.go | 182 +++++++++++++++++ internal/metadata/oci/imports_test.go | 38 ++++ internal/metadata/oci/link.go | 75 +++++++ internal/metadata/oci/manifest.go | 68 +++++++ internal/metadata/oci/metadata_test.go | 238 +++++++++++++++++++++++ 10 files changed, 640 insertions(+), 233 deletions(-) create mode 100644 internal/metadata/oci/accept.go create mode 100644 internal/metadata/oci/imports_test.go create mode 100644 internal/metadata/oci/link.go create mode 100644 internal/metadata/oci/manifest.go create mode 100644 internal/metadata/oci/metadata_test.go diff --git a/internal/handler/container.go b/internal/handler/container.go index 2e941180..1e00ccc3 100644 --- a/internal/handler/container.go +++ b/internal/handler/container.go @@ -13,6 +13,7 @@ import ( "strings" "sync" + "github.com/git-pkgs/proxy/internal/metadata/oci" "github.com/git-pkgs/proxy/internal/retention" "github.com/git-pkgs/purl" "github.com/git-pkgs/registries/fetch" @@ -28,7 +29,7 @@ const ( // namespaceQueryParam is the query parameter containerd appends to mirror // requests to name the registry the image reference points at. - namespaceQueryParam = "ns" + namespaceQueryParam = oci.NamespaceQueryParam // defaultNamespaceRoute marks namespace hosts served by the default registry. defaultNamespaceRoute = "" // maxReportedNamespaceRefusals bounds the upstream/ns pairs remembered diff --git a/internal/handler/container_image_refs.go b/internal/handler/container_image_refs.go index c99237dc..6547c12b 100644 --- a/internal/handler/container_image_refs.go +++ b/internal/handler/container_image_refs.go @@ -1,18 +1,13 @@ package handler import ( - "encoding/json" "regexp" - "slices" "time" "github.com/git-pkgs/proxy/internal/database" + "github.com/git-pkgs/proxy/internal/metadata/oci" ) -// maxImageManifestRefs is how many references of one manifest are recorded. -// A manifest with more is not recorded. -const maxImageManifestRefs = 4096 - // imageSubjectTagPattern matches the tags that hold what refers to an image // rather than an image of their own: the referrers tag schema, and the // sha256-.sig, .att and .sbom tags of cosign. @@ -70,29 +65,8 @@ func (h *ContainerHandler) recordImageManifest(cacheName, reference string, mani } } -// imageManifestRefs returns the digests of the manifests an index lists, or -// of the config and layers of an image manifest. It returns nil for a -// document that names none, or more than maxImageManifestRefs. +// imageManifestRefs returns the digests a manifest references; see +// oci.ManifestRefs. func imageManifestRefs(body []byte) []string { - var manifest ociManifest - if len(body) == 0 || json.Unmarshal(body, &manifest) != nil { - return nil - } - descriptors := slices.Concat(manifest.Manifests, manifest.Layers) - if manifest.Config != nil { - descriptors = append(descriptors, *manifest.Config) - } - seen := make(map[string]struct{}, len(descriptors)) - var refs []string - for _, descriptor := range descriptors { - if _, dup := seen[descriptor.Digest]; dup || !mirrorDigestPattern.MatchString(descriptor.Digest) { - continue - } - seen[descriptor.Digest] = struct{}{} - refs = append(refs, descriptor.Digest) - } - if len(refs) > maxImageManifestRefs { - return nil - } - return refs + return oci.ManifestRefs(body) } diff --git a/internal/handler/container_manifest.go b/internal/handler/container_manifest.go index bf4644d7..98ee9e52 100644 --- a/internal/handler/container_manifest.go +++ b/internal/handler/container_manifest.go @@ -5,31 +5,27 @@ import ( "crypto/sha256" "encoding/hex" "fmt" - "mime" "net/http" "regexp" "slices" - "sort" "strconv" "strings" "time" + + "github.com/git-pkgs/proxy/internal/metadata/oci" ) const ( containerManifestCacheEcosystem = "oci-manifest" containerStaleWarning = `110 - "Response is Stale"` - - containerAcceptWildcardSpecificity = iota - containerAcceptTypeWildcardSpecificity - containerAcceptExactSpecificity ) const ( // containerManifestIndexCacheClass replaces the Accept header in tag cache // keys for clients that accept an index type. containerManifestIndexCacheClass = "index" - ociImageIndexMediaType = "application/vnd.oci.image.index.v1+json" - dockerManifestListMediaType = "application/vnd.docker.distribution.manifest.list.v2+json" + ociImageIndexMediaType = oci.ImageIndexMediaType + dockerManifestListMediaType = oci.DockerManifestListMediaType ) var manifestDigestReferencePattern = regexp.MustCompile(`^[a-z0-9]+:[a-f0-9]+$`) @@ -149,19 +145,13 @@ func (h *ContainerHandler) containerManifestSharedCacheKey(registryURL, name, re } func containerManifestAcceptsIndex(accept string) bool { - return containerManifestAccepts(accept, ociImageIndexMediaType) || containerManifestAccepts(accept, dockerManifestListMediaType) + return oci.AcceptsIndex(accept) } // containerManifestNames reports whether accept lists mediaType itself and -// doesn't refuse it with q=0. Registries compare Accept values literally, so a -// wildcard gets a client the converted manifest, not the index. +// doesn't refuse it with q=0; see oci.Names. func containerManifestNames(accept, mediaType string) bool { - for _, value := range strings.Split(accept, ",") { - if named, _, err := mime.ParseMediaType(value); err == nil && named == mediaType { - return containerManifestAccepts(accept, mediaType) - } - } - return false + return oci.Names(accept, mediaType) } // containerManifestSharable reports whether manifest may go under the shared @@ -174,8 +164,7 @@ func containerManifestSharable(reference, cacheAccept string, manifest *cachedCo if manifestDigestReferencePattern.MatchString(reference) || !containerManifestAcceptsIndex(cacheAccept) { return true } - if mediaType, _, err := mime.ParseMediaType(manifest.contentType); err == nil && - (mediaType == ociImageIndexMediaType || mediaType == dockerManifestListMediaType) { + if oci.IsIndexMediaType(manifest.contentType) { return true } return containerManifestNames(cacheAccept, ociImageIndexMediaType) && containerManifestNames(cacheAccept, dockerManifestListMediaType) @@ -348,138 +337,25 @@ func containerManifestAccept(r *http.Request) string { if accept := strings.Join(r.Header.Values("Accept"), ", "); accept != "" { return accept } - return strings.Join([]string{ - "application/vnd.oci.image.manifest.v1+json", - "application/vnd.oci.image.index.v1+json", - "application/vnd.docker.distribution.manifest.v2+json", - "application/vnd.docker.distribution.manifest.list.v2+json", - "application/vnd.docker.distribution.manifest.v1+prettyjws", - }, ", ") + return oci.DefaultManifestAccept } +// normalizeContainerManifestAccept is accept in the form cache keys use; +// see oci.NormalizeAccept. func normalizeContainerManifestAccept(accept string) string { - mediaTypes := make(map[string]struct{}) - for _, value := range strings.Split(accept, ",") { - value = strings.TrimSpace(value) - if value == "" { - continue - } - mediaType, params, err := mime.ParseMediaType(value) - if err != nil { - mediaTypes[strings.ToLower(value)] = struct{}{} - continue - } - paramKeys := make([]string, 0, len(params)) - for key := range params { - paramKeys = append(paramKeys, key) - } - sort.Strings(paramKeys) - canonical := strings.ToLower(mediaType) - for _, key := range paramKeys { - value := params[key] - if strings.EqualFold(key, "q") { - if quality, err := strconv.ParseFloat(value, 64); err == nil { - if quality == 1 { - continue - } - value = strconv.FormatFloat(quality, 'g', -1, 64) - } - } - canonical += ";" + strings.ToLower(key) + "=" + value - } - mediaTypes[canonical] = struct{}{} - } - canonicalMediaTypes := make([]string, 0, len(mediaTypes)) - for mediaType := range mediaTypes { - canonicalMediaTypes = append(canonicalMediaTypes, mediaType) - } - sort.Strings(canonicalMediaTypes) - return strings.Join(canonicalMediaTypes, ",") + return oci.NormalizeAccept(accept) } +// containerManifestAccepts reports whether accept allows contentType; see +// oci.Accepts. func containerManifestAccepts(accept, contentType string) bool { - contentType, contentParams, err := mime.ParseMediaType(contentType) - if err != nil { - return false - } - contentType = strings.ToLower(contentType) - contentMajor, contentMinor, found := strings.Cut(contentType, "/") - if !found { - return false - } - - bestMediaTypeSpecificity := -1 - bestParameterSpecificity := 0 - bestQuality := 0.0 - for _, value := range strings.Split(accept, ",") { - mediaType, params, err := mime.ParseMediaType(strings.TrimSpace(value)) - if err != nil { - continue - } - mediaType = strings.ToLower(mediaType) - major, minor, found := strings.Cut(mediaType, "/") - if found && containerAcceptRangeMatches(major, minor, params, contentMajor, contentMinor, contentParams) { - mediaTypeSpecificity, parameterSpecificity := containerAcceptSpecificity(major, minor, params) - if mediaTypeSpecificity > bestMediaTypeSpecificity || - (mediaTypeSpecificity == bestMediaTypeSpecificity && parameterSpecificity > bestParameterSpecificity) { - bestMediaTypeSpecificity = mediaTypeSpecificity - bestParameterSpecificity = parameterSpecificity - bestQuality = containerAcceptQuality(params) - } - } - } - return bestQuality > 0 + return oci.Accepts(accept, contentType) } func containerManifestCacheCompatible(accept string, manifest *cachedContainerManifest) bool { return manifest.contentType == "" || containerManifestAccepts(accept, manifest.contentType) } -func containerAcceptRangeMatches(major, minor string, params map[string]string, contentMajor, contentMinor string, contentParams map[string]string) bool { - if (major != "*" && major != contentMajor) || (minor != "*" && minor != contentMinor) { - return false - } - for key, value := range params { - if strings.EqualFold(key, "q") { - continue - } - if contentParams[key] != value { - return false - } - } - return true -} - -func containerAcceptSpecificity(major, minor string, params map[string]string) (int, int) { - parameterSpecificity := 0 - for key := range params { - if !strings.EqualFold(key, "q") { - parameterSpecificity++ - } - } - - switch { - case major == "*" && minor == "*": - return containerAcceptWildcardSpecificity, parameterSpecificity - case major == "*" || minor == "*": - return containerAcceptTypeWildcardSpecificity, parameterSpecificity - default: - return containerAcceptExactSpecificity, parameterSpecificity - } -} - -func containerAcceptQuality(params map[string]string) float64 { - value, ok := params["q"] - if !ok { - return 1 - } - quality, err := strconv.ParseFloat(value, 64) - if err != nil || quality < 0 || quality > 1 { - return 0 - } - return quality -} - func copyContainerManifestHeaders(destination, source http.Header) { for _, header := range []string{headerContentType, headerContentLength, "Docker-Content-Digest", headerETag, headerLastModified, "WWW-Authenticate"} { if value := source.Get(header); value != "" { diff --git a/internal/handler/container_mirror.go b/internal/handler/container_mirror.go index 422f0129..ebaf9ea5 100644 --- a/internal/handler/container_mirror.go +++ b/internal/handler/container_mirror.go @@ -15,6 +15,7 @@ import ( "sync/atomic" "time" + "github.com/git-pkgs/proxy/internal/metadata/oci" "golang.org/x/sync/errgroup" ) @@ -36,7 +37,7 @@ var ( // Grammar from the OCI distribution spec. mirrorNamePattern = regexp.MustCompile(`^[a-z0-9]+((\.|_|__|-+)[a-z0-9]+)*(/[a-z0-9]+((\.|_|__|-+)[a-z0-9]+)*)*$`) mirrorTagPattern = regexp.MustCompile(`^[a-zA-Z0-9_][a-zA-Z0-9._-]{0,127}$`) - mirrorDigestPattern = regexp.MustCompile(`^(sha256:[a-f0-9]{64}|sha512:[a-f0-9]{128})$`) + mirrorDigestPattern = oci.DigestPattern ) // dockerHubMirrorAliases are registry hosts that name Docker Hub in image @@ -103,27 +104,13 @@ type ImageResult struct { Warnings []string } -type ociDescriptor struct { - MediaType string `json:"mediaType"` - Digest string `json:"digest"` - URLs []string `json:"urls"` - Platform *ociPlatform `json:"platform"` - Annotations map[string]string `json:"annotations"` -} - -type ociPlatform struct { - OS string `json:"os"` - Architecture string `json:"architecture"` - Variant string `json:"variant"` -} - -type ociManifest struct { - SchemaVersion int `json:"schemaVersion"` - MediaType string `json:"mediaType"` - Manifests []ociDescriptor `json:"manifests"` - Config *ociDescriptor `json:"config"` - Layers []ociDescriptor `json:"layers"` -} +// ociDescriptor, ociPlatform and ociManifest are the manifest documents the +// mirror reads (see the oci package). +type ( + ociDescriptor = oci.Descriptor + ociPlatform = oci.Platform + ociManifest = oci.Manifest +) type imageMirror struct { h *ContainerHandler diff --git a/internal/handler/container_tags.go b/internal/handler/container_tags.go index cca97b6b..67d84164 100644 --- a/internal/handler/container_tags.go +++ b/internal/handler/container_tags.go @@ -7,10 +7,11 @@ import ( "fmt" "net/http" "net/url" - "regexp" "strconv" "strings" "time" + + "github.com/git-pkgs/proxy/internal/metadata/oci" ) const ( @@ -22,8 +23,6 @@ const ( containerTagsCacheFormat = "raw-link" ) -var containerLinkTargetPattern = regexp.MustCompile(`<([^>]*)>`) - type cachedContainerTags struct { body []byte contentType string @@ -207,44 +206,13 @@ func copyContainerTagsHeaders(destination, source http.Header) { } } +// rewriteContainerTagsLink points a tag list or referrers Link header back +// at the proxy; see oci.RewriteLink. func (h *ContainerHandler) rewriteContainerTagsLink(link, registryURL, requestPath, namespace string) string { - if link == "" { - return "" - } - upstreamURL, err := url.Parse(registryURL) - if err != nil { - return link - } - proxyURL, err := url.Parse(h.proxyURL) - if err != nil { - return link - } - - return containerLinkTargetPattern.ReplaceAllStringFunc(link, func(target string) string { - linkURL, err := url.Parse(target[1 : len(target)-1]) - if err != nil { - return target - } - if linkURL.IsAbs() { - if linkURL.Scheme != upstreamURL.Scheme || linkURL.Host != upstreamURL.Host { - return target - } - } else if linkURL.Host != "" || (linkURL.Path != "" && !strings.HasPrefix(linkURL.Path, "/v2/")) { - return target - } - // Relative registry API links resolve against the current tag-list - // endpoint. Rebuild them below so named-registry selectors are kept. - linkURL.Scheme = proxyURL.Scheme - linkURL.Host = proxyURL.Host - linkURL.User = proxyURL.User - linkURL.Path = strings.TrimSuffix(proxyURL.Path, "/") + "/v2" + requestPath - linkURL.RawPath = "" - if namespace != "" { - // Keep follow-up pages on the ns route the client is using. - query := linkURL.Query() - query.Set(namespaceQueryParam, namespace) - linkURL.RawQuery = query.Encode() - } - return "<" + linkURL.String() + ">" + return oci.RewriteLink(link, oci.LinkOptions{ + ProxyURL: h.proxyURL, + RegistryURL: registryURL, + RequestPath: requestPath, + Namespace: namespace, }) } diff --git a/internal/metadata/oci/accept.go b/internal/metadata/oci/accept.go new file mode 100644 index 00000000..80e7d61b --- /dev/null +++ b/internal/metadata/oci/accept.go @@ -0,0 +1,182 @@ +package oci + +import ( + "mime" + "sort" + "strconv" + "strings" +) + +// Manifest media types the Accept negotiation names. +const ( + ImageManifestMediaType = "application/vnd.oci.image.manifest.v1+json" + ImageIndexMediaType = "application/vnd.oci.image.index.v1+json" + DockerManifestMediaType = "application/vnd.docker.distribution.manifest.v2+json" + DockerManifestListMediaType = "application/vnd.docker.distribution.manifest.list.v2+json" + DockerSignedManifestType = "application/vnd.docker.distribution.manifest.v1+prettyjws" +) + +// DefaultManifestAccept is the Accept value used for a manifest request +// that sends none: every manifest type a registry may answer with. +var DefaultManifestAccept = strings.Join([]string{ + ImageManifestMediaType, + ImageIndexMediaType, + DockerManifestMediaType, + DockerManifestListMediaType, + DockerSignedManifestType, +}, ", ") + +const ( + acceptWildcardSpecificity = iota + acceptTypeWildcardSpecificity + acceptExactSpecificity +) + +// NormalizeAccept returns accept with its media ranges lowercased, their +// parameters sorted, q=1 dropped and duplicates removed, in a fixed order, +// so Accept values that mean the same share a cache key. +func NormalizeAccept(accept string) string { + mediaTypes := make(map[string]struct{}) + for _, value := range strings.Split(accept, ",") { + value = strings.TrimSpace(value) + if value == "" { + continue + } + mediaType, params, err := mime.ParseMediaType(value) + if err != nil { + mediaTypes[strings.ToLower(value)] = struct{}{} + continue + } + paramKeys := make([]string, 0, len(params)) + for key := range params { + paramKeys = append(paramKeys, key) + } + sort.Strings(paramKeys) + canonical := strings.ToLower(mediaType) + for _, key := range paramKeys { + value := params[key] + if strings.EqualFold(key, "q") { + if quality, err := strconv.ParseFloat(value, 64); err == nil { + if quality == 1 { + continue + } + value = strconv.FormatFloat(quality, 'g', -1, 64) + } + } + canonical += ";" + strings.ToLower(key) + "=" + value + } + mediaTypes[canonical] = struct{}{} + } + canonicalMediaTypes := make([]string, 0, len(mediaTypes)) + for mediaType := range mediaTypes { + canonicalMediaTypes = append(canonicalMediaTypes, mediaType) + } + sort.Strings(canonicalMediaTypes) + return strings.Join(canonicalMediaTypes, ",") +} + +// Accepts reports whether accept allows contentType: the most specific +// media range that matches it has a quality above zero. +func Accepts(accept, contentType string) bool { + contentType, contentParams, err := mime.ParseMediaType(contentType) + if err != nil { + return false + } + contentType = strings.ToLower(contentType) + contentMajor, contentMinor, found := strings.Cut(contentType, "/") + if !found { + return false + } + + bestMediaTypeSpecificity := -1 + bestParameterSpecificity := 0 + bestQuality := 0.0 + for _, value := range strings.Split(accept, ",") { + mediaType, params, err := mime.ParseMediaType(strings.TrimSpace(value)) + if err != nil { + continue + } + mediaType = strings.ToLower(mediaType) + major, minor, found := strings.Cut(mediaType, "/") + if found && acceptRangeMatches(major, minor, params, contentMajor, contentMinor, contentParams) { + mediaTypeSpecificity, parameterSpecificity := acceptSpecificity(major, minor, params) + if mediaTypeSpecificity > bestMediaTypeSpecificity || + (mediaTypeSpecificity == bestMediaTypeSpecificity && parameterSpecificity > bestParameterSpecificity) { + bestMediaTypeSpecificity = mediaTypeSpecificity + bestParameterSpecificity = parameterSpecificity + bestQuality = acceptQuality(params) + } + } + } + return bestQuality > 0 +} + +// AcceptsIndex reports whether accept allows an OCI image index or a Docker +// manifest list. +func AcceptsIndex(accept string) bool { + return Accepts(accept, ImageIndexMediaType) || Accepts(accept, DockerManifestListMediaType) +} + +// Names reports whether accept lists mediaType itself and doesn't refuse it +// with q=0. Registries compare Accept values literally, so a wildcard gets a +// client the converted manifest, not the index. +func Names(accept, mediaType string) bool { + for _, value := range strings.Split(accept, ",") { + if named, _, err := mime.ParseMediaType(value); err == nil && named == mediaType { + return Accepts(accept, mediaType) + } + } + return false +} + +// IsIndexMediaType reports whether contentType is an OCI image index or a +// Docker manifest list. +func IsIndexMediaType(contentType string) bool { + mediaType, _, err := mime.ParseMediaType(contentType) + return err == nil && (mediaType == ImageIndexMediaType || mediaType == DockerManifestListMediaType) +} + +func acceptRangeMatches(major, minor string, params map[string]string, contentMajor, contentMinor string, contentParams map[string]string) bool { + if (major != "*" && major != contentMajor) || (minor != "*" && minor != contentMinor) { + return false + } + for key, value := range params { + if strings.EqualFold(key, "q") { + continue + } + if contentParams[key] != value { + return false + } + } + return true +} + +func acceptSpecificity(major, minor string, params map[string]string) (int, int) { + parameterSpecificity := 0 + for key := range params { + if !strings.EqualFold(key, "q") { + parameterSpecificity++ + } + } + + switch { + case major == "*" && minor == "*": + return acceptWildcardSpecificity, parameterSpecificity + case major == "*" || minor == "*": + return acceptTypeWildcardSpecificity, parameterSpecificity + default: + return acceptExactSpecificity, parameterSpecificity + } +} + +func acceptQuality(params map[string]string) float64 { + value, ok := params["q"] + if !ok { + return 1 + } + quality, err := strconv.ParseFloat(value, 64) + if err != nil || quality < 0 || quality > 1 { + return 0 + } + return quality +} diff --git a/internal/metadata/oci/imports_test.go b/internal/metadata/oci/imports_test.go new file mode 100644 index 00000000..088a37cc --- /dev/null +++ b/internal/metadata/oci/imports_test.go @@ -0,0 +1,38 @@ +package oci + +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/oci", + } + 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/oci/link.go b/internal/metadata/oci/link.go new file mode 100644 index 00000000..3895ae72 --- /dev/null +++ b/internal/metadata/oci/link.go @@ -0,0 +1,75 @@ +// Package oci holds the OCI distribution metadata transformations the +// container handler applies: pagination Link rewrites, manifest Accept +// negotiation and the references a manifest names. It takes its inputs +// explicitly and has no dependency on the proxy's storage, database or HTTP +// client, so it builds on its own, for WASI among others. +package oci + +import ( + "net/url" + "regexp" + "strings" +) + +// NamespaceQueryParam is the query parameter that selects a registry by +// namespace on the proxy's /v2 routes. +const NamespaceQueryParam = "ns" + +var linkTargetPattern = regexp.MustCompile(`<([^>]*)>`) + +// LinkOptions are the URLs a Link rewrite needs: the proxy's public URL, the +// upstream registry the Link came from, the path of the request being +// answered (below /v2), and the ns value it used, if any. +type LinkOptions struct { + ProxyURL string + RegistryURL string + RequestPath string + Namespace string +} + +// RewriteLink points the targets of a tag list or referrers Link header that +// lead back into the upstream registry's API at the same endpoint on the +// proxy, keeping their query and the ns route the client is on. Targets on +// other hosts or outside /v2/ are left as they are, and so is the whole +// header when a URL doesn't parse. +func RewriteLink(link string, o LinkOptions) string { + if link == "" { + return "" + } + upstreamURL, err := url.Parse(o.RegistryURL) + if err != nil { + return link + } + proxyURL, err := url.Parse(o.ProxyURL) + if err != nil { + return link + } + + return linkTargetPattern.ReplaceAllStringFunc(link, func(target string) string { + linkURL, err := url.Parse(target[1 : len(target)-1]) + if err != nil { + return target + } + if linkURL.IsAbs() { + if linkURL.Scheme != upstreamURL.Scheme || linkURL.Host != upstreamURL.Host { + return target + } + } else if linkURL.Host != "" || (linkURL.Path != "" && !strings.HasPrefix(linkURL.Path, "/v2/")) { + return target + } + // Relative registry API links resolve against the current tag-list + // endpoint. Rebuild them below so named-registry selectors are kept. + linkURL.Scheme = proxyURL.Scheme + linkURL.Host = proxyURL.Host + linkURL.User = proxyURL.User + linkURL.Path = strings.TrimSuffix(proxyURL.Path, "/") + "/v2" + o.RequestPath + linkURL.RawPath = "" + if o.Namespace != "" { + // Keep follow-up pages on the ns route the client is using. + query := linkURL.Query() + query.Set(NamespaceQueryParam, o.Namespace) + linkURL.RawQuery = query.Encode() + } + return "<" + linkURL.String() + ">" + }) +} diff --git a/internal/metadata/oci/manifest.go b/internal/metadata/oci/manifest.go new file mode 100644 index 00000000..0f05c737 --- /dev/null +++ b/internal/metadata/oci/manifest.go @@ -0,0 +1,68 @@ +package oci + +import ( + "encoding/json" + "regexp" + "slices" +) + +// MaxManifestRefs is how many references ManifestRefs returns at most. A +// manifest with more yields none. +const MaxManifestRefs = 4096 + +// DigestPattern matches the sha256 and sha512 digests the proxy accepts. +var DigestPattern = regexp.MustCompile(`^(sha256:[a-f0-9]{64}|sha512:[a-f0-9]{128})$`) + +// Descriptor is an OCI content descriptor. +type Descriptor struct { + MediaType string `json:"mediaType"` + Digest string `json:"digest"` + URLs []string `json:"urls"` + Platform *Platform `json:"platform"` + Annotations map[string]string `json:"annotations"` +} + +// Platform is the platform an index entry is for. +type Platform struct { + OS string `json:"os"` + Architecture string `json:"architecture"` + Variant string `json:"variant"` +} + +// Manifest is the part of an image manifest or index the proxy reads: an +// index's manifests, or an image's config and layers. +type Manifest struct { + SchemaVersion int `json:"schemaVersion"` + MediaType string `json:"mediaType"` + Manifests []Descriptor `json:"manifests"` + Config *Descriptor `json:"config"` + Layers []Descriptor `json:"layers"` +} + +// ManifestRefs returns the digests of the manifests an index lists, or of +// the config and layers of an image manifest, each once. It returns nil for +// a document that doesn't parse, names none, or names more than +// MaxManifestRefs. +func ManifestRefs(body []byte) []string { + var manifest Manifest + if len(body) == 0 || json.Unmarshal(body, &manifest) != nil { + return nil + } + descriptors := slices.Concat(manifest.Manifests, manifest.Layers) + if manifest.Config != nil { + descriptors = append(descriptors, *manifest.Config) + } + seen := make(map[string]struct{}, len(descriptors)) + var refs []string + for _, descriptor := range descriptors { + if _, dup := seen[descriptor.Digest]; dup || !DigestPattern.MatchString(descriptor.Digest) { + continue + } + seen[descriptor.Digest] = struct{}{} + refs = append(refs, descriptor.Digest) + } + if len(refs) > MaxManifestRefs { + return nil + } + return refs +} diff --git a/internal/metadata/oci/metadata_test.go b/internal/metadata/oci/metadata_test.go new file mode 100644 index 00000000..d9930eb2 --- /dev/null +++ b/internal/metadata/oci/metadata_test.go @@ -0,0 +1,238 @@ +package oci + +import ( + "slices" + "strconv" + "strings" + "testing" +) + +func TestRewriteLink(t *testing.T) { + base := LinkOptions{ + ProxyURL: "https://proxy.example/base/", + RegistryURL: "https://registry.example", + RequestPath: "/library/alpine/tags/list", + } + withNS := base + withNS.Namespace = "docker.io" + badProxy := base + badProxy.ProxyURL = "://bad" + badRegistry := base + badRegistry.RegistryURL = "://bad" + userProxy := base + userProxy.ProxyURL = "https://u:p@proxy.example" + + tests := []struct { + name string + link string + o LinkOptions + want string + }{ + {"empty", "", base, ""}, + {"relative", `; rel="next"`, base, + `; rel="next"`}, + {"query only", `; rel="next"`, base, + `; rel="next"`}, + {"absolute upstream", `; rel="next"`, base, + `; rel="next"`}, + {"other host", `; rel="next"`, base, + `; rel="next"`}, + {"other scheme", `; rel="next"`, base, + `; rel="next"`}, + {"outside v2", `; rel="help"`, base, `; rel="help"`}, + {"protocol relative", `; rel="next"`, base, `; rel="next"`}, + {"unparseable target", "<%zz>; rel=\"next\"", base, "<%zz>; rel=\"next\""}, + {"namespace kept", `; rel="next"`, withNS, + `; rel="next"`}, + {"bad proxy URL", `; rel="next"`, badProxy, `; rel="next"`}, + {"bad registry URL", `; rel="next"`, badRegistry, `; rel="next"`}, + {"proxy userinfo", `; rel="next"`, userProxy, `; rel="next"`}, + {"two targets", `; rel="next", ; rel="x"`, base, + `; rel="next", ; rel="x"`}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := RewriteLink(tt.link, tt.o); got != tt.want { + t.Errorf("RewriteLink(%q) = %q, want %q", tt.link, got, tt.want) + } + }) + } +} + +func TestRewriteLinkEncodesRequestPath(t *testing.T) { + // RequestPath is the decoded request path, which the rewritten target + // encodes again in place of the upstream's encoded path. + o := LinkOptions{ProxyURL: "https://proxy.example", RegistryURL: "https://registry.example", RequestPath: "/a b/tags/list"} + got := RewriteLink(``, o) + if got != `` { + t.Errorf("got %q", got) + } +} + +func TestAccepts(t *testing.T) { + tests := []struct { + accept, contentType string + want bool + }{ + {ImageManifestMediaType, ImageManifestMediaType, true}, + {ImageManifestMediaType, ImageIndexMediaType, false}, + {"*/*", ImageIndexMediaType, true}, + {"application/*", ImageIndexMediaType, true}, + {"text/*", ImageIndexMediaType, false}, + {"*/json", "application/json", true}, + {"*/xml", "application/json", false}, + {"APPLICATION/VND.OCI.IMAGE.INDEX.V1+JSON", ImageIndexMediaType, true}, + {ImageIndexMediaType + ";q=0", ImageIndexMediaType, false}, + {"*/*, " + ImageIndexMediaType + ";q=0", ImageIndexMediaType, false}, + {"*/*;q=0, " + ImageIndexMediaType, ImageIndexMediaType, true}, + {"application/*;q=0, */*", ImageIndexMediaType, false}, + {"*/*;q=0, application/*", ImageIndexMediaType, true}, + {"application/*, application/json;q=0", "application/json", false}, + {ImageIndexMediaType + ";q=0.5", ImageIndexMediaType, true}, + {ImageIndexMediaType + ";q=2", ImageIndexMediaType, false}, + {ImageIndexMediaType + ";q=-1", ImageIndexMediaType, false}, + {ImageIndexMediaType + ";q=x", ImageIndexMediaType, false}, + {"application/json;charset=utf-8", "application/json", false}, + {"application/json;charset=utf-8", "application/json; charset=utf-8", true}, + {"application/json;charset=utf-8;q=0, application/json", "application/json; charset=utf-8", false}, + {"application/json;q=0, application/json;charset=utf-8", "application/json; charset=utf-8", true}, + {"application/json;a=1;q=0, application/json;a=1;b=2", "application/json; a=1; b=2", true}, + {"application/json;a=1;b=2;q=0, application/json;a=1", "application/json; a=1; b=2", false}, + {"bad;;", ImageIndexMediaType, false}, + {"json", "application/json", false}, + {ImageIndexMediaType, "bad;;", false}, + {ImageIndexMediaType, "nojsontype", false}, + {"", ImageIndexMediaType, false}, + } + for _, tt := range tests { + if got := Accepts(tt.accept, tt.contentType); got != tt.want { + t.Errorf("Accepts(%q, %q) = %v, want %v", tt.accept, tt.contentType, got, tt.want) + } + } +} + +func TestAcceptsIndex(t *testing.T) { + for accept, want := range map[string]bool{ + ImageIndexMediaType: true, + DockerManifestListMediaType: true, + ImageManifestMediaType: false, + "*/*": true, + } { + if got := AcceptsIndex(accept); got != want { + t.Errorf("AcceptsIndex(%q) = %v, want %v", accept, got, want) + } + } +} + +func TestNames(t *testing.T) { + tests := []struct { + accept string + want bool + }{ + {ImageIndexMediaType, true}, + {ImageManifestMediaType + ", " + ImageIndexMediaType, true}, + {"*/*", false}, + {ImageIndexMediaType + ";q=0", false}, + {ImageIndexMediaType + ";q=0, */*", false}, + {"bad;;, " + ImageIndexMediaType, true}, + } + for _, tt := range tests { + if got := Names(tt.accept, ImageIndexMediaType); got != tt.want { + t.Errorf("Names(%q) = %v, want %v", tt.accept, got, tt.want) + } + } +} + +func TestIsIndexMediaType(t *testing.T) { + for contentType, want := range map[string]bool{ + ImageIndexMediaType: true, + DockerManifestListMediaType: true, + ImageIndexMediaType + "; charset=x": true, + ImageManifestMediaType: false, + "bad;;": false, + "": false, + } { + if got := IsIndexMediaType(contentType); got != want { + t.Errorf("IsIndexMediaType(%q) = %v, want %v", contentType, got, want) + } + } +} + +func TestNormalizeAccept(t *testing.T) { + tests := []struct{ in, want string }{ + {"", ""}, + {" , ", ""}, + {"B/X, a/y", "a/y,b/x"}, + {"a/y, a/y", "a/y"}, + {"a/y;q=1", "a/y"}, + {"a/y;q=1.0", "a/y"}, + {"a/y;q=0.50", "a/y;q=0.5"}, + {"a/y;q=bad", "a/y;q=bad"}, + {"a/y;Z=1;b=2", "a/y;b=2;z=1"}, + {"BAD;;", "bad;;"}, + {"a/y, ,", "a/y"}, + {"e/e, d/d, c/c, b/b, a/a, f/f", "a/a,b/b,c/c,d/d,e/e,f/f"}, + } + for _, tt := range tests { + if got := NormalizeAccept(tt.in); got != tt.want { + t.Errorf("NormalizeAccept(%q) = %q, want %q", tt.in, got, tt.want) + } + } +} + +func TestDefaultManifestAccept(t *testing.T) { + for _, mediaType := range []string{ImageManifestMediaType, ImageIndexMediaType, DockerManifestMediaType, DockerManifestListMediaType, DockerSignedManifestType} { + if !Names(DefaultManifestAccept, mediaType) { + t.Errorf("DefaultManifestAccept doesn't name %s", mediaType) + } + } +} + +func TestManifestRefs(t *testing.T) { + d := func(c byte) string { return "sha256:" + strings.Repeat(string(c), 64) } + tests := []struct { + name string + body string + want []string + }{ + {"empty", "", nil}, + {"not JSON", "{", nil}, + {"none", `{"schemaVersion":2}`, nil}, + {"index", `{"manifests":[{"digest":"` + d('a') + `"},{"digest":"` + d('b') + `"}]}`, []string{d('a'), d('b')}}, + {"image", `{"config":{"digest":"` + d('c') + `"},"layers":[{"digest":"` + d('a') + `"}]}`, []string{d('a'), d('c')}}, + {"duplicates and bad digests", `{"layers":[{"digest":"` + d('a') + `"},{"digest":"` + d('a') + `"},{"digest":"md5:x"}]}`, []string{d('a')}}, + {"sha512", `{"layers":[{"digest":"sha512:` + strings.Repeat("f", 128) + `"}]}`, []string{"sha512:" + strings.Repeat("f", 128)}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := ManifestRefs([]byte(tt.body)); !slices.Equal(got, tt.want) { + t.Errorf("ManifestRefs = %v, want %v", got, tt.want) + } + }) + } +} + +func TestManifestRefsLimit(t *testing.T) { + build := func(n int) []byte { + var b strings.Builder + b.WriteString(`{"layers":[`) + for i := range n { + if i > 0 { + b.WriteString(",") + } + b.WriteString(`{"digest":"sha256:`) + b.WriteString(strings.Repeat("0", 56)) + b.WriteString(strings.Repeat("0", 8-len(strconv.Itoa(i)))) + b.WriteString(strconv.Itoa(i)) + b.WriteString(`"}`) + } + b.WriteString("]}") + return []byte(b.String()) + } + if got := ManifestRefs(build(MaxManifestRefs)); len(got) != MaxManifestRefs { + t.Errorf("at the limit: %d refs, want %d", len(got), MaxManifestRefs) + } + if got := ManifestRefs(build(MaxManifestRefs + 1)); got != nil { + t.Errorf("over the limit: %d refs, want none", len(got)) + } +}