Documentation
¶
Overview ¶
Package proxy serves proxy repositories: files are fetched from the repository's upstream on first request, cached content-addressed in the blob store, recorded in proxy_cache_entries (which also backs the repository's package listing) and served from the cache until their TTL expires. When an expired entry cannot be revalidated because the upstream is down, it is served stale for up to the repository's max_stale_seconds.
Index ¶
- Constants
- Variables
- func CleanPath(p string) (string, bool)
- func Immutable(format, key string) bool
- func PackageCoordinates(format, cacheKey string) (string, string, bool)
- func Register(format string, h Hooks)
- type Hooks
- type Service
- func (s *Service) Open(ctx context.Context, repo *models.Repository, relPath string) (io.ReadCloser, error)
- func (s *Service) Serve(w http.ResponseWriter, r *http.Request, repo *models.Repository, ...)
- func (s *Service) ServeOCI(w http.ResponseWriter, r *http.Request, repo *models.Repository, ...)
- func (s *Service) ServeTerraformDownload(w http.ResponseWriter, r *http.Request, repo *models.Repository, ...)
- func (s *Service) SetBaseURL(baseURL string)
- func (s *Service) WithDockerDigestTTL(ttl time.Duration) *Service
- func (s *Service) WithTerraformTicketKey(secret []byte) *Service
- func (s *Service) WithUpstreamStallTimeout(d time.Duration) *Service
- type ServiceStore
Constants ¶
const ( // DefaultMaxBody caps any single file fetched from an upstream. DefaultMaxBody int64 = 4 << 30 // 4 GiB // DefaultMaxMetadata caps an index or metadata file fetched from an // upstream (Packages, repodata, packuments, simple pages, maven-metadata, // cargo and helm indexes, Go version lists). The largest real ones are // tens of MiB; a hostile upstream must not make the proxy spool and store // gigabytes under a metadata name. DefaultMaxMetadata int64 = 256 << 20 // DefaultUpstreamStallTimeout is how long an upstream response body may // deliver no data before the fetch fails, so a dead connection releases // its flight (and the requests waiting on it) in a minute rather than // holding it until fetchTimeout. DefaultUpstreamStallTimeout = 60 * time.Second )
const DefaultMaxCondaIndex int64 = 2 << 30
DefaultMaxCondaIndex caps one repodata file fetched from a conda upstream, both as downloaded and decompressed. The conda-forge linux-64 repodata.json is about 460 MB (59 MB as .zst) and keeps growing, far beyond what any other format's index reaches, so it has a limit of its own.
Variables ¶
var APKHooks = Hooks{ Fetch: (*Service).fetchAPK, Immutable: apkPackageKey, IsMetadata: apkIndexKey, }
APKHooks is the proxy hooks of the apk format.
var AnsibleHooks = Hooks{ Serve: (*Service).serveAnsible, Immutable: func(key string) bool { return strings.HasPrefix(key, ansibleArtifactDir) }, IsMetadata: func(key string) bool { return !strings.HasPrefix(key, ansibleArtifactDir) }, BlobPath: presign.AnsibleBlobPath, }
AnsibleHooks is the proxy hooks of the ansible format.
var CargoHooks = Hooks{ Serve: (*Service).serveCargo, Immutable: func(key string) bool { return strings.HasPrefix(key, cargoCrateDir) && keyName(key) == "download" }, IsMetadata: func(key string) bool { return !strings.HasPrefix(key, cargoCrateDir) }, BlobPath: presign.CargoBlobPath, }
CargoHooks is the proxy hooks of the cargo format.
var ComposerHooks = Hooks{ Serve: (*Service).serveComposer, Immutable: composerDistImmutable, IsMetadata: func(key string) bool { return !strings.HasPrefix(key, composerDistDir) }, BlobPath: presign.ComposerBlobPath, }
ComposerHooks is the proxy hooks of the composer format.
var ConanHooks = Hooks{ Serve: (*Service).serveConan, Immutable: conanRevisionFile, IsMetadata: func(key string) bool { return !strings.Contains(key, "/files/") }, BlobPath: presign.ConanBlobPath, }
ConanHooks is the proxy hooks of the conan format.
var CondaHooks = Hooks{ Serve: (*Service).serveConda, Immutable: func(key string) bool { return condaImmutable(keyName(key)) }, IsMetadata: func(key string) bool { return !condaImmutable(keyName(key)) }, IsLargeMetadata: isCondaIndexKey, PackageExts: []string{conda.ExtConda, conda.ExtTarBz2}, BlobPath: presign.CondaBlobPath, }
CondaHooks is the proxy hooks of the conda format.
var DebHooks = Hooks{ Immutable: func(key string) bool { name := keyName(key) return inDir(key, "pool") && (strings.HasSuffix(name, ".deb") || strings.HasSuffix(name, ".udeb")) }, IsMetadata: func(key string) bool { return inDir(key, "dists") }, PackageExts: []string{".deb", ".udeb"}, BlobPath: presign.DebBlobPath, }
DebHooks is the proxy hooks of the deb format.
var DockerHooks = Hooks{ Immutable: func(key string) bool { return digestRE.MatchString(keyName(key)) }, }
DockerHooks is the proxy hooks of the docker format. Docker is served by ServeOCI, not by path: it has no Serve hook, and its manifests are sized by the OCI path, so it has no metadata rule.
var ErrBlocked = errors.New("proxy: repository is blocked")
ErrBlocked is returned by Open for a blocked proxy repository.
var ErrNotFound = errors.New("proxy: not found upstream")
ErrNotFound is returned by Open for a file the upstream does not have.
var GoHooks = Hooks{ Serve: (*Service).serveGo, Immutable: goImmutable, IsMetadata: func(key string) bool { return keyName(key) == "list" || strings.HasSuffix(key, "/@latest") }, BlobPath: presign.GoBlobPath, }
GoHooks is the proxy hooks of the go format.
var HelmHooks = Hooks{ Serve: (*Service).serveHelm, Immutable: func(key string) bool { return strings.HasPrefix(key, helmChartsDir) && !strings.HasSuffix(keyName(key), helmProvExt) }, IsMetadata: func(key string) bool { return keyName(key) == helmIndexKey }, BlobPath: presign.HelmBlobPath, }
HelmHooks is the proxy hooks of the helm format.
var IvyHooks = Hooks{ Fetch: (*Service).fetchIvy, Immutable: ivyImmutable, IsMetadata: func(key string) bool { return isIvyMetadata(key) || isIvySidecar(key) || keyName(key) == "ivy.xml" }, PackageExts: ivyPackageExts, }
IvyHooks is the proxy hooks of the ivy format; the sbt format shares them (SbtHooks): the two layouts differ in the upstream's directory naming only.
var MavenHooks = Hooks{ Immutable: mavenImmutable, IsMetadata: func(key string) bool { return strings.HasPrefix(keyName(key), "maven-metadata") }, PackageExts: []string{".jar", ".pom", ".zip", ".war", ".ear", ".aar", ".module", ".gz"}, BlobPath: presign.MavenBlobPath, }
MavenHooks is the proxy hooks of the maven format.
var NPMHooks = Hooks{ Serve: (*Service).serveNPM, Immutable: func(key string) bool { return strings.HasSuffix(keyName(key), ".tgz") && strings.Contains(key, "/-/") }, IsMetadata: func(key string) bool { return !strings.Contains(key, "/-/") }, BlobPath: presign.NPMBlobPath, }
NPMHooks is the proxy hooks of the npm format.
var NixHooks = Hooks{ Fetch: (*Service).fetchNix, Immutable: nixNarKey, IsMetadata: nixMetadataKey, PackageExts: []string{".nar", ".nar.xz", ".nar.zst", ".nar.bz2", ".nar.br", ".nar.gz", ".nar.lz4"}, BlobPath: presign.NixBlobPath, }
NixHooks is the proxy hooks of the nix format.
var NuGetHooks = Hooks{ Serve: (*Service).serveNuGet, Immutable: nugetImmutable, IsMetadata: func(key string) bool { return !strings.HasPrefix(key, nugetPackageDir) }, BlobPath: presign.NuGetBlobPath, }
NuGetHooks is the proxy hooks of the nuget format.
var PacmanHooks = Hooks{ IsMetadata: isPacmanDatabase, PackageExts: []string{".pkg.tar.zst", ".pkg.tar.xz", ".pkg.tar.gz", ".pkg.tar.bz2", ".pkg.tar.lz4", ".pkg.tar"}, CapTTL: func(key string, ttl time.Duration) time.Duration { if isPacmanDatabase(key) { return min(ttl, pacmanDBMaxTTL) } return ttl }, WriteEntry: func( _ *Service, w http.ResponseWriter, r *http.Request, _ *models.Repository, entry *models.ProxyCacheEntry, key string, _ io.Reader, ) bool { return pacmanNotModified(w, r, entry, key) }, BlobPath: presign.PacmanBlobPath, }
PacmanHooks is the proxy hooks of the pacman format. Package files have no immutable rule: a mirror may republish a package file name, so they use the repository TTL.
var PyPIHooks = Hooks{ Serve: (*Service).servePyPI, Immutable: func(key string) bool { return strings.HasPrefix(key, "files/") }, IsMetadata: func(key string) bool { return !strings.HasPrefix(key, "files/") }, BlobPath: presign.PyPIBlobPath, }
PyPIHooks is the proxy hooks of the pypi format.
var RPMHooks = Hooks{ Immutable: func(key string) bool { return inDir(key, "Packages") && strings.HasSuffix(keyName(key), ".rpm") }, IsMetadata: func(key string) bool { return inDir(key, "repodata") }, PackageExts: []string{".rpm"}, BlobPath: presign.RPMBlobPath, }
RPMHooks is the proxy hooks of the rpm format.
var RawHooks = Hooks{ BlobPath: presign.RawBlobPath, }
RawHooks is the proxy hooks of the raw format: every file is a download, there are no index files and nothing is immutable.
var RubyGemsHooks = Hooks{ Serve: (*Service).serveRubyGems, Immutable: func(key string) bool { return strings.HasPrefix(key, rubygemsPackageDir) && strings.HasSuffix(keyName(key), ".gem") }, IsMetadata: func(key string) bool { return !strings.HasPrefix(key, rubygemsPackageDir) }, WriteEntry: func( s *Service, w http.ResponseWriter, r *http.Request, repo *models.Repository, entry *models.ProxyCacheEntry, key string, body io.Reader, ) bool { if !rubygemsCompact(key) { return false } s.writeCompactEntry(w, r, repo, entry, body) return true }, BlobPath: presign.RubyGemsBlobPath, }
RubyGemsHooks is the proxy hooks of the rubygems format.
var SbtHooks = IvyHooks //nolint:gochecknoglobals // format hook table
SbtHooks is the proxy hooks of the sbt format: the same as IvyHooks.
var TerraformHooks = Hooks{ Serve: (*Service).serveTerraform, Immutable: tfProviderZipKey, IsMetadata: func(key string) bool { return !tfArchiveKey(key) }, PackageExts: tfArchiveExts, BlobPath: presign.TerraformBlobPath, }
TerraformHooks is the proxy hooks of the terraform format.
Functions ¶
func CleanPath ¶ added in v0.4.0
CleanPath validates a client-supplied repository-relative path and returns it without the leading slash. Empty paths, directory paths (trailing slash), empty/dot/dot-dot segments, backslashes and control characters are refused: the path is appended to the upstream URL and must not be able to escape it.
func Immutable ¶ added in v0.4.0
Immutable reports whether the file at key never changes once published, so a cached copy never needs revalidation. Formats whose bodies are verified against a published digest (see fetchOpts) pin by name alone; the ones that have no such check here (deb, Maven, pacman, rpm) pin only under layouts whose file names are never reused, and everything else is cached for the repository TTL so a wrong copy is replaced on revalidation. The rule of each format is its Hooks.Immutable:
- apk: `.apk` files of a `<branch>/<repo>/<arch>/<file>` key; they are only cached once their checksum matched the upstream index (apk.go).
- composer: dists of released versions (not branches), which are refused when they differ from a non-empty shasum; the reference in the key names the content (composer.go).
- deb: .deb/.udeb below a pool/ directory (the Debian archive layout, where a file name is never reused); the same names in a flat repository, where a publisher may overwrite a package, use the repository TTL.
- ivy, sbt: released files, not checksum or signature files, maven-metadata*.xml or -SNAPSHOT files; a file is pinned only when its body matched the checksum the upstream publishes (ivy.go), otherwise the repository TTL applies.
- maven: released artifacts, not maven-metadata*.xml, archetype-catalog.xml (both are regenerated in place) or -SNAPSHOT files; a checksum or signature file (.md5 .sha1 .sha256 .sha512 .asc) is as immutable as the file it belongs to.
- nix: nar/ files, cached only after their body matched the FileHash and FileSize of their narinfo (nix.go); narinfo and nix-cache-info move.
- pacman: nothing. A mirror may republish a package file name, so package files use the repository TTL.
- rpm: .rpm below a Packages/ directory (the layout of Fedora, CentOS, RHEL and most vendor repositories, whose NEVRA-named files are not rebuilt in place); flat or other layouts use the repository TTL. No cheap integrity signal (the repodata checksums are not checked by this proxy) exists to pin the rest.
An unregistered format has no immutable file.
func PackageCoordinates ¶ added in v0.14.0
PackageCoordinates recovers the package name and version from the cache key (the upstream-relative key a proxy repository stores a file under) of a cached package artifact, in the shapes OSV advisories use: npm "name" or "@scope/name", PyPI project name as in the key (callers normalise), Maven "group:artifact", crates.io/RubyGems/NuGet id, Go module path (case decoded) with its "v" version prefix, Helm chart name.
ok is false for every key that is not a package artifact (indexes, packuments, simple pages, checksums, signatures, .info/.mod/list files, ...), for malformed keys and for formats whose keys carry no version.
Types ¶
type Hooks ¶ added in v0.15.0
type Hooks struct {
// Serve answers a GET/HEAD for rel, the path below the repository root,
// for the formats that map upstream paths to their own cache keys and
// verification (pipeline.go). Nil mirrors the upstream path by path
// through resolve, with the generic quarantine, presign and stale
// handling of serveResolved.
Serve func(s *Service, w http.ResponseWriter, r *http.Request, repo *models.Repository, rel string)
// Fetch downloads key from target, the upstream URL of key, and records
// the cache entry, for the formats that verify a file against a published
// digest or have a flow of their own (apk, ivy, nix, sbt). Nil is a plain
// fetch of target.
Fetch func(s *Service, ctx context.Context, repo *models.Repository, key, target string) (*models.ProxyCacheEntry, error)
// Immutable reports whether the cached file at key never changes once
// published (see Immutable). Nil means no key is: every file uses the
// repository TTL.
Immutable func(key string) bool
// IsMetadata reports whether key names an index or metadata file
// (small by nature, capped at the service's metadata limit) rather than a
// package file. Nil means no key is.
IsMetadata func(key string) bool
// IsLargeMetadata reports whether key is a metadata file that outgrows the
// common metadata limit (conda repodata); it is capped at the service's
// separate large-index limit instead of IsMetadata's. Nil means none is.
IsLargeMetadata func(key string) bool
// PackageExts lists the file extensions that name a binary package for the
// formats whose files are not checked against a digest: an upstream HTML
// answer (captive portal, WAF challenge) for such a path is refused rather
// than cached. Empty disables the check.
PackageExts []string
// CapTTL narrows the cache lifetime ttl (the repository TTL, or the
// immutable one) of key, for files that must refresh sooner than the
// repository default (pacman sync databases). Nil leaves ttl unchanged.
CapTTL func(key string, ttl time.Duration) time.Duration
// WriteEntry answers a cached file the format serves in its own way
// (rubygems compact index, pacman database not-modified) and reports
// whether it did; false falls through to the generic entry writer. It
// runs after the quarantine and presign steps of serveResolved. Nil
// always falls through.
WriteEntry func(
s *Service, w http.ResponseWriter, r *http.Request, repo *models.Repository, entry *models.ProxyCacheEntry, key string, body io.Reader,
) bool
// BlobPath reports whether rel, a file below the repository root, is a
// package download that may be redirected to the object store rather than
// metadata (see presign.Register). Register hands it to presign. Nil means
// nothing is redirected.
BlobPath func(rel string) bool
}
Hooks is everything the proxy decides per format. Each proxy-capable format has one value (CargoHooks, NPMHooks, ...), defined next to the format's code and registered with Register at startup; nothing is registered implicitly. A nil field is the default documented on it, which is what the formats with nothing to say there (apk, deb, ivy, maven, nix, pacman, raw, rpm, sbt) always had.
A format that is not registered is served by the path-mirroring default with no immutable, metadata or package-extension rule, and is never redirected to the object store.
type Service ¶ added in v0.4.0
type Service struct {
// contains filtered or unexported fields
}
Service fetches and caches upstream files for proxy repositories.
func NewService ¶ added in v0.4.0
NewService creates the proxy service. Upstream requests use an SSRF-safe client: blocked destination addresses are refused at dial time and on every redirect hop.
func (*Service) Open ¶ added in v0.8.0
func (s *Service) Open(ctx context.Context, repo *models.Repository, relPath string) (io.ReadCloser, error)
Open returns the body of relPath of a path-mirrored proxy repository (deb, maven, raw, rpm), fetching and caching it exactly as Serve would. It is for server-side consumers of upstream metadata (deb/rpm groups merging a proxy member's indexes), which read it once and must see what a client of the proxy would. An expired entry is revalidated, and served stale when the upstream is down within the repository's max-stale window. ErrNotFound is returned for an upstream 404; any other error means the file could not be obtained. The caller closes the reader.
func (*Service) Serve ¶ added in v0.4.0
func (s *Service) Serve(w http.ResponseWriter, r *http.Request, repo *models.Repository, relPath string)
Serve answers a GET/HEAD for relPath (the path below the repository root) of proxy repo.
func (*Service) ServeOCI ¶ added in v0.6.0
func (s *Service) ServeOCI(w http.ResponseWriter, r *http.Request, repo *models.Repository, req ocipath.Request)
ServeOCI answers a request under /v2/ for the docker proxy repository repo: manifests and blobs are pulled through (and cached), tag and referrer listings are passed through, anything that would write is refused. req is the parsed /v2/<repo>/<image>/... path.
func (*Service) ServeTerraformDownload ¶ added in v0.13.0
func (s *Service) ServeTerraformDownload(w http.ResponseWriter, r *http.Request, repo *models.Repository, d terraform.Download)
ServeTerraformDownload serves the file a ticket of proxy repo names, fetching it from its upstream host first when it is not cached (terraform.ProxyServer). The ticket's coordinates were validated by the caller; the requested file name must be the one the documents served by this proxy carry.
func (*Service) SetBaseURL ¶ added in v0.6.0
SetBaseURL sets BASE_URL, the explicit override of the origin rewritten tarball URLs point at ("" derives it from each request). Call it before serving requests.
func (*Service) WithDockerDigestTTL ¶ added in v0.8.0
WithDockerDigestTTL sets how long a docker manifest or blob addressed by digest stays cached without being used. Such an entry never changes, so until now it never expired; with a positive ttl the cache worker evicts it (and its blob, once no other entry references it) after ttl without a pull, and every pull that finds it past half its lifetime renews it. 0 keeps the old behavior. It must be called before the service serves requests.
func (*Service) WithTerraformTicketKey ¶ added in v0.13.0
WithTerraformTicketKey sets the server HMAC secret the download tickets of Terraform proxy repositories are signed with (the secret the hosted registry verifies them with). Without it such repositories answer downloads with 503. Call it before serving requests.
func (*Service) WithUpstreamStallTimeout ¶ added in v0.13.0
WithUpstreamStallTimeout sets how long an upstream response body may deliver no data before the fetch fails (DefaultUpstreamStallTimeout by default); 0 disables the check. It must be called before the service serves requests.
type ServiceStore ¶ added in v0.15.0
type ServiceStore interface {
quarantine.Checker
DeleteProxyCacheEntry(ctx context.Context, repoID string, cacheKey string) error
EnsureBlob(ctx context.Context, sha256 string, mediaType string, size int64) (string, error)
GetProxyCacheEntry(ctx context.Context, repoID string, cacheKey string) (*models.ProxyCacheEntry, error)
UpsertProxyCacheEntry(ctx context.Context, entry *models.ProxyCacheEntry) error
}
ServiceStore is the part of the database Service needs.