Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion internal/handler/container.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -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
Expand Down
34 changes: 4 additions & 30 deletions internal/handler/container_image_refs.go
Original file line number Diff line number Diff line change
@@ -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-<hex>.sig, .att and .sbom tags of cosign.
Expand Down Expand Up @@ -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)
}
154 changes: 15 additions & 139 deletions internal/handler/container_manifest.go
Original file line number Diff line number Diff line change
Expand Up @@ -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]+$`)
Expand Down Expand Up @@ -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
Expand All @@ -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)
Expand Down Expand Up @@ -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 != "" {
Expand Down
31 changes: 9 additions & 22 deletions internal/handler/container_mirror.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import (
"sync/atomic"
"time"

"github.com/git-pkgs/proxy/internal/metadata/oci"
"golang.org/x/sync/errgroup"
)

Expand All @@ -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
Expand Down Expand Up @@ -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
Expand Down
Loading
Loading