diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..05fb224 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,17 @@ +# Version and commit come in as build args, so the build doesn't need .git. +.git +.github + +# Local build output and runtime data +/proxy +dist/ +build/ +cache/ +*.db +*.tar.gz + +# Local config and secrets +.env +.env.local +proxy.cfg +config.yaml diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c4b7776..4d2e324 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -31,6 +31,40 @@ jobs: - name: Test run: go test -v -race ./... + postgres: + name: test (postgres) + runs-on: ubuntu-latest + services: + postgres: + image: postgres:17@sha256:b8faeff7712663c2773a190181e1246e37e364b887611c04658c28b44e2408fe + env: + POSTGRES_PASSWORD: test + POSTGRES_DB: proxy + ports: + - 5432:5432 + options: >- + --health-cmd "pg_isready -U postgres -d proxy" + --health-interval 2s + --health-timeout 5s + --health-retries 30 + + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Set up Go + uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 + with: + go-version-file: go.mod + + # The packages with tests that need PROXY_DATABASE_URL. -p 1 because + # their tests drop and recreate tables in the one shared database. + - name: Test + env: + PROXY_DATABASE_URL: postgres://postgres:test@localhost:5432/proxy?sslmode=disable + run: go test -v -race -p 1 ./internal/database/... ./internal/handler/... ./internal/server/... + lint: runs-on: ubuntu-latest steps: @@ -44,7 +78,7 @@ jobs: go-version-file: go.mod - name: Install golangci-lint - run: go install github.com/golangci/golangci-lint/v2/cmd/golangci-lint@v2.13.1 + run: go install github.com/golangci/golangci-lint/v2/cmd/golangci-lint@v2.15.0 - name: golangci-lint run: golangci-lint run ./... @@ -76,3 +110,13 @@ jobs: --set 'ingress.hosts[0].paths[0].path=/' \ --set 'ingress.hosts[0].paths[0].pathType=Prefix' \ >/dev/null + helm template proxy deploy/charts/proxy \ + --set 'extraVolumes[0].name=corp-ca' \ + --set 'extraVolumes[0].configMap.name=corp-ca' \ + --set 'extraVolumeMounts[0].name=corp-ca' \ + --set 'extraVolumeMounts[0].mountPath=/etc/proxy/ca' \ + --set 'extraVolumeMounts[0].readOnly=true' \ + --set 'extraInitContainers[0].name=wait-for-db' \ + --set 'extraInitContainers[0].image=busybox:1.37' \ + --set 'extraInitContainers[0].command={sh,-c,exit 0}' \ + >/dev/null diff --git a/.github/workflows/monthly-release.yml b/.github/workflows/monthly-release.yml new file mode 100644 index 0000000..b0da481 --- /dev/null +++ b/.github/workflows/monthly-release.yml @@ -0,0 +1,137 @@ +name: Monthly release + +# Cuts a release on the 1st of each month when main is green and something +# has merged since the last release: a patch release, or a new minor version +# if a pull request labelled "breaking" was merged (a new major version from +# 1.0 on). A breaking release is created as a draft, and its images and chart +# are published only when someone publishes the draft, after writing the +# upgrade notes. Scheduled runs only report what they would do until the +# repository variable MONTHLY_RELEASE is "true". + +on: + schedule: + - cron: "0 6 1 * *" + workflow_dispatch: + inputs: + dry_run: + description: Only report what would be released + type: boolean + default: true + +permissions: {} + +concurrency: + group: monthly-release + +jobs: + release: + runs-on: ubuntu-latest + permissions: + contents: write + actions: write + checks: read + pull-requests: read + env: + GH_TOKEN: ${{ github.token }} + REPO: ${{ github.repository }} + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: main + fetch-depth: 0 + persist-credentials: false + + - name: Decide whether to release + id: plan + env: + EVENT: ${{ github.event_name }} + INPUT_DRY_RUN: ${{ inputs.dry_run }} + ENABLED: ${{ vars.MONTHLY_RELEASE }} + run: | + set -euo pipefail + if [ "$EVENT" = workflow_dispatch ]; then + dry_run=$INPUT_DRY_RUN + elif [ "$ENABLED" = true ]; then + dry_run=false + else + dry_run=true + fi + echo "dry_run=$dry_run" >> "$GITHUB_OUTPUT" + + sha=$(git rev-parse HEAD) + last=$(git describe --tags --abbrev=0 --match 'v[0-9]*.[0-9]*.[0-9]*' --exclude '*-*') + # A breaking release waits as a draft for its upgrade notes. Building + # on its tag would publish those changes without them. Older tags + # were released by hand and may have no release at all. + draft=$(gh release view "$last" -R "$REPO" --json isDraft --jq .isDraft 2>/dev/null || echo false) + if [ "$draft" = true ]; then + echo "::warning::$last is still a draft, publish it first" + exit 0 + fi + merged=$(git rev-list --count "$last..$sha") + if [ "$merged" -eq 0 ]; then + echo "Nothing merged since $last" + exit 0 + fi + + # Every check on main's HEAD must have finished green. This run + # shows up as a check on the same commit, so it is left out. + bad=$(gh api --paginate "repos/$REPO/commits/$sha/check-runs?per_page=100" \ + --jq ".check_runs[] + | select(.html_url | contains(\"/actions/runs/$GITHUB_RUN_ID/\") | not) + | select(.status != \"completed\" + or (.conclusion | IN(\"success\", \"skipped\", \"neutral\") | not)) + | .name") + if [ -n "$bad" ]; then + echo "::warning::main ($sha) is not green, skipping: $(echo "$bad" | sort -u | paste -sd, -)" + exit 0 + fi + + since=$(git log -1 --format=%cI "$last") + breaking=$(gh pr list -R "$REPO" --state merged --base main --limit 1000 \ + --search "merged:>$since label:breaking" --json number --jq '.[].number') + + IFS=. read -r major minor patch <<<"${last#v}" + if [ -z "$breaking" ]; then + tag="v$major.$minor.$((patch + 1))" + else + echo "Breaking changes merged since $last: #$(echo "$breaking" | sort -n | paste -sd, - | sed 's/,/, #/g')" + if [ "$major" -eq 0 ]; then + tag="v0.$((minor + 1)).0" + else + tag="v$((major + 1)).0.0" + fi + fi + echo "$merged commits since $last, next release $tag at $sha" + echo "tag=$tag" >> "$GITHUB_OUTPUT" + echo "sha=$sha" >> "$GITHUB_OUTPUT" + echo "draft=$([ -n "$breaking" ] && echo true || echo false)" >> "$GITHUB_OUTPUT" + + # A tag pushed with GITHUB_TOKEN doesn't start other workflows, so the + # release workflows are dispatched on the new tag instead. + - name: Tag and start the release workflows + if: steps.plan.outputs.tag != '' + env: + TAG: ${{ steps.plan.outputs.tag }} + SHA: ${{ steps.plan.outputs.sha }} + DRY_RUN: ${{ steps.plan.outputs.dry_run }} + DRAFT: ${{ steps.plan.outputs.draft }} + run: | + set -euo pipefail + if [ "$DRAFT" = true ]; then + what="start release.yml for a draft release" + else + what="start release.yml and publish.yml" + fi + if [ "$DRY_RUN" = true ]; then + echo "Dry run: would tag $TAG at $SHA and $what" + exit 0 + fi + gh api "repos/$REPO/git/refs" -f ref="refs/tags/$TAG" -f sha="$SHA" >/dev/null + gh workflow run release.yml -R "$REPO" --ref "$TAG" -f draft="$DRAFT" + if [ "$DRAFT" = true ]; then + echo "::notice::$TAG is a draft release: add the upgrade notes and publish it to push the images and chart" + else + gh workflow run publish.yml -R "$REPO" --ref "$TAG" + fi + echo "Tagged $TAG at $SHA" diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index b7ac470..e325a8a 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -5,6 +5,10 @@ on: push: tags: - "v*" + # A draft release made by monthly-release.yml is published by hand. Releases + # published with GITHUB_TOKEN don't start this. + release: + types: [published] permissions: {} @@ -34,7 +38,7 @@ jobs: uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1 - name: Log in to the Container registry - uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f + uses: docker/login-action@81c6f93d4bc991e510b342a00b419b3bb4efc5c6 with: registry: ghcr.io username: ${{ github.actor }} @@ -57,6 +61,9 @@ jobs: push: true tags: ${{ steps.meta.outputs.tags }} labels: ${{ steps.meta.outputs.labels }} + build-args: | + VERSION=${{ steps.meta.outputs.version }} + COMMIT=${{ github.sha }} provenance: mode=max sbom: true diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 5d32181..491d6ec 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -4,6 +4,13 @@ on: push: tags: - "v*" + # Started by monthly-release.yml on the tag it creates. + workflow_dispatch: + inputs: + draft: + description: Create the release as a draft + type: boolean + default: false permissions: contents: write @@ -11,6 +18,7 @@ permissions: jobs: release: + if: github.ref_type == 'tag' runs-on: ubuntu-latest steps: @@ -27,9 +35,9 @@ jobs: go-version-file: go.mod cache: false - - uses: goreleaser/goreleaser-action@f06c13b6b1a9625abc9e6e439d9c05a8f2190e94 # v7.2.3 + - uses: goreleaser/goreleaser-action@a4f02ab5355a589de60d917a659ce617ed19b3de # v7.3.0 with: version: "~> v2" - args: release --clean + args: release --clean${{ inputs.draft && ' --draft' || '' }} env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/zizmor.yml b/.github/workflows/zizmor.yml index 1f6df79..00041a6 100644 --- a/.github/workflows/zizmor.yml +++ b/.github/workflows/zizmor.yml @@ -34,4 +34,4 @@ jobs: persist-credentials: false - name: Run zizmor - uses: zizmorcore/zizmor-action@cc914d7f3750a2d13d75c7f184a1060aa0e9d482 # v0.6.4 + uses: zizmorcore/zizmor-action@53290badfa369cb0bf7ad16342cb62c2fa47ac7b # v0.8.0 diff --git a/.golangci.yml b/.golangci.yml index 9d4b957..57c0f69 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -26,3 +26,7 @@ linters: - goconst - dupl - mnd + +formatters: + enable: + - gofmt diff --git a/.goreleaser.yaml b/.goreleaser.yaml index e5881db..9aec8f9 100644 --- a/.goreleaser.yaml +++ b/.goreleaser.yaml @@ -15,6 +15,7 @@ builds: - linux - darwin - windows + - freebsd goarch: - amd64 - arm64 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 2c69728..6674b8c 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -212,6 +212,24 @@ Add PyPI registry support - Add tests for wheel and sdist downloads ``` +## Reviewing and Merging + +Maintainers are the members of the proxy team in the git-pkgs org. Any maintainer can review and merge. A pull request needs green CI and an approval from a maintainer other than its author. A "request changes" review from any maintainer blocks it until that reviewer approves or withdraws the review. + +Using AI to write or review is fine, but whoever approves a pull request should understand it and stand behind it. If it touches an ecosystem you don't use, you can ask someone who does to look before you approve. + +Open an issue before a bigger change: anything that changes behaviour users rely on, new configuration that would be hard to remove, or a change that fans out into other git-pkgs modules. If no maintainer objects within a few days, open the pull request; it's reviewed like any other. Objections are worked out in the issue, with @andrew breaking ties for now. Where possible, deprecate before removing: an old configuration key keeps working, with a warning, in at least one release before the one that removes it. + +## Releases + +A release is cut on the 1st of each month by `.github/workflows/monthly-release.yml` when `main` is green and something has merged since the last tag. It is a patch release, or a new minor version if a pull request labelled `breaking` was merged since then (a new major version from 1.0 on), so label pull requests that change behaviour users rely on. + +A patch release is published on its own. A breaking release is created as a draft, without images or a chart: write the upgrade notes in it and publish it, which starts `publish.yml` for the images and the chart. Until then the monthly run releases nothing. + +Scheduled runs only report what they would release until the repository variable `MONTHLY_RELEASE` is set to `true`. The workflow can also be started by hand from the Actions tab, as a dry run by default. + +To release by hand, push a `v*` tag. + ## Questions? Open an issue on GitHub if you have questions or need help getting started. diff --git a/Dockerfile b/Dockerfile index de784e8..d434e58 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,4 +1,4 @@ -FROM --platform=$BUILDPLATFORM golang:1.26.7-alpine AS builder +FROM --platform=$BUILDPLATFORM golang:1.27.3-alpine AS builder WORKDIR /src @@ -14,11 +14,15 @@ COPY . . # Build the binary for the target platform ARG TARGETARCH -RUN CGO_ENABLED=0 GOOS=linux GOARCH=${TARGETARCH} go build -ldflags="-s -w" -o /proxy ./cmd/proxy +ARG VERSION=dev +ARG COMMIT=unknown +RUN CGO_ENABLED=0 GOOS=linux GOARCH=${TARGETARCH} go build \ + -ldflags="-s -w -X main.Version=${VERSION} -X main.Commit=${COMMIT}" \ + -o /proxy ./cmd/proxy -FROM alpine:3.24.2 +FROM alpine:3.24.3 -RUN apk add --no-cache ca-certificates +RUN apk add --no-cache ca-certificates git COPY --from=builder /proxy /usr/local/bin/proxy @@ -31,5 +35,9 @@ WORKDIR /data EXPOSE 8080 +# /health checks the database and storage and can take up to ten seconds. +HEALTHCHECK --interval=30s --timeout=11s --start-period=10s --retries=3 \ + CMD wget -q -O /dev/null http://127.0.0.1:8080/health || exit 1 + ENTRYPOINT ["proxy"] CMD ["serve"] diff --git a/README.md b/README.md index 559f1a8..dff6964 100644 --- a/README.md +++ b/README.md @@ -20,6 +20,8 @@ A 3-day cooldown means that when `lodash` publishes version `4.18.0`, your build Resolution order: package override, then ecosystem override, then global default. This lets you set a conservative default and carve out exceptions for packages where you need faster updates. See [docs/configuration.md](docs/configuration.md) for the full config reference. +One instance can offer several cooldown policies through [named profiles](docs/configuration.md#cooldown-profiles). Configure `cooldown.profiles` and point clients at paths such as `/cooldown/3d/npm/` or `/cooldown/7d/cargo/`. Profiles share the package cache; existing URLs keep using the global policy. + ## Artifact Scanning Cooldown only looks at a version's publish timestamp — it never inspects the actual bytes. Artifact scanning closes that gap: when enabled, every artifact is staged into storage and scanned by one or more external services (trivy, ClamAV, Wiz, or anything else that speaks a small HTTP/JSON contract) before it's committed to the cache and served to clients. @@ -47,11 +49,11 @@ The proxy never uploads artifact bytes to a scanner. Each scanner is notified wi | npm | JavaScript | Yes | ✓ | | Cargo | Rust | Yes | ✓ | | RubyGems | Ruby | Yes | ✓ | -| Go proxy | Go | | ✓ | +| Go proxy | Go | Yes† | ✓ | | Hex | Elixir | Yes* | ✓ | | pub.dev | Dart | Yes | ✓ | | PyPI | Python | Yes | ✓ | -| Maven | Java | | ✓ | +| Maven | Java | Yes‡ | ✓ | | Gradle Build Cache | Java/Kotlin | | ✓ | | NuGet | .NET | Yes | ✓ | | Composer | PHP | Yes | ✓ | @@ -66,14 +68,20 @@ The proxy never uploads artifact bytes to a scanner. Each scanner is notified wi | RPM | RHEL/Fedora | | ✓ | | Alpine | Alpine Linux | | ✓ | | Arch | Arch Linux | | ✓ | -| Chef | Chef | | ✗ | +| FreeBSD | FreeBSD (ports and pkgbase) | | ✓ | +| Chef Supermarket | Chef | | ✓ | | Generic | Any | | ✓ | +| Git | Any | | ✓ | | Helm | Kubernetes | Yes | ✓ | | Vagrant | Vagrant | | ✗ | Cooldown requires publish timestamps in metadata. Registries without a "Yes" in the cooldown column either don't expose timestamps or haven't been wired up yet. -\* Hex cooldown requires disabling registry signature verification (`HEX_NO_VERIFY_REPO_ORIGIN=1`) since the proxy re-encodes the protobuf payload. +\* Hex cooldown requires disabling registry signature verification (`HEX_UNSAFE_REGISTRY=1`) since the proxy re-encodes the protobuf payload. Origin verification can stay enabled. + +† Go cooldown uses the time in each version's `.info`, which is the commit time of the tagged revision, not when the tag was pushed. + +‡ Maven cooldown uses the `Last-Modified` header of each version's `.pom`. On Maven Central that is the deploy time; a Nexus or Artifactory upstream may report when it cached the file instead. SNAPSHOT versions are not held back. ## Install @@ -81,7 +89,11 @@ Cooldown requires publish timestamps in metadata. Registries without a "Yes" in brew install git-pkgs/git-pkgs/proxy ``` -Or download a binary from the [releases page](https://github.com/git-pkgs/proxy/releases). +Or download a binary from the [releases page](https://github.com/git-pkgs/proxy/releases), or run the container image: + +```bash +docker run -p 8080:8080 -v proxy-data:/data ghcr.io/git-pkgs/proxy:latest +``` ### Helm @@ -98,6 +110,33 @@ using SQLite and filesystem artifact storage under `/data`. See [`deploy/charts/proxy/values.yaml`](deploy/charts/proxy/values.yaml) for ingress, external database and object-storage configuration options. +The SQLite database needs a local disk or a block-backed volume, even with one +replica; `ReadWriteOnce` alone doesn't guarantee that, since the storage class +can still be NFS. If the cluster only offers network filesystem storage, use +Postgres. Artifact storage can stay on NFS, separately from the database. See +[SQLite](docs/configuration.md#sqlite). + +To trust a private CA, for example when upstreams sit behind a TLS-intercepting +corporate proxy or are internal registries signed by an in-house CA, mount the +certificate with `extraVolumes` and `extraVolumeMounts` and add its directory +to `SSL_CERT_DIR`. The proxy process makes all upstream TLS connections itself, +Git fetches included, so no other configuration is needed. Public CAs stay +trusted alongside the private one: + +```yaml +extraVolumes: + - name: corp-ca + configMap: + name: corp-ca # e.g. key corp-ca.crt, PEM-encoded +extraVolumeMounts: + - name: corp-ca + mountPath: /etc/proxy/ca + readOnly: true +extraEnv: + - name: SSL_CERT_DIR + value: /etc/ssl/certs:/etc/proxy/ca +``` + ## Quick Start ```bash @@ -111,7 +150,8 @@ go build -o proxy ./cmd/proxy ./proxy -listen :3000 -base-url https://proxy.example.com ``` -The proxy is now running. Configure your package managers to use it. +The proxy is now running. Configure your package managers to use it. For image +builds, see [Using proxy in Docker builds](docs/docker-builds.md). ## OpenAPI (Swagger) @@ -159,9 +199,12 @@ through the proxy: the audit and signing-key endpoints are passed through to the configured upstream registry, with upstream authentication applied. Advisories therefore come from upstream's database, not from the proxy's own vulnerability data, and versions withheld by [cooldown](#version-cooldown) are not excluded -from the report. +from the report. Packuments point each version's attestations (provenance) at +the proxy, which fetches them from the package's registry and caches them; +attestations of versions held back by cooldown or blocked by the denylist are +not served. -To serve private packages through the same registry URL, see [Private package routes](docs/configuration.md#private-package-routes). +To serve private packages through the same registry URL, see [Private package routes](docs/configuration.md#private-package-routes). To see new releases before `metadata_ttl` runs out, see [Change feeds](docs/configuration.md#change-feeds). ### Cargo @@ -212,6 +255,14 @@ the `go` command contacts the database directly as before. Set checksum databases are listed under `upstream.go_sumdbs`, see [Go checksum database](docs/configuration.md#go-checksum-database). +govulncheck can use the proxy for the Go vulnerability database: + +```bash +govulncheck -db http://localhost:8080/go/vulndb ./... +``` + +See [Go vulnerability database](docs/configuration.md#go-vulnerability-database). + ### Homebrew Point Homebrew's JSON API and artifact domain at the proxy: @@ -223,7 +274,7 @@ export HOMEBREW_ARTIFACT_DOMAIN=http://localhost:8080 The artifact domain proxies manifests and bottle blobs under `/v2/homebrew/core/`. GHCR routing is limited to that repository. Source archives, cask application downloads, custom tap artifacts, and legacy flat-file bottle mirrors use Homebrew's normal fallback URLs. Keep fallback enabled by leaving `HOMEBREW_ARTIFACT_DOMAIN_NO_FALLBACK` unset. -Enable `cache_metadata` or set `PROXY_CACHE_METADATA=true` to retain Homebrew JSON API responses for offline fallback. Bottle blobs and their OCI manifests are cached without this setting. +Enable `cache_metadata` or set `PROXY_CACHE_METADATA=true` to retain Homebrew JSON API responses for offline fallback. Bottle blobs and their OCI manifests are cached without this setting. `proxy mirror pkg:brew/` pre-fetches a formula's bottles (see [Homebrew bottles](docs/configuration.md#homebrew-bottles)). The upstreams default to `https://formulae.brew.sh/api` for the JSON API and `https://ghcr.io` for artifacts. To chain this proxy to another proxy, configure its Homebrew endpoints as the upstreams: @@ -237,10 +288,10 @@ The equivalent environment variables are `PROXY_UPSTREAM_HOMEBREW_API` and `PROX ### Hex (Elixir) -Configure in `~/.hex/hex.config`: +Configure the mirror: -```erlang -{default_url, <<"http://localhost:8080/hex">>}. +```bash +mix hex.config mirror_url http://localhost:8080/hex ``` Or set the environment variable: @@ -249,6 +300,14 @@ Or set the environment variable: export HEX_MIRROR=http://localhost:8080/hex ``` +When the proxy applies a cooldown, also set: + +```bash +export HEX_UNSAFE_REGISTRY=1 +``` + +Filtering releases removes the registry signature. The proxy preserves the package name and repository fields, so origin verification can stay enabled. Without a cooldown, leave signature verification enabled too. + ### pub.dev (Dart/Flutter) Set the PUB_HOSTED_URL environment variable: @@ -290,6 +349,8 @@ Add to your `~/.m2/settings.xml`: The `/maven/` endpoint uses Maven Central as primary upstream and falls back to the Gradle Plugin Portal for Gradle plugin marker metadata and related artifacts when the primary upstream returns not found. +Further Maven repositories can be configured under `upstream.maven_repositories` and are served at `/maven/{name}/`, each from its own upstream (see [Maven repositories](docs/configuration.md#maven-repositories)). Point a second `` or Gradle `maven(url = ...)` entry at `http://localhost:8080/maven/{name}/`. + For Gradle plugin resolution via the same proxy endpoint: ```kotlin @@ -302,20 +363,20 @@ pluginManagement { ### Gradle HTTP Build Cache -Configure in `settings.gradle(.kts)`: +Configure in `settings.gradle.kts`: ```kotlin buildCache { - local { - enabled = false - } remote { url = uri("http://localhost:8080/gradle/") - push = true } } ``` +Enable build caching with `org.gradle.caching=true` in `gradle.properties`, or pass `--build-cache` when running Gradle. The local cache stays enabled and remote uploads are disabled by default. + +To upload from CI, set `gradle.build_cache.read_only` to `false` on the proxy and add `isPush = System.getenv("CI") != null` inside the client's `remote` block. See [docs/configuration.md](docs/configuration.md#gradle-build-cache). + ### NuGet Configure in `nuget.config`: @@ -356,7 +417,16 @@ Or set globally: composer config -g repositories.proxy composer http://localhost:8080/composer ``` -To serve private packages through the same URL, see [Private package routes](docs/configuration.md#private-package-routes). +`composer audit`, `audit.block-insecure` and Packagist's malware filter list +work through the proxy when `upstream.composer_repository` offers them in its +`packages.json`, as repo.packagist.org does. The proxy advertises them in its +own `packages.json` and passes the advisories and filter list requests through +to the upstream uncached. Names of packages in `upstream.composer_routes` or +`hosted.composer_vendors` are removed from advisories requests before they are +sent. Versions withheld by [cooldown](#version-cooldown) are not excluded from +the report. + +To serve private packages through the same URL, see [Private package routes](docs/configuration.md#private-package-routes). To see new releases before `metadata_ttl` runs out, see [Change feeds](docs/configuration.md#change-feeds). ### Conan (C/C++) @@ -369,6 +439,24 @@ conan remote disable conancenter Or configure in `~/.conan2/remotes.json`. +### Chef Supermarket (Berkshelf, Policyfiles) + +Point Berkshelf at the proxy in your `Berksfile`: + +```ruby +source "http://localhost:8080/chef" +``` + +Or set the default source of a Policyfile: + +```ruby +default_source :supermarket, "http://localhost:8080/chef" +``` + +The proxy serves the `/universe` dependency index and the cookbook API, rewriting every download location to itself while leaving dependency constraints unchanged. Cookbook archives are fetched through the Supermarket download redirect and cached, so they stay available when the Supermarket is down. With `cache_metadata` on, the universe and cookbook metadata follow the usual TTL and stale fallback. + +To proxy a private Supermarket instead of `supermarket.chef.io`, set `upstream.chef` (or `PROXY_UPSTREAM_CHEF`) and add credentials under `upstream.auth` if it needs them. See [docs/configuration.md](docs/configuration.md#upstream-registries). + ### Conda Configure in `~/.condarc`: @@ -381,12 +469,17 @@ default_channels: - http://localhost:8080/conda/main ``` +`default_channels` also routes requests for `defaults` through the proxy, including `-c defaults` and `environment.yml` files that name it. + Or set via command: ```bash conda config --add channels http://localhost:8080/conda/main +conda config --add default_channels http://localhost:8080/conda/main ``` +pixi and other rattler-based clients use sharded repodata ([CEP 16](https://github.com/conda/ceps/blob/main/cep-0016.md)) where a channel offers it, as conda-forge does. Point them at the same channel URLs, for example `pixi init -c http://localhost:8080/conda/conda-forge`. The shard index and shards are cached as metadata when `cache_metadata` is on. + ### CRAN (R) Set the repository in R: @@ -405,6 +498,8 @@ local({ }) ``` +Source packages, Windows and macOS binaries (including the `bin/macosx/big-sur-arm64/` layout used by R 4.3 and later) are cached as artifacts. `PACKAGES` indexes and the `src/contrib/Meta/*.rds` files that `remotes::install_version` and pak read are cached as metadata. + ### Julia Set the Pkg server before starting Julia: @@ -632,16 +727,20 @@ indexes unchanged. To keep APT from selecting a denied version, configure ### RPM / Yum / DNF -Configure yum/dnf to use the proxy in `/etc/yum.repos.d/proxy.repo`: +In the `[fedora]` section of your existing repository file under `/etc/yum.repos.d/`, replace the `metalink` or `mirrorlist` entry with: ```ini -[proxy-fedora] -name=Fedora via Proxy baseurl=http://localhost:8080/rpm/releases/$releasever/Everything/$basearch/os/ -enabled=1 -gpgcheck=0 ``` +In the `[updates]` section of `fedora-updates.repo`, replace its `metalink` or `mirrorlist` entry with: + +```ini +baseurl=http://localhost:8080/rpm/updates/$releasever/Everything/$basearch/ +``` + +Keep the existing `gpgkey` and signature settings, including `gpgcheck=1`. The proxy serves RPM packages unchanged, so their signatures remain valid. + Then: ```bash @@ -671,6 +770,11 @@ signature verification keeps working. Indexes use the metadata cache (`metadata_ttl`, stale fallback); `.apk` packages are stored in the shared artifact cache and remain available when the upstream is unreachable. +Set `upstream.apk_snapshots` (e.g. `"90d"`) to keep replaced indexes and serve +them by date at `/apk/alpine@2026-10-01/v3.22/main`, so pinned package versions +stay installable after the mirror moves on. See +[Alpine APK snapshots](docs/configuration.md#alpine-apk-snapshots). + To proxy other mirrors or private repositories, configure named upstreams under `upstream.apk` (this replaces the built-in default; re-add `alpine` if you still want it): @@ -754,6 +858,62 @@ Avoid `mirror.archlinuxarm.org` as the upstream. It redirects each request to a changing regional mirror over plain HTTP, so the database and the packages can come from mirrors with a different sync state. +### FreeBSD / pkg + +Override the repositories in `/usr/local/etc/pkg/repos/FreeBSD.conf`. Settings +there are merged with `/etc/pkg/FreeBSD.conf`, so only the URL and mirror type +change and the signature settings stay. The default repository name `freebsd` +proxies the official mirror (`https://pkg.freebsd.org`). On FreeBSD 15: + +``` +FreeBSD-ports: { + url: "http://localhost:8080/freebsd/freebsd/${ABI}/quarterly", + mirror_type: "none" +} +FreeBSD-ports-kmods: { + url: "http://localhost:8080/freebsd/freebsd/${ABI}/kmods_quarterly_${VERSION_MINOR}", + mirror_type: "none" +} +FreeBSD-base: { + url: "http://localhost:8080/freebsd/freebsd/${ABI}/base_release_${VERSION_MINOR}", + mirror_type: "none" +} +``` + +FreeBSD 14 has a single repository called `FreeBSD`: + +``` +FreeBSD: { + url: "http://localhost:8080/freebsd/freebsd/${ABI}/quarterly", + mirror_type: "none" +} +``` + +Then: + +```bash +pkg update +``` + +Keep the path after `${ABI}` that `pkg -vv` shows for each repository +(`quarterly`, `latest`, `base_latest`, ...) and replace only the host part. + +The repository catalogues (`meta.conf`, `packagesite.pkg`, `data.pkg`) carry +their signature inside the archive and are served byte-for-byte unchanged +through the metadata cache (`metadata_ttl`, stale fallback). Enable +`cache_metadata` so `pkg update` keeps working while the upstream is down. +Packages under `Hashed/` have their content hash in the file name, so they are +stored in the shared artifact cache as `pkg:bsd/freebsd/{name}@{version}` and +remain available when the upstream is unreachable. + +Other files are passed through uncached. That includes the bootstrap package +under `Latest/`, whose signature file is rewritten with every repository build, +and package files without a hash in their name, which can be rebuilt under the +same name. The denylist still applies to unhashed package files. Since only +cached artifacts can be scanned, both kinds of package file are refused while +a scanner covers `freebsd`; use repositories built with `pkg repo --hash` and +bootstrap pkg without the proxy. + ### GitHub Releases / mise (aqua backend) Configure named generic upstreams: @@ -777,8 +937,26 @@ Release assets are cached permanently after the first download and keep installing while GitHub is down. Tag lookups through `api.github.com` are cached for `metadata_ttl` and served stale during an outage or rate limit. Commit a `mise.lock` and install with `mise install --locked` so pinned -installs need no API call at all. Add a bearer token for `https://api.github.com` -under `upstream.auth` if the fleet exceeds GitHub's anonymous rate limit. +installs need no API call at all. + +If the fleet exceeds GitHub's anonymous rate limit, add a bearer token for +`https://api.github.com` under `upstream.auth`. Everyone who can reach the +proxy can then make requests with that token, so the proxy requires +`generic_paths` listing the API paths it may serve, and the token should be a +fine-grained one with read-only access to public repositories: + +```yaml +upstream: + generic_paths: + github-api: + - "repos/*/*/releases" + - "repos/*/*/releases/**" + - "repos/*/*/tags" + auth: + "https://api.github.com": + type: bearer + token: "${GITHUB_TOKEN}" +``` Maven, mvnd, Node and Go downloads are cached the same way once their hosts are configured as generic upstreams; their version-pinned paths are built in @@ -804,6 +982,28 @@ go.download_mirror = "http://localhost:8080/generic/golang" Other download hosts need their version-pinned paths declared in `upstream.generic_artifacts`. +### Git repositories + +Configure named Git servers: + +```yaml +upstream: + git: + github: "https://github.com" +``` + +Then point clones at the proxy: + +```bash +git config --global url."http://localhost:8080/git/github/".insteadOf https://github.com/ +``` + +Each repository is cached as a bare clone and refreshed whenever its branches +or tags change upstream. Git LFS objects are cached in the artifact cache; +git-lfs uses the proxy for them with no further setup. See [configuration](docs/configuration.md#git-repositories) +for setting the rewrite through environment variables, size limits, private +repositories and outage behavior. + ## Configuration The proxy can be configured via: @@ -855,7 +1055,7 @@ storage: url: "file:///var/cache/proxy/artifacts" max_size: "10GB" # Optional: evict LRU when exceeded retention: - default: "30d" # Optional: evict artifacts not downloaded for 30 days + default: "30d" # Optional: evict unused artifacts after 30 days; excludes generic database: driver: "sqlite" @@ -889,7 +1089,7 @@ Run with config file: ### PostgreSQL -SQLite is the default and works well for single-node deployments. For multi-node setups or if you prefer a managed database, switch to Postgres: +SQLite is the default and works well for single-node deployments, with the database file on a local disk or block-backed volume. For multi-node setups, when only network filesystem storage such as NFS is available, or if you prefer a managed database, switch to Postgres: ```yaml database: @@ -997,6 +1197,9 @@ proxy mirror pkg:npm/lodash@4.17.21 pkg:cargo/serde@1.0.0 # Mirror all versions of a package proxy mirror pkg:npm/lodash +# Mirror only the newest version of a package +proxy mirror --latest pkg:npm/lodash + # Mirror from a CycloneDX or SPDX SBOM proxy mirror --sbom sbom.cdx.json @@ -1008,9 +1211,14 @@ proxy mirror --concurrency 8 pkg:npm/lodash@4.17.21 # Mirror a container image for one platform proxy mirror --platform linux/amd64 pkg:docker/library/alpine@3.20 + +# Mirror a commit of an upstream.git repository into the git cache +proxy mirror pkg:git/github.com/git-pkgs/purl@0123456789abcdef0123456789abcdef01234567 ``` -The mirror command accepts the same storage and database flags as `serve`. Already-cached artifacts are skipped. +The mirror command accepts the same storage and database flags as `serve`. Already-cached artifacts are skipped. If any package version fails to mirror, the command lists the errors and exits with status 1, so a CI step that warms the cache fails on a partial mirror. + +With `scanning.enabled`, the mirror command refuses every package and container image so nothing is cached unscanned. Each one is reported as failed, so the command exits with status 1. Scanners fetch the staged bytes from the running server, which this command does not start. Use the mirror API below instead, since its jobs run inside the server and go through the pre-cache scan. `--dry-run` still lists what would be mirrored. A mirror API is also available when the server is running: @@ -1104,6 +1312,9 @@ Recently cached: | `GET /npm/*` | npm registry protocol | | `POST /npm/-/npm/v1/security/*` | npm/pnpm/Yarn audit endpoints, passed through to upstream | | `GET /npm/-/npm/v1/keys` | npm registry signing keys, passed through to upstream | +| `GET /npm/-/package/{name}/dist-tags` | `npm dist-tag ls`, answered from the packument the proxy serves (cooldown and pushed versions applied); changing tags is not supported | +| `GET /npm/-/npm/v1/attestations/{name}@{version}` | npm provenance attestations of a version, fetched from the package's registry and cached | +| `GET /npm/-/v1/search`, `GET /npm/-/ping` | `npm search` and `npm ping`, passed through to upstream uncached | | `GET /cargo/*` | Cargo sparse index protocol | | `GET /gem/*` | RubyGems protocol | | `GET /go/*` | Go module proxy protocol | @@ -1113,7 +1324,10 @@ Recently cached: | `GET /maven/*` | Maven repository protocol | | `GET /nuget/*` | NuGet V3 API | | `GET /composer/*` | Composer/Packagist protocol | +| `GET`, `POST /composer/api/security-advisories/` | Composer security advisories, passed through to upstream without private package names | +| `GET /composer/lists/summary.json` | Composer filter list summary, passed through to upstream uncached | | `GET /conan/*` | Conan C/C++ protocol | +| `GET /chef/*` | Chef Supermarket protocol (universe, cookbook API and downloads) | | `GET /conda/*` | Conda/Anaconda protocol | | `GET /cran/*` | CRAN (R) protocol | | `GET /julia/*` | Julia Pkg server protocol | @@ -1124,7 +1338,9 @@ Recently cached: | `GET /v2/homebrew/core/*` | Homebrew core bottle manifests and blobs from GHCR | | `GET /apk/{repository}/*` | Alpine APK repository protocol | | `GET /arch/{repository}/*` | Arch Linux pacman repository protocol | +| `GET /freebsd/{repository}/*` | FreeBSD pkg repository protocol | | `GET /generic/{name}/*` | Generic HTTP download proxy (GitHub release assets, mise/aqua) | +| `GET /git/{name}/{repo}/info/refs`, `POST /git/{name}/{repo}/git-upload-pack` | Git smart HTTP protocol, read-only | | `GET /debian/*` | Debian/APT repository protocol (main archive) | | `GET /debian/{repository}/*` | Debian/APT repository protocol (named archive, e.g. security) | | `GET /rpm/*` | RPM/Yum repository protocol | @@ -1147,6 +1363,25 @@ Registered when `hosted.enabled` is set. Pushing and deleting require `Authoriza | `GET /api/hosted/{ecosystem}/{name}` | List the archives pushed for a package | | `DELETE /api/hosted/{ecosystem}/{name}/{version}` | Delete a pushed version | +### Projects API + +Registered when `projects.enabled` is set. Uploading and deleting require `Authorization: Bearer `. See [Project inventory](docs/configuration.md#project-inventory). + +| Endpoint | Description | +|----------|-------------| +| `PUT /api/projects/{project}/sbom` | Replace a project's recorded package versions with the ones the SBOM in the body lists | +| `GET /api/projects` | List projects, or with `?purl=pkg:npm/lodash@4.17.20` the projects using a package or version | +| `GET /api/projects/{project}` | A project's recorded package versions | +| `DELETE /api/projects/{project}` | Delete a project | + +### Cache API + +Registered when `cache_delete` is set. It has no authentication of its own. + +| Endpoint | Description | +|----------|-------------| +| `DELETE /api/cache/{ecosystem}/{name}/{version}` | Delete a version's cached files, or only `?filename=` | + ### Enrichment API The proxy provides REST endpoints for package metadata enrichment, vulnerability scanning, and outdated detection. @@ -1300,9 +1535,7 @@ Response: { "cached_artifacts": 142, "total_size_bytes": 523456789, - "total_size": "499.2 MB", - "storage_url": "file:///path/to/cache/artifacts", - "database_path": "./cache/proxy.db" + "total_size": "499.2 MB" } ``` @@ -1342,6 +1575,7 @@ The proxy serves a web UI under `/ui`. No separate frontend build is needed -- t - **Version detail** (`/ui/package/{ecosystem}/{name}/{version}`) -- per-version metadata, integrity hash, artifact cache status, and hit counts. - **Source browser** (`/ui/package/{ecosystem}/{name}/{version}/browse`) -- browse files inside cached archives with syntax highlighting for text files and image previews. - **Version diff** (`/ui/package/{ecosystem}/{name}/compare/{v1}...{v2}`) -- side-by-side diff of two cached versions showing added, removed, and changed files. +- **Projects** (`/ui/projects`) -- with the [project inventory](docs/configuration.md#project-inventory) enabled, the package versions each repository's uploaded SBOM lists, marked when outdated. Package pages then show which projects use each version. ## Monitoring @@ -1351,11 +1585,17 @@ The proxy exposes Prometheus metrics at `GET /metrics`. All metric names are pre |--------|------|--------|-------------| | `proxy_requests_total` | counter | `ecosystem`, `status` | Proxy responses by package ecosystem and HTTP status | | `proxy_request_duration_seconds` | histogram | `ecosystem`, `status` | Proxy request duration | -| `proxy_cache_hits_total` | counter | `ecosystem` | Cache hits | -| `proxy_cache_misses_total` | counter | `ecosystem` | Cache misses | +| `proxy_cache_hits_total` | counter | `ecosystem`, `kind` | Cache hits. `kind` is `artifact` or `metadata`. | +| `proxy_cache_misses_total` | counter | `ecosystem`, `kind` | Cache misses. `kind` is `artifact` or `metadata`; metadata misses are counted only while `cache_metadata` is on. | | `proxy_cache_size_bytes` | gauge | | Total size of cached artifacts | | `proxy_cached_artifacts_total` | gauge | | Number of cached artifacts | +| `proxy_metadata_cache_served_bytes_total` | counter | `ecosystem` | Metadata bytes served from the metadata cache. | +| `proxy_metadata_cache_size_bytes` | gauge | `ecosystem` | Size of cached metadata documents per ecosystem. | +| `proxy_metadata_cache_entries` | gauge | `ecosystem` | Number of cached metadata documents per ecosystem. | | `proxy_artifacts_evicted_total` | counter | `reason`, `ecosystem` | Artifacts evicted by the size limit (`lru`) or by age (`retention`) | +| `proxy_metadata_evicted_total` | counter | `ecosystem` | Cached metadata documents evicted by the size limit | +| `proxy_metadata_expired_by_change_feed_total` | counter | `ecosystem` | Cached metadata documents set to revalidate because an upstream [change feed](docs/configuration.md#change-feeds) listed them | +| `proxy_fetch_lease_waits_total` | counter | `kind` | Cache misses (`artifact` or `metadata`) that waited for another instance sharing the database to fetch them | | `proxy_upstream_fetch_duration_seconds` | histogram | `ecosystem` | Time spent fetching from upstream | | `proxy_upstream_errors_total` | counter | `ecosystem`, `error_type` | Upstream fetch failures | | `proxy_storage_operation_duration_seconds` | histogram | `operation` | Storage read/write latency | @@ -1415,11 +1655,17 @@ For history, trends and alerting, scrape `/metrics` with Prometheus. That is the The same figures are available as JSON from `GET /stats`, which reports `downloaded_bytes`, `downloads` and an `ecosystems` array carrying the per-ecosystem breakdown, served from the same 60-second snapshot the page and the gauges read. When the aggregation fails with no snapshot to fall back on, the response carries `stats_unavailable: true` rather than passing zeros off as a count -- the endpoint keeps answering with the artifact count and cache size either way. +#### Artifact and metadata caches + +The proxy keeps two caches. Artifacts (tarballs, wheels, crates and so on) live in storage and are what `proxy_cache_size_bytes`, `proxy_ecosystem_downloaded_bytes` and the other artifact figures describe. Registry metadata is cached separately when `cache_metadata` is on. It is stored persistently in the `metadata_cache` table rather than held in memory. + +The `kind` label on `proxy_cache_hits_total` and `proxy_cache_misses_total` keeps the two apart, so an artifact hit rate is `sum(rate(proxy_cache_hits_total{kind="artifact"}[5m]))` over the same expression with misses added. Metadata has its own size and entry gauges plus `proxy_metadata_cache_served_bytes_total`. That one is a process counter rather than a database total, because metadata hits are not recorded per row. On `/ui/analytics` metadata appears in its own card and in the Runtime card's metadata lookups, never mixed into the artifact figures. The card and the two gauges read one 60-second snapshot, like the artifact figures. The bundled Grafana dashboard's hit ratio covers artifacts only, while its hits and misses panel shows each kind as its own series. + #### Three ecosystem label sets `ecosystem` means three slightly different things across `/metrics`, and queries that join across them need to know which. -**From the package record, normalized.** The six `proxy_ecosystem_*` gauges, `proxy_cache_hits_total`, `proxy_cache_misses_total`, `proxy_artifacts_evicted_total`, `proxy_integrity_failures_total` and the scan metrics. Aliases collapse here: `gem` reads as `rubygems`, `composer` as `packagist`, `go` as `golang`. +**From the package record, normalized.** The six `proxy_ecosystem_*` gauges, `proxy_cache_hits_total`, `proxy_cache_misses_total`, the three `proxy_metadata_cache_*` metrics, `proxy_artifacts_evicted_total`, `proxy_metadata_evicted_total`, `proxy_metadata_expired_by_change_feed_total`, `proxy_integrity_failures_total` and the scan metrics. Aliases collapse here: `gem` reads as `rubygems`, `composer` as `packagist`, `go` as `golang`. **From the request path.** `proxy_requests_total`, `proxy_request_duration_seconds` and `proxy_response_bytes_total`. The names mostly coincide with the normalized ones -- these also report `rubygems`, `packagist` and `golang` -- but the Debian route reports `debian` where the package record says `deb`, and any path that is not a package endpoint reports `other`, which corresponds to no ecosystem at all. @@ -1480,7 +1726,7 @@ Failing checks include an `"error"` field. Storage failures also include a `"ste `circuit_breakers` reports the state of each upstream's artifact-fetch circuit breaker (`"open"` or `"closed"`), keyed by upstream host — or by the `hostless-url-` placeholder described under [Monitoring](#monitoring) where the fetch URL has no host to read. The key is omitted until the proxy has fetched an artifact from at least one upstream, and a host appears only once a breaker has been created for it. Breakers trip after repeated upstream failures and retry the upstream after an exponential backoff. While one is open, artifact downloads for that host return HTTP 502 on a cache miss without contacting the upstream; already-cached artifacts are still served from storage, since the cache is checked before the fetcher. A breaker is reported as `"open"` throughout its backoff, including the half-open window in which it admits one probe request to test recovery. Breaker state is per process and in memory, so a restart clears it, but a restart is not needed for recovery: the backoff keeps retrying for as long as the breaker is open, so it closes on its own once the upstream serves again. -`upstream_holds` lists upstream hosts that answered the proxy with HTTP 429, or 503 with a `Retry-After`, and the time until which the proxy sends them nothing. Every request to a held host, metadata and artifacts alike, fails locally for the duration the upstream asked for (capped at one hour), or for one minute doubling up to fifteen when the upstream gave no `Retry-After`. Cached metadata is served stale during a hold, and anything uncached returns HTTP 503 with the remaining `Retry-After` so a client can pace itself too. Metadata requests do not go through the circuit breaker, so without the hold a rate-limited upstream would keep receiving one request per cache miss, which is exactly the traffic it is asking the proxy to stop sending. The first non-limited response after a hold ends clears it, and `proxy_upstream_rate_limit_holds_total` counts the holds placed. The key is omitted while no host is held. +`upstream_holds` lists upstream hosts that answered the proxy with HTTP 429, or 503 with a `Retry-After`, and the time until which the proxy sends them nothing. Every request to a held host, metadata and artifacts alike, fails locally for the duration the upstream asked for (capped at one hour), or for one minute doubling up to fifteen when the upstream gave no `Retry-After`. Cached metadata is served stale during a hold, and anything uncached returns HTTP 503 with the remaining `Retry-After` so a client can pace itself too. Metadata requests do not go through the circuit breaker, so without the hold a rate-limited upstream would keep receiving one request per cache miss, which is exactly the traffic it is asking the proxy to stop sending. The first non-limited response after a hold ends clears it, and `proxy_upstream_rate_limit_holds_total` counts the holds placed. Holds are recorded in the database, so instances sharing one honour each other's holds and list them here too. The key is omitted while no host is held. An open breaker does **not** set `status` to `"error"` or change the HTTP status code: it reports a specific upstream refusing to serve, not this proxy being unfit to receive traffic, and failing the readiness probe over one unhealthy upstream would pull the pod out of rotation for every other ecosystem too. Use `proxy_circuit_breaker_state` for alerting on it. @@ -1526,13 +1772,23 @@ sudo systemctl start proxy ### Docker -A Dockerfile is included in the repo. Build and run: +Images for linux/amd64 and linux/arm64 are published to `ghcr.io/git-pkgs/proxy` for each release, tagged with the version and `latest`: + +```bash +docker run -p 8080:8080 -v proxy-data:/data ghcr.io/git-pkgs/proxy:latest +``` + +To build the image from the repo instead: ```bash docker build -t proxy . docker run -p 8080:8080 -v proxy-data:/data proxy ``` +The image has a health check that requests `/health` on port 8080. It checks the database and storage, so a container reports unhealthy when either fails. If you change the port with `PROXY_LISTEN`, override it with `--health-cmd`. + +With `--read-only`, also pass `--tmpfs /tmp`: the proxy writes some uploads to a temporary file before reading them. + With Postgres and S3: ```bash @@ -1622,6 +1878,12 @@ cache/artifacts/ └── nginx-1.24.0-1.fc39.x86_64.rpm ``` +To delete one version's cached files, so the next request fetches them again, enable `cache_delete` and use the Delete buttons on the version page in the web UI, or the [cache API](docs/configuration.md#cache-delete-api): + +```bash +curl -X DELETE 'http://localhost:8080/api/cache/maven/com.google.guava:guava/32.1.3-jre?filename=guava-32.1.3-jre.jar' +``` + Cache metadata is stored in SQLite (default) or PostgreSQL. To clear a local cache: ```bash diff --git a/cmd/proxy/hosted.go b/cmd/proxy/hosted.go index bbc947d..36a798d 100644 --- a/cmd/proxy/hosted.go +++ b/cmd/proxy/hosted.go @@ -1,6 +1,8 @@ package main import ( + "crypto/sha256" + "encoding/hex" "encoding/json" "errors" "flag" @@ -9,9 +11,12 @@ import ( "net/http" "net/url" "os" + "path/filepath" "strings" "text/tabwriter" "time" + + "github.com/git-pkgs/proxy/internal/handler" ) const ( @@ -19,10 +24,11 @@ const ( hostedTokenEnv = "PROXY_HOSTED_TOKEN" hostedClientTimeout = 10 * time.Minute - pushArgCount = 4 // ecosystem, name, version, file - listArgCount = 2 // ecosystem, name - deleteArgCount = 3 // ecosystem, name, version - tablePadding = 2 + pushArgCount = 4 // ecosystem, name, version, file + listArgCount = 2 // ecosystem, name + deleteArgCount = 3 // ecosystem, name, version + deleteMaxArgCount = 4 // ecosystem, name, version, file for generic files + tablePadding = 2 ) // hostedArtifact mirrors the JSON the /api/hosted endpoints return. @@ -69,15 +75,16 @@ func newHostedCommand(name, usage, summary string, getenv func(string) string) h return cmd } -// parse parses flags and checks for exactly want positional arguments. -func (c hostedCommand) parse(args []string, want int) ([]string, error) { +// parse parses flags and checks for between minArgs and maxArgs positional +// arguments. +func (c hostedCommand) parse(args []string, minArgs, maxArgs int) ([]string, error) { if err := c.flags.Parse(args); err != nil { if errors.Is(err, flag.ErrHelp) { c.flags.Usage() } return nil, fmt.Errorf("%w\nusage: %s", err, c.usage) } - if c.flags.NArg() != want { + if n := c.flags.NArg(); n < minArgs || n > maxArgs { return nil, fmt.Errorf("usage: %s", c.usage) } return c.flags.Args(), nil @@ -105,7 +112,7 @@ func hostedToken(getenv func(string) string) (string, error) { func runPush(args []string, getenv func(string) string, stdout io.Writer, client *http.Client) error { cmd := newHostedCommand("push", "proxy hosted push [-url URL] ", "Push a package archive to the proxy", getenv) - positional, err := cmd.parse(args, pushArgCount) + positional, err := cmd.parse(args, pushArgCount, pushArgCount) if err != nil { return err } @@ -121,12 +128,32 @@ func runPush(args []string, getenv func(string) string, stdout io.Writer, client } defer func() { _ = file.Close() }() - req, err := http.NewRequest(http.MethodPut, cmd.endpoint(ecosystem, name, version), file) + // The proxy checks the upload against this, so a truncated or corrupted + // transfer is refused rather than stored. + digest := sha256.New() + size, err := io.Copy(digest, file) if err != nil { return err } + if _, err := file.Seek(0, io.SeekStart); err != nil { + return err + } + + segments := []string{version} + if handler.HostedFileInPath(ecosystem) { + segments = append(segments, filepath.Base(path)) + } + endpoint := cmd.endpoint(ecosystem, name, segments...) + "?sha256=" + hex.EncodeToString(digest.Sum(nil)) + req, err := http.NewRequest(http.MethodPut, endpoint, file) + if err != nil { + return err + } + req.ContentLength = size req.Header.Set("Authorization", "Bearer "+token) req.Header.Set("Content-Type", "application/octet-stream") + // The proxy refuses an existing file or a bad token before reading the + // body, so the file is only uploaded once it would be accepted. + req.Header.Set("Expect", "100-continue") var pushed hostedPushResponse if err := doHosted(client, req, http.StatusCreated, &pushed); err != nil { @@ -139,7 +166,7 @@ func runPush(args []string, getenv func(string) string, stdout io.Writer, client func runList(args []string, getenv func(string) string, stdout io.Writer, client *http.Client) error { cmd := newHostedCommand("list", "proxy hosted list [-url URL] ", "List pushed package archives", getenv) - positional, err := cmd.parse(args, listArgCount) + positional, err := cmd.parse(args, listArgCount, listArgCount) if err != nil { return err } @@ -161,16 +188,20 @@ func runList(args []string, getenv func(string) string, stdout io.Writer, client } func runDelete(args []string, getenv func(string) string, stdout io.Writer, client *http.Client) error { - cmd := newHostedCommand("delete", "proxy hosted delete [-url URL] ", "Delete a pushed version", getenv) - positional, err := cmd.parse(args, deleteArgCount) + cmd := newHostedCommand("delete", "proxy hosted delete [-url URL] [file]", + "Delete a pushed version, or one generic file of it", getenv) + positional, err := cmd.parse(args, deleteArgCount, deleteMaxArgCount) if err != nil { return err } + if len(positional) > deleteArgCount && !handler.HostedFileInPath(positional[0]) { + return fmt.Errorf("only generic files can be deleted one at a time\nusage: %s", cmd.usage) + } token, err := hostedToken(getenv) if err != nil { return err } - req, err := http.NewRequest(http.MethodDelete, cmd.endpoint(positional[0], positional[1], positional[2]), nil) + req, err := http.NewRequest(http.MethodDelete, cmd.endpoint(positional[0], positional[1], positional[2:]...), nil) if err != nil { return err } @@ -179,7 +210,11 @@ func runDelete(args []string, getenv func(string) string, stdout io.Writer, clie if err := doHosted(client, req, http.StatusNoContent, nil); err != nil { return err } - _, err = fmt.Fprintf(stdout, "deleted %s %s@%s\n", positional[0], positional[1], positional[2]) + deleted := positional[1] + "@" + positional[2] + if len(positional) > deleteArgCount { + deleted += " " + positional[deleteArgCount] + } + _, err = fmt.Fprintf(stdout, "deleted %s %s\n", positional[0], deleted) return err } @@ -210,7 +245,7 @@ func doHosted(client *http.Client, req *http.Request, wantStatus int, out any) e const hostedUsage = "usage: proxy hosted [flags] ...\n\n" + " push Push a package archive to the proxy\n" + " list List pushed package archives\n" + - " delete Delete a pushed version" + " delete Delete a pushed version, or one generic file of it" type hostedSubcommand func([]string, func(string) string, io.Writer, *http.Client) error diff --git a/cmd/proxy/hosted_test.go b/cmd/proxy/hosted_test.go index fef7160..33fe226 100644 --- a/cmd/proxy/hosted_test.go +++ b/cmd/proxy/hosted_test.go @@ -12,7 +12,8 @@ import ( ) type recordedRequest struct { - method, path, query, authorization, body string + method, path, query, authorization, body, expect string + contentLength int64 } func hostedTestServer(t *testing.T, status int, response string) (*httptest.Server, *recordedRequest) { @@ -26,6 +27,8 @@ func hostedTestServer(t *testing.T, status int, response string) (*httptest.Serv query: r.URL.RawQuery, authorization: r.Header.Get("Authorization"), body: string(body), + expect: r.Header.Get("Expect"), + contentLength: r.ContentLength, } w.Header().Set("Content-Type", "application/json") w.WriteHeader(status) @@ -62,14 +65,34 @@ func TestRunPush(t *testing.T) { if recorded.method != http.MethodPut || recorded.path != "/api/hosted/npm/@types/node/20.1.0" { t.Errorf("request = %s %s", recorded.method, recorded.path) } - if recorded.authorization != "Bearer tok" || recorded.body != "tarball" || recorded.query != "" { + // sha256 of "tarball", so the proxy can check the upload. + const tarballSHA256 = "db4b4d0d1cb480bf9aeea253771c00febe627f236765fa37d6a5614f079a3aa0" + if recorded.authorization != "Bearer tok" || recorded.body != "tarball" || recorded.query != "sha256="+tarballSHA256 { t.Errorf("authorization/body/query = %q/%q/%q", recorded.authorization, recorded.body, recorded.query) } + if recorded.expect != "100-continue" || recorded.contentLength != int64(len("tarball")) { + t.Errorf("expect/content length = %q/%d, want 100-continue and the file size", recorded.expect, recorded.contentLength) + } if out := stdout.String(); !strings.Contains(out, "node-20.1.0.tgz") || !strings.Contains(out, "abc123") { t.Errorf("output = %q, want filename and sha256", out) } } +func TestRunPushGenericNamesTheFile(t *testing.T) { + srv, recorded := hostedTestServer(t, http.StatusCreated, + `{"ecosystem":"generic","name":"tools","version":"1.2.0","filename":"tool-linux-arm64.tar.gz","sha256":"abc123","size":7}`) + archive := writeArchive(t, "tool-linux-arm64.tar.gz", "tarball") + + err := runPush([]string{"-url", srv.URL, "generic", "tools", "1.2.0", archive}, + hostedEnv(map[string]string{"PROXY_HOSTED_TOKEN": "tok"}), io.Discard, srv.Client()) + if err != nil { + t.Fatalf("runPush: %v", err) + } + if recorded.path != "/api/hosted/generic/tools/1.2.0/tool-linux-arm64.tar.gz" { + t.Errorf("path = %q, want the file name appended", recorded.path) + } +} + func TestRunPushErrors(t *testing.T) { srv, _ := hostedTestServer(t, http.StatusBadRequest, `{"code":"BAD_REQUEST","message":"pushing packages is not supported for this ecosystem: cargo"}`) archive := writeArchive(t, "serde-1.0.200.crate", "crate") @@ -141,6 +164,36 @@ func TestRunDelete(t *testing.T) { } } +func TestRunDeleteOneFile(t *testing.T) { + srv, recorded := hostedTestServer(t, http.StatusNoContent, "") + var stdout bytes.Buffer + + err := runDelete([]string{"-url", srv.URL, "generic", "tools", "1.2.0", "tool-linux-arm64.tar.gz"}, + hostedEnv(map[string]string{"PROXY_HOSTED_TOKEN": "tok"}), &stdout, srv.Client()) + if err != nil { + t.Fatalf("runDelete: %v", err) + } + if recorded.path != "/api/hosted/generic/tools/1.2.0/tool-linux-arm64.tar.gz" { + t.Errorf("path = %q", recorded.path) + } + if out := stdout.String(); out != "deleted generic tools@1.2.0 tool-linux-arm64.tar.gz\n" { + t.Errorf("output = %q", out) + } +} + +func TestRunDeleteOneFileOnlyForGeneric(t *testing.T) { + srv, recorded := hostedTestServer(t, http.StatusNoContent, "") + + err := runDelete([]string{"-url", srv.URL, "npm", "@acme", "widget", "1.0.0"}, + hostedEnv(map[string]string{"PROXY_HOSTED_TOKEN": "tok"}), io.Discard, srv.Client()) + if err == nil || !strings.Contains(err.Error(), "only generic files") { + t.Errorf("npm delete with a fourth argument error = %v, want a refusal", err) + } + if recorded.method != "" { + t.Errorf("refused delete sent %s %s", recorded.method, recorded.path) + } +} + func TestRunHostedDispatchesSubcommands(t *testing.T) { srv, recorded := hostedTestServer(t, http.StatusOK, `{"ecosystem":"npm","name":"request","artifacts":[]}`) diff --git a/cmd/proxy/main.go b/cmd/proxy/main.go index 75f0097..7c51732 100644 --- a/cmd/proxy/main.go +++ b/cmd/proxy/main.go @@ -8,7 +8,7 @@ // @securityDefinitions.apikey BearerAuth // @in header // @name Authorization -// @description "Bearer " followed by hosted.token +// @description "Bearer " followed by hosted.token, or projects.token for /api/projects // // The proxy caches package artifacts from upstream registries (npm, cargo, etc.) // providing faster, more reliable access for development teams. @@ -82,7 +82,7 @@ // PROXY_LOG_FORMAT - Log format // PROXY_ACCESS_LOG_PATH - JSONL access log path // PROXY_UPSTREAM_* - Upstream URLs and network access controls -// PROXY_GRADLE_BUILD_CACHE_READ_ONLY - Disable Gradle PUT uploads +// PROXY_GRADLE_BUILD_CACHE_READ_ONLY - Set false to allow Gradle PUT uploads (default true) // PROXY_GRADLE_BUILD_CACHE_MAX_UPLOAD_SIZE - Max Gradle PUT request body size // PROXY_GRADLE_BUILD_CACHE_MAX_AGE - Gradle cache max age eviction // PROXY_GRADLE_BUILD_CACHE_MAX_SIZE - Gradle cache max total size @@ -93,6 +93,9 @@ // PROXY_HOSTED_MAX_UPLOAD_SIZE - Max size of one pushed archive (default "100MB") // PROXY_HOSTED_NPM_SCOPES - npm scopes served from pushed packages only // PROXY_HOSTED_COMPOSER_VENDORS - Composer vendors served from pushed packages only +// PROXY_PROJECTS_ENABLED - Enable the project inventory (/api/projects, /ui/projects) +// PROXY_PROJECTS_TOKEN - Bearer token for uploading and deleting project SBOMs +// PROXY_PROJECTS_MAX_AGE - Remove projects not uploaded for this long (e.g. "90d") // PROXY_URL - Proxy URL for proxy hosted // // Example: @@ -124,7 +127,8 @@ import ( "github.com/git-pkgs/proxy/internal/config" "github.com/git-pkgs/proxy/internal/database" - "github.com/git-pkgs/proxy/internal/denylist" + "github.com/git-pkgs/proxy/internal/handler" + "github.com/git-pkgs/proxy/internal/memlimit" "github.com/git-pkgs/proxy/internal/mirror" "github.com/git-pkgs/proxy/internal/server" "github.com/git-pkgs/proxy/internal/storage" @@ -238,6 +242,7 @@ func runServe() { fmt.Fprintf(os.Stderr, " PROXY_UPSTREAM_CARGO_DOWNLOAD Cargo download upstream URL\n") fmt.Fprintf(os.Stderr, " PROXY_UPSTREAM_GEM RubyGems upstream URL\n") fmt.Fprintf(os.Stderr, " PROXY_UPSTREAM_GO Go module proxy upstream URL\n") + fmt.Fprintf(os.Stderr, " PROXY_UPSTREAM_GO_VULNDB Go vulnerability database URL\n") fmt.Fprintf(os.Stderr, " PROXY_UPSTREAM_HEX Hex repository upstream URL\n") fmt.Fprintf(os.Stderr, " PROXY_UPSTREAM_HEX_API Hex API upstream URL\n") fmt.Fprintf(os.Stderr, " PROXY_UPSTREAM_PUB pub registry upstream URL\n") @@ -250,6 +255,7 @@ func runServe() { fmt.Fprintf(os.Stderr, " PROXY_UPSTREAM_COMPOSER Packagist API upstream URL\n") fmt.Fprintf(os.Stderr, " PROXY_UPSTREAM_COMPOSER_REPOSITORY Packagist repository upstream URL\n") fmt.Fprintf(os.Stderr, " PROXY_UPSTREAM_CONAN Conan registry upstream URL\n") + fmt.Fprintf(os.Stderr, " PROXY_UPSTREAM_CHEF Chef Supermarket upstream URL\n") fmt.Fprintf(os.Stderr, " PROXY_UPSTREAM_CONDA Conda channel upstream URL\n") fmt.Fprintf(os.Stderr, " PROXY_UPSTREAM_CRAN CRAN mirror upstream URL\n") fmt.Fprintf(os.Stderr, " PROXY_UPSTREAM_JULIA Julia package server upstream URL\n") @@ -257,7 +263,7 @@ func runServe() { fmt.Fprintf(os.Stderr, " PROXY_UPSTREAM_OCI_DEFAULT Default OCI registry upstream URL\n") fmt.Fprintf(os.Stderr, " PROXY_UPSTREAM_DEBIAN Debian repository upstream URL\n") fmt.Fprintf(os.Stderr, " PROXY_UPSTREAM_RPM RPM repository upstream URL\n") - fmt.Fprintf(os.Stderr, " PROXY_GRADLE_BUILD_CACHE_READ_ONLY Disable Gradle PUT uploads\n") + fmt.Fprintf(os.Stderr, " PROXY_GRADLE_BUILD_CACHE_READ_ONLY Set false to allow Gradle PUT uploads (default true)\n") fmt.Fprintf(os.Stderr, " PROXY_GRADLE_BUILD_CACHE_MAX_UPLOAD_SIZE Max Gradle PUT request body size\n") fmt.Fprintf(os.Stderr, " PROXY_GRADLE_BUILD_CACHE_MAX_AGE Gradle cache max age eviction\n") fmt.Fprintf(os.Stderr, " PROXY_GRADLE_BUILD_CACHE_MAX_SIZE Gradle cache max total size\n") @@ -322,6 +328,7 @@ func runServe() { // Setup logger logger := setupLogger(cfg.Log.Level, cfg.Log.Format) + memlimit.Apply(logger) // Create and start server srv, err := server.New(cfg, logger, server.BuildInfo{ @@ -437,6 +444,7 @@ func runMirror() { concurrency := fs.Int("concurrency", 4, "Number of parallel downloads") //nolint:mnd // default concurrency dryRun := fs.Bool("dry-run", false, "Show what would be mirrored without downloading") platforms := fs.String("platform", "", "Comma-separated os/arch[/variant] list limiting which platforms of container images are mirrored") + latest := fs.Bool("latest", false, "Mirror only the newest version of PURLs without a version") fs.Usage = func() { fmt.Fprintf(os.Stderr, "git-pkgs proxy - Pre-populate cache\n\n") @@ -445,6 +453,7 @@ func runMirror() { fmt.Fprintf(os.Stderr, " proxy mirror pkg:npm/lodash@4.17.21\n") fmt.Fprintf(os.Stderr, " proxy mirror --sbom sbom.cdx.json\n") fmt.Fprintf(os.Stderr, " proxy mirror pkg:npm/lodash # all versions\n") + fmt.Fprintf(os.Stderr, " proxy mirror --latest pkg:npm/lodash # newest version\n") fmt.Fprintf(os.Stderr, " proxy mirror --platform linux/amd64 pkg:docker/library/alpine@3.20\n\n") fmt.Fprintf(os.Stderr, "Flags:\n") fs.PrintDefaults() @@ -470,9 +479,9 @@ func runMirror() { fmt.Fprintf(os.Stderr, "error reading SBOM %s: %v\n", *sbomPath, err) os.Exit(1) } - source = &mirror.SBOMSource{Data: data, Name: *sbomPath, Platforms: platformList} + source = &mirror.SBOMSource{Data: data, Name: *sbomPath, Latest: *latest, Platforms: platformList} case len(purls) > 0: - source = &mirror.PURLSource{PURLs: purls, Platforms: platformList} + source = &mirror.PURLSource{PURLs: purls, Latest: *latest, Platforms: platformList} default: fmt.Fprintf(os.Stderr, "error: provide PURLs or --sbom\n") fs.Usage() @@ -486,6 +495,7 @@ func runMirror() { os.Exit(1) } cfg.LoadFromEnv() + printEnvWarnings(cfg) if *storageURL != "" { cfg.Storage.URL = *storageURL @@ -545,22 +555,24 @@ func runMirror() { // Build proxy with the same upstream clients and authentication as serve proxy, images := server.NewMirrorProxy(cfg, db, store, logger) - proxy.Denylist, err = denylist.New(cfg.Denylist.Packages) - if err != nil { - _ = db.Close() - fmt.Fprintf(os.Stderr, "invalid denylist: %v\n", err) - os.Exit(1) //nolint:gocritic // db closed above - } proxy.CacheMetadata = true // mirror always caches metadata proxy.MetadataTTL = cfg.ParseMetadataTTL() proxy.MetadataMaxSize = cfg.ParseMetadataMaxSize() + proxy.MetadataStreamMaxSize = cfg.ParseMetadataStreamMaxSize() + // As serve does, resolve Swift source repositories in the denylist through + // the upstream, and refuse to run when one can't be. + if err := server.ConfigureDenylist(cfg, proxy); err != nil { + _ = db.Close() + fmt.Fprintf(os.Stderr, "error: %v\n", err) + os.Exit(1) //nolint:gocritic // db closed above + } - m := mirror.New(proxy, db, store, logger, *concurrency) - m.Images = images - if cfg.Scanning.Enabled { - // Scanners fetch staged layers from the running server, which this - // command does not start. - m.Images = mirror.UnavailableImages{Reason: "container images cannot be mirrored by this command while scanning is enabled; use the mirror API of the running server"} + m := newCommandMirror(cfg, proxy, images, db, store, logger, *concurrency) + switch s := source.(type) { + case *mirror.PURLSource: + s.Versions = m.Versions + case *mirror.SBOMSource: + s.Versions = m.Versions } ctx, cancel := context.WithCancel(context.Background()) @@ -584,7 +596,9 @@ func runMirror() { return } + closeGit := useCommandGit(cfg, proxy, m, logger) progress, err := m.Run(ctx, source) + closeGit() if err != nil { fmt.Fprintf(os.Stderr, "error: %v\n", err) os.Exit(1) @@ -599,6 +613,75 @@ func runMirror() { fmt.Fprintf(os.Stderr, " %s/%s@%s: %s\n", e.Ecosystem, e.Name, e.Version, e.Error) } } + + // A partial mirror has to be visible in the exit status, or a CI step + // that prewarms the cache passes even when every download failed. + if code := mirrorExitCode(progress); code != 0 { + _ = db.Close() + os.Exit(code) //nolint:gocritic // db closed above + } +} + +// newCommandMirror builds the mirror proxy mirror runs, which fetches and +// lists versions from the configured upstreams. +func newCommandMirror(cfg *config.Config, proxy *handler.Proxy, images *handler.ContainerHandler, + db *database.DB, store storage.Storage, logger *slog.Logger, workers int) *mirror.Mirror { + m := mirror.New(proxy, db, store, logger, workers) + m.Images = images + m.Bottles = handler.NewHomebrewHandler(proxy, cfg.Upstream.HomebrewAPI) + m.Charts = handler.NewHelmHandler(proxy, cfg.BaseURL, cfg.Upstream.Helm) + server.UseMirrorUpstreams(m, cfg.Upstream, proxy.HTTPClient) + if cfg.Scanning.Enabled { + refuseUnscannedMirroring(m) + } + return m +} + +// useCommandGit opens the git cache for the pkg:git items of proxy mirror, +// when upstream.git is configured, and returns the function that closes it. +// Where it can't be opened, such as while the running server holds +// git.cache_dir, those items fail with the reason and the rest are mirrored. +func useCommandGit(cfg *config.Config, proxy *handler.Proxy, m *mirror.Mirror, logger *slog.Logger) func() { + git, closeGit, err := server.NewMirrorGit(cfg, proxy, logger) + if err != nil { + m.Git = mirror.UnavailableGit{Reason: fmt.Sprintf("this command can't open the git cache (%v); while the server runs, use its mirror API", err)} + return func() {} + } + if git == nil { + return func() {} + } + m.Git = git + return func() { + if err := closeGit(); err != nil { + logger.Warn("closing the git cache", "error", err) + } + } +} + +// mirrorExitCode returns the exit status for a finished mirror run: 1 when any +// package version failed to mirror, 0 otherwise. +func mirrorExitCode(progress *mirror.Progress) int { + if progress != nil && progress.Failed > 0 { + return 1 + } + return 0 +} + +// Reasons the mirror command gives for refusing items while scanning is +// enabled. +const ( + mirrorScanningImagesReason = "container images cannot be mirrored by this command while scanning is enabled; use the mirror API of the running server" + mirrorScanningPackagesReason = "packages cannot be mirrored by this command while scanning is enabled; use the mirror API of the running server" +) + +// refuseUnscannedMirroring makes m fail every item instead of caching it. +// Scanners fetch the staged bytes from the running server, which this command +// does not start, so anything it cached would skip the pre-cache scan and +// later be served from the cache unscanned. The mirror API's jobs run inside +// the server with its scanners and are unaffected. +func refuseUnscannedMirroring(m *mirror.Mirror) { + m.Images = mirror.UnavailableImages{Reason: mirrorScanningImagesReason} + m.RefusePackages = mirrorScanningPackagesReason } func printStats(db *database.DB, popular, recent int, asJSON bool) error { @@ -743,6 +826,14 @@ func formatSize(bytes int64) string { } } +// printEnvWarnings reports environment values LoadFromEnv ignored. serve +// logs them from server.Start; mirror never gets there. +func printEnvWarnings(cfg *config.Config) { + for _, warning := range cfg.EnvWarnings() { + fmt.Fprintf(os.Stderr, "warning: %s\n", warning) + } +} + func loadConfig(path string) (*config.Config, error) { if path != "" { return config.Load(path) diff --git a/cmd/proxy/main_test.go b/cmd/proxy/main_test.go index 4393c44..d5a020d 100644 --- a/cmd/proxy/main_test.go +++ b/cmd/proxy/main_test.go @@ -35,6 +35,7 @@ func TestServeHelpListsUpstreamEnvironmentVariables(t *testing.T) { "PROXY_UPSTREAM_COMPOSER", "PROXY_UPSTREAM_COMPOSER_REPOSITORY", "PROXY_UPSTREAM_CONAN", + "PROXY_UPSTREAM_CHEF", "PROXY_UPSTREAM_CONDA", "PROXY_UPSTREAM_CRAN", "PROXY_UPSTREAM_JULIA", @@ -56,3 +57,24 @@ func TestServeHelpProcess(*testing.T) { os.Args = []string{"proxy", "serve", "-help"} main() } + +func TestMirrorLogsEnvWarnings(t *testing.T) { + cmd := exec.Command(os.Args[0], "-test.run=^TestMirrorEnvWarningsProcess$") + // The negative size stops mirror before it opens any storage. + cmd.Env = append(os.Environ(), + "PROXY_TEST_MIRROR_ENV_WARNINGS=1", + "PROXY_CACHE_METADATA=maybe", + "PROXY_STORAGE_MAX_SIZE=-1") + output, _ := cmd.CombinedOutput() + if !strings.Contains(string(output), "PROXY_CACHE_METADATA") { + t.Errorf("mirror did not warn about PROXY_CACHE_METADATA:\n%s", output) + } +} + +func TestMirrorEnvWarningsProcess(*testing.T) { + if os.Getenv("PROXY_TEST_MIRROR_ENV_WARNINGS") != "1" { + return + } + os.Args = []string{"proxy", "mirror", "pkg:npm/lodash@4.17.21"} + main() +} diff --git a/cmd/proxy/mirror_git_test.go b/cmd/proxy/mirror_git_test.go new file mode 100644 index 0000000..2789536 --- /dev/null +++ b/cmd/proxy/mirror_git_test.go @@ -0,0 +1,132 @@ +package main + +import ( + "net/http" + "net/http/cgi" + "net/http/httptest" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/git-pkgs/proxy/internal/gitcache" +) + +// gitMirrorUpstream serves team/repo, with one commit on main, from git +// http-backend, and returns the server and the commit. +func gitMirrorUpstream(t *testing.T) (*httptest.Server, string) { + t.Helper() + git := func(dir string, args ...string) string { + t.Helper() + cmd := exec.Command("git", args...) + cmd.Dir = dir + cmd.Env = []string{ + "PATH=" + os.Getenv("PATH"), "HOME=" + t.TempDir(), "GIT_CONFIG_NOSYSTEM=1", + "GIT_AUTHOR_NAME=test", "GIT_AUTHOR_EMAIL=test@example.com", + "GIT_COMMITTER_NAME=test", "GIT_COMMITTER_EMAIL=test@example.com", + } + out, err := cmd.CombinedOutput() + if err != nil { + t.Fatalf("git %s: %v\n%s", strings.Join(args, " "), err, out) + } + return strings.TrimSpace(string(out)) + } + backend := "" + for _, name := range []string{"git-http-backend", "git-http-backend.exe"} { + if path := filepath.Join(git("", "--exec-path"), name); fileExistsForTest(path) { + backend = path + } + } + if backend == "" { + t.Skip("git http-backend is not installed") + } + root := t.TempDir() + bare := filepath.Join(root, "team", "repo.git") + git("", "init", "--quiet", "--bare", "--initial-branch=main", bare) + work := t.TempDir() + git("", "clone", "--quiet", bare, work) + git(work, "commit", "--quiet", "--allow-empty", "-m", "first") + git(work, "push", "--quiet", "origin", "HEAD:main") + head := git(work, "rev-parse", "HEAD") + + server := httptest.NewServer(&cgi.Handler{ + Path: backend, + Env: []string{"PATH=" + os.Getenv("PATH"), "GIT_PROJECT_ROOT=" + root, "GIT_HTTP_EXPORT_ALL=1"}, + }) + t.Cleanup(server.Close) + return server, head +} + +func fileExistsForTest(path string) bool { + _, err := os.Stat(path) + return err == nil +} + +// writeGitMirrorConfig writes a config with upstream.git "up" at +// upstreamURL and the git cache, storage and database under dir. +func writeGitMirrorConfig(t *testing.T, dir, upstreamURL string) string { + t.Helper() + cfg := "storage:\n" + + " url: file://" + filepath.Join(dir, "artifacts") + "\n" + + "database:\n" + + " path: " + filepath.Join(dir, "proxy.db") + "\n" + + "upstream:\n" + + " allow_loopback: true\n" + + " git:\n" + + " up: " + upstreamURL + "\n" + + "git:\n" + + " cache_dir: " + filepath.Join(dir, "git") + "\n" + path := filepath.Join(dir, "config.yaml") + if err := os.WriteFile(path, []byte(cfg), 0o600); err != nil { + t.Fatalf("writing config: %v", err) + } + return path +} + +func TestMirrorCommandCachesGitCommit(t *testing.T) { + upstream, head := gitMirrorUpstream(t) + dir := t.TempDir() + configPath := writeGitMirrorConfig(t, dir, upstream.URL) + purl := "pkg:git/" + strings.TrimPrefix(upstream.URL, "http://") + "/team/repo@" + head + + output := runMirrorProcess(t, 0, "-config", configPath, purl) + if !strings.Contains(output, "1 downloaded") { + t.Errorf("output:\n%s", output) + } + cached, _ := filepath.Glob(filepath.Join(dir, "git", "up-*", "team", "repo.git")) + if len(cached) != 1 { + t.Errorf("cached repositories %v, want team/repo.git", cached) + } + + output = runMirrorProcess(t, 0, "-config", configPath, purl) + if !strings.Contains(output, "1 skipped") { + t.Errorf("second run output:\n%s", output) + } +} + +// TestMirrorCommandGitCacheInUse checks pkg:git items fail, pointing at the +// mirror API, while the running server holds git.cache_dir. +func TestMirrorCommandGitCacheInUse(t *testing.T) { + upstream, head := gitMirrorUpstream(t) + dir := t.TempDir() + configPath := writeGitMirrorConfig(t, dir, upstream.URL) + cache, err := gitcache.New(gitcache.Options{ + CacheDir: filepath.Join(dir, "git"), + RefreshWait: time.Second, + Client: &http.Client{}, + }) + if err != nil { + t.Fatal(err) + } + defer func() { _ = cache.Close() }() + purl := "pkg:git/" + strings.TrimPrefix(upstream.URL, "http://") + "/team/repo@" + head + + output := runMirrorProcess(t, 1, "-config", configPath, purl) + for _, want := range []string{"in use by another process", "mirror API", "1 failed"} { + if !strings.Contains(output, want) { + t.Errorf("output missing %q:\n%s", want, output) + } + } +} diff --git a/cmd/proxy/mirror_swift_test.go b/cmd/proxy/mirror_swift_test.go new file mode 100644 index 0000000..28fa8ba --- /dev/null +++ b/cmd/proxy/mirror_swift_test.go @@ -0,0 +1,186 @@ +package main + +import ( + "crypto/sha256" + "encoding/hex" + "encoding/json" + "fmt" + "io" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "sync/atomic" + "testing" + + "github.com/git-pkgs/proxy/internal/database" +) + +const swiftWidgetArchive = "acme widget archive" + +// swiftMirrorUpstream serves acme.widget 1.0.0 the way a Swift package +// registry does, with https://github.com/acme/widget as its source +// repository, and counts archive downloads and identifier lookups. The +// repository's identifiers are ids, or only acme.widget. +func swiftMirrorUpstream(t *testing.T, ids ...string) (srv *httptest.Server, downloads, lookups *atomic.Int64) { + t.Helper() + if len(ids) == 0 { + ids = []string{"acme.widget"} + } + identifiers, err := json.Marshal(map[string][]string{"identifiers": ids}) + if err != nil { + t.Fatal(err) + } + downloads, lookups = new(atomic.Int64), new(atomic.Int64) + sum := sha256.Sum256([]byte(swiftWidgetArchive)) + srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Version", "1") + switch r.URL.Path { + case "/identifiers": + lookups.Add(1) + if r.URL.Query().Get("url") != "https://github.com/acme/widget" { + http.NotFound(w, r) + return + } + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write(identifiers) + case "/acme/widget": + w.Header().Set("Content-Type", "application/json") + _, _ = io.WriteString(w, `{"releases":{"1.0.0":{}}}`) + case "/acme/widget/1.0.0/Package.swift": + w.Header().Set("Content-Type", "text/x-swift") + _, _ = io.WriteString(w, "// swift-tools-version:5.9\n") + case "/acme/widget/1.0.0": + w.Header().Set("Content-Type", "application/json") + _, _ = fmt.Fprintf(w, `{"id":"acme.widget","version":"1.0.0","resources":[{"name":"source-archive","type":"application/zip","checksum":%q}]}`, hex.EncodeToString(sum[:])) + case "/acme/widget/1.0.0.zip": + downloads.Add(1) + w.Header().Set("Content-Type", "application/zip") + _, _ = io.WriteString(w, swiftWidgetArchive) + default: + http.NotFound(w, r) + } + })) + t.Cleanup(srv.Close) + return srv, downloads, lookups +} + +// writeSwiftMirrorConfig writes a config using upstream as the Swift +// registry, denying the denied package PURLs. +func writeSwiftMirrorConfig(t *testing.T, dir, upstream string, denied ...string) string { + t.Helper() + cfg := "storage:\n" + + " url: file://" + filepath.Join(dir, "artifacts") + "\n" + + "database:\n" + + " path: " + filepath.Join(dir, "proxy.db") + "\n" + + "upstream:\n" + + " swift: " + upstream + "\n" + + " allow_loopback: true\n" + if len(denied) > 0 { + cfg += "denylist:\n packages:\n" + for _, p := range denied { + cfg += " - " + p + "\n" + } + } + path := filepath.Join(dir, "config.yaml") + if err := os.WriteFile(path, []byte(cfg), 0o600); err != nil { + t.Fatalf("writing config: %v", err) + } + return path +} + +func cachedArtifacts(t *testing.T, dir string) int64 { + t.Helper() + db, err := database.Open(filepath.Join(dir, "proxy.db")) + if err != nil { + t.Fatalf("opening database: %v", err) + } + defer func() { _ = db.Close() }() + stats, err := db.GetCacheStats() + if err != nil { + t.Fatalf("GetCacheStats: %v", err) + } + return stats.TotalArtifacts +} + +// Without a denylist the fake registry mirrors the release, so the tests +// below fail for the denylist and not for the setup. +func TestMirrorSwiftRelease(t *testing.T) { + upstream, downloads, _ := swiftMirrorUpstream(t) + dir := t.TempDir() + configPath := writeSwiftMirrorConfig(t, dir, upstream.URL) + + output := runMirrorProcess(t, 0, "-config", configPath, "pkg:swift/acme/widget@1.0.0") + + if !strings.Contains(output, "1 downloaded") { + t.Errorf("output:\n%s", output) + } + if n := downloads.Load(); n != 1 { + t.Errorf("archive downloads = %d, want 1", n) + } + if n := cachedArtifacts(t, dir); n != 1 { + t.Errorf("cached artifacts = %d, want 1", n) + } +} + +// A denylist entry naming the package by its source repository blocks the +// mirror download of the registry identity it resolves to. +func TestMirrorDenylistSwiftSourceEntry(t *testing.T) { + upstream, downloads, _ := swiftMirrorUpstream(t) + dir := t.TempDir() + configPath := writeSwiftMirrorConfig(t, dir, upstream.URL, "pkg:swift/github.com/acme/widget@1.0.0") + + output := runMirrorProcess(t, 1, "-config", configPath, "pkg:swift/acme/widget@1.0.0") + + if !strings.Contains(output, "0 downloaded") || !strings.Contains(output, "1 failed") { + t.Errorf("output:\n%s", output) + } + if n := downloads.Load(); n != 0 { + t.Errorf("archive downloads = %d, want 0", n) + } + if n := cachedArtifacts(t, dir); n != 0 { + t.Errorf("cached artifacts = %d, want 0", n) + } +} + +// The registry may list several identities for one repository. A source +// entry denies all of them, not only the first. +func TestMirrorDenylistSwiftSourceEntryEveryIdentity(t *testing.T) { + upstream, downloads, _ := swiftMirrorUpstream(t, "other.widget", "acme.widget") + dir := t.TempDir() + configPath := writeSwiftMirrorConfig(t, dir, upstream.URL, "pkg:swift/github.com/acme/widget@1.0.0") + + output := runMirrorProcess(t, 1, "-config", configPath, "pkg:swift/acme/widget@1.0.0") + + if !strings.Contains(output, "0 downloaded") || !strings.Contains(output, "1 failed") { + t.Errorf("output:\n%s", output) + } + if n := downloads.Load(); n != 0 { + t.Errorf("archive downloads = %d, want 0", n) + } +} + +// A source repository entry the registry can't resolve stops the mirror +// before it downloads anything, as it stops serve: left out, it would let +// the version through. +func TestMirrorDenylistUnresolvedSwiftSource(t *testing.T) { + upstream, downloads, lookups := swiftMirrorUpstream(t) + dir := t.TempDir() + configPath := writeSwiftMirrorConfig(t, dir, upstream.URL, "pkg:swift/github.com/acme/unknown@1.0.0") + + output := runMirrorProcess(t, 1, "-config", configPath, "pkg:swift/acme/widget@1.0.0") + + if !strings.Contains(output, "configuring denylist") || !strings.Contains(output, "github.com/acme/unknown") { + t.Errorf("output does not report the unresolved entry:\n%s", output) + } + if strings.Contains(output, "Mirror complete") { + t.Errorf("mirror ran:\n%s", output) + } + if lookups.Load() == 0 { + t.Error("the entry was not looked up") + } + if n := downloads.Load(); n != 0 { + t.Errorf("archive downloads = %d, want 0", n) + } +} diff --git a/cmd/proxy/mirror_test.go b/cmd/proxy/mirror_test.go new file mode 100644 index 0000000..bd39de9 --- /dev/null +++ b/cmd/proxy/mirror_test.go @@ -0,0 +1,214 @@ +package main + +import ( + "errors" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + + "github.com/git-pkgs/proxy/internal/database" + "github.com/git-pkgs/proxy/internal/mirror" +) + +// mirrorTestEnv carries the mirror command's arguments into the helper +// process, one per line. +const mirrorTestEnv = "PROXY_TEST_MIRROR_ARGS" + +// writeScanningMirrorConfig writes a config with scanning enabled and storage +// and database under dir. The scanner address is never reached. +func writeScanningMirrorConfig(t *testing.T, dir string) string { + t.Helper() + cfg := "storage:\n" + + " url: file://" + filepath.Join(dir, "artifacts") + "\n" + + "database:\n" + + " path: " + filepath.Join(dir, "proxy.db") + "\n" + + "scanning:\n" + + " enabled: true\n" + + " signing_key: test-signing-key\n" + + " scanners:\n" + + " - name: test\n" + + " url: http://127.0.0.1:1/scan\n" + path := filepath.Join(dir, "config.yaml") + if err := os.WriteFile(path, []byte(cfg), 0o600); err != nil { + t.Fatalf("writing config: %v", err) + } + return path +} + +// runMirrorProcess runs proxy mirror with args in a helper process and +// checks that it exits with wantCode. +func runMirrorProcess(t *testing.T, wantCode int, args ...string) string { + t.Helper() + cmd := exec.Command(os.Args[0], "-test.run=^TestMirrorHelperProcess$") + cmd.Env = append(os.Environ(), mirrorTestEnv+"="+strings.Join(args, "\n")) + output, err := cmd.CombinedOutput() + + code := 0 + var exitErr *exec.ExitError + if errors.As(err, &exitErr) { + code = exitErr.ExitCode() + } else if err != nil { + t.Fatalf("proxy mirror %v: %v\n%s", args, err, output) + } + if code != wantCode { + t.Fatalf("proxy mirror %v exited with status %d, want %d\n%s", args, code, wantCode, output) + } + return string(output) +} + +// With scanning enabled, proxy mirror refuses packages rather than caching +// them unscanned: scanners fetch staged bytes from the running server, which +// the command does not start. +// A refused package counts as failed, so the command exits 1. +func TestMirrorCommandRefusesPackagesWhileScanning(t *testing.T) { + dir := t.TempDir() + configPath := writeScanningMirrorConfig(t, dir) + + output := runMirrorProcess(t, 1, "-config", configPath, "pkg:npm/lodash@4.17.21") + + for _, want := range []string{mirrorScanningPackagesReason, "0 downloaded", "1 failed"} { + if !strings.Contains(output, want) { + t.Errorf("output missing %q:\n%s", want, output) + } + } + + db, err := database.Open(filepath.Join(dir, "proxy.db")) + if err != nil { + t.Fatalf("opening database: %v", err) + } + defer func() { _ = db.Close() }() + stats, err := db.GetCacheStats() + if err != nil { + t.Fatalf("GetCacheStats: %v", err) + } + if stats.TotalArtifacts != 0 { + t.Errorf("cached artifacts = %d, want 0", stats.TotalArtifacts) + } + + var stored []string + _ = filepath.WalkDir(filepath.Join(dir, "artifacts"), func(path string, d os.DirEntry, err error) error { + if err == nil && !d.IsDir() { + stored = append(stored, path) + } + return nil + }) + if len(stored) != 0 { + t.Errorf("files written to storage: %v", stored) + } +} + +// A dry run caches nothing, so it still lists what would be mirrored. +func TestMirrorCommandDryRunWhileScanning(t *testing.T) { + configPath := writeScanningMirrorConfig(t, t.TempDir()) + + output := runMirrorProcess(t, 0, "-config", configPath, "-dry-run", "pkg:npm/lodash@4.17.21") + + if !strings.Contains(output, "Would mirror 1 package versions") { + t.Errorf("dry run output:\n%s", output) + } + if strings.Contains(output, mirrorScanningPackagesReason) { + t.Errorf("dry run reported the refusal:\n%s", output) + } +} + +func TestMirrorCommandSBOMComponentVersion(t *testing.T) { + dir := t.TempDir() + configPath := writeScanningMirrorConfig(t, dir) + sbomPath := filepath.Join(dir, "bom.json") + data := []byte(`{"components":[{"name":"app","version":"1.0","purl":"pkg:docker/ghcr.io/team/app"}]}`) + if err := os.WriteFile(sbomPath, data, 0600); err != nil { + t.Fatal(err) + } + output := runMirrorProcess(t, 0, "-config", configPath, "-dry-run", "-sbom", sbomPath) + for _, want := range []string{"Would mirror 1 package versions", "pkg:docker/ghcr.io/team/app@1.0"} { + if !strings.Contains(output, want) { + t.Errorf("dry run missing %q:\n%s", want, output) + } + } +} + +func TestRefuseUnscannedMirroring(t *testing.T) { + m := mirror.New(nil, nil, nil, nil, 1) + refuseUnscannedMirroring(m) + + if m.RefusePackages != mirrorScanningPackagesReason { + t.Errorf("RefusePackages = %q, want %q", m.RefusePackages, mirrorScanningPackagesReason) + } + images, ok := m.Images.(mirror.UnavailableImages) + if !ok || images.Reason != mirrorScanningImagesReason { + t.Errorf("Images = %#v, want UnavailableImages with the scanning reason", m.Images) + } +} + +func TestMirrorHelperProcess(*testing.T) { + args := os.Getenv(mirrorTestEnv) + if args == "" { + return + } + os.Args = append([]string{"proxy", "mirror"}, strings.Split(args, "\n")...) + main() +} + +func TestMirrorExitCode(t *testing.T) { + tests := []struct { + name string + progress *mirror.Progress + want int + }{ + {"nil progress", nil, 0}, + {"everything mirrored", &mirror.Progress{Total: 2, Completed: 2}, 0}, + {"everything cached", &mirror.Progress{Total: 2, Skipped: 2}, 0}, + {"one failure", &mirror.Progress{Total: 2, Completed: 1, Failed: 1}, 1}, + {"all failed", &mirror.Progress{Total: 3, Failed: 3}, 1}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := mirrorExitCode(tt.progress); got != tt.want { + t.Errorf("mirrorExitCode() = %d, want %d", got, tt.want) + } + }) + } +} + +// proxy mirror used to exit 0 after printing "N failed", so a CI step that +// prewarms the cache passed even when every download failed (#500). An +// ecosystem the resolver rejects fails without touching the network. +func TestMirrorExitsNonZeroWhenDownloadsFail(t *testing.T) { + dir := t.TempDir() + cmd := exec.Command(os.Args[0], "-test.run=^TestMirrorFailureProcess$") + cmd.Env = append(os.Environ(), + "PROXY_TEST_MIRROR_FAILURE=1", + "PROXY_TEST_MIRROR_DIR="+dir, + ) + output, err := cmd.CombinedOutput() + + var exitErr *exec.ExitError + if !errors.As(err, &exitErr) { + t.Fatalf("mirror with a failed download exited with %v, want status 1\n%s", err, output) + } + if code := exitErr.ExitCode(); code != 1 { + t.Fatalf("exit status = %d, want 1\n%s", code, output) + } + if !strings.Contains(string(output), "1 failed") { + t.Errorf("output does not report the failure:\n%s", output) + } + if !strings.Contains(string(output), "bogus/foo@1.0.0") { + t.Errorf("output does not list the failed package:\n%s", output) + } +} + +func TestMirrorFailureProcess(*testing.T) { + if os.Getenv("PROXY_TEST_MIRROR_FAILURE") != "1" { + return + } + dir := os.Getenv("PROXY_TEST_MIRROR_DIR") + os.Args = []string{ + "proxy", "mirror", + "--storage-url", "file://" + filepath.Join(dir, "store"), + "--database-path", filepath.Join(dir, "cache.db"), + "pkg:bogus/foo@1.0.0", + } + main() +} diff --git a/config.example.yaml b/config.example.yaml index accae89..002d506 100644 --- a/config.example.yaml +++ b/config.example.yaml @@ -14,6 +14,19 @@ base_url: "http://localhost:8080" # Set to "0" to disable the timeout. Default: "30s". # http_timeout: "30s" +# Response write deadline, including download and scan time before sending data. +# Set to "0" to disable. Default: "5m". +# write_timeout: "5m" + +# Timeout for each upstream artifact download while serving requests; excludes +# scanning. Set to "0" to disable. Default: "5m". Does not limit proxy mirror. +# artifact_timeout: "5m" + +# Register DELETE /api/cache and show Delete buttons on the UI's version page, +# for removing cached artifacts so they are fetched again. Has no +# authentication: restrict /api/cache and /ui at the ingress first. +# cache_delete: false + # Largest upstream artifact to fetch (e.g. "2GB"). Larger ones are refused # and not cached. Default: unlimited. # artifact_max_size: "" @@ -91,19 +104,24 @@ storage: # The default only applies to ecosystems that support retention; naming an # ecosystem or package that does not is a configuration error. See # docs/configuration.md for the supported ecosystems. + # Generic downloads require an explicit ecosystem or package rule; + # they never inherit default, since an upstream release may disappear. retention: default: "" # ecosystems: # npm: "30d" + # generic: "30d" # packages: # "pkg:npm/lodash": "0" + # "pkg:generic/owner%2Frepo": "90d" # How often to look for expired artifacts; at least "1m". sweep_interval: "10m" # Store fetched artifacts. Set to false to stream every download from # upstream without storing it; metadata filtering, cooldown and the # denylist still apply. Useful when another cache sits in front of the - # proxy. false is incompatible with direct_serve, scanning and mirror_api. + # proxy. false is incompatible with direct_serve, scanning, mirror_api, + # mirror.schedules and mirror.refresh. cache_artifacts: true # Redirect cached artifact downloads to presigned storage URLs (HTTP 302) @@ -171,6 +189,10 @@ upstream: # npm_routes: # "@example/*": "https://npm.example.com/registry" + # Follow the npm registry's change feed, so a new release is fetched on the + # next request instead of after metadata_ttl. Requires cache_metadata. + # npm_change_feed: true + # Cargo sparse index URL cargo: "https://index.crates.io" @@ -201,6 +223,12 @@ upstream: # Maven repository URL (used by /maven endpoint) maven: "https://repo1.maven.org/maven2" + # Additional Maven repositories, served at /maven/{name}/. A name must not + # be the start of a group ID (such as "org" or "tools"), since it would hide + # those groups in the default repository. + # maven_repositories: + # grails: "https://repo.grails.org/grails/restricted" + # Gradle Plugin Portal Maven URL (fallback for plugin marker artifacts) gradle_plugin_portal: "https://plugins.gradle.org/m2" @@ -221,9 +249,18 @@ upstream: # composer_routes: # "example/*": "https://composer.example.com/packages" + # Follow the change feed of the Packagist at composer, so a new release is + # fetched on the next request instead of after metadata_ttl. Requires + # cache_metadata. + # composer_change_feed: true + # Conan registry URL conan: "https://center.conan.io" + # Chef Supermarket URL (used by /chef/). Point it at a private + # Supermarket to proxy that instead. + chef: "https://supermarket.chef.io" + # Conda channel base URL conda: "https://conda.anaconda.org" @@ -287,6 +324,14 @@ upstream: # archlinux: "https://geo.mirror.pkgbuild.com" # archlinuxarm: "https://.mirror.archlinuxarm.org" + # Named FreeBSD pkg mirrors (used by /freebsd/{name}/), for ports and + # pkgbase repositories alike. + # Defaults to {"freebsd": "https://pkg.freebsd.org"} when empty; + # configuring any entry replaces that default. + # freebsd: + # freebsd: "https://pkg.freebsd.org" + # poudriere: "https://packages.example.com" + # Named generic HTTP upstreams (used by /generic/{name}/). The remaining # request path and query are appended to the upstream URL. GitHub release # assets ({owner}/{repo}/releases/download/{tag}/{asset}) are cached @@ -296,6 +341,18 @@ upstream: # github-api: "https://api.github.com" # apache: "https://archive.apache.org" + # Paths a generic upstream may serve, as path.Match patterns for the path + # after /generic/{name}/; a pattern ending in /** also matches everything + # nested below its prefix. Other paths answer 404. Required for an upstream + # that upstream.auth has credentials for, such as a GitHub token for + # api.github.com; use a fine-grained token with read-only access to public + # repositories. + # generic_paths: + # github-api: + # - "repos/*/*/releases" + # - "repos/*/*/releases/**" + # - "repos/*/*/tags" + # Version-pinned paths of generic upstreams, cached immutably like GitHub # release assets. Each pattern must match the whole path after # /generic/{name}/ and have `version` and `file` named groups; an optional @@ -304,6 +361,15 @@ upstream: # apache: # - 'dist/(?Pmaven)/maven-3/(?P[^/]+)/binaries/(?P[^/]+)' + # Named Git servers (used by /git/{name}/{repo}), served read-only from + # cached bare repositories. repos limits which repositories may be served + # and is required when upstream.auth has credentials for the server. + # git: + # github: "https://github.com" + # wikimedia: + # url: "https://gerrit.wikimedia.org/r" + # repos: ["mediawiki/**"] + # Authentication for upstream registries # Keys are absolute URL scopes. Scheme, host, effective port, and path # segment boundaries must match; the longest matching scope wins. @@ -344,11 +410,20 @@ upstream: # "https://123456789012.dkr.ecr.eu-west-1.amazonaws.com": # type: ecr +# Git repository cache, used when upstream.git is set +# git: +# cache_dir: ./cache/git # local disk, used by this process only +# max_size: "" # evict least recently used repositories past this +# max_repo_size: 5GB # refuse a repository that grows past this +# refresh_wait: 5s # then serve the cached copy if the upstream check is slow +# stale_max_age: 24h # never serve a copy not checked for this long + # Gradle HttpBuildCache configuration gradle: build_cache: - # Set to true to disable PUT uploads (read-only cache mode) - read_only: false + # PUT uploads are rejected by default; set to false on the instance + # your CI jobs upload to + read_only: true # Maximum accepted Gradle cache upload body size # Required and must be > 0 @@ -376,6 +451,33 @@ gradle: # npm_scopes: ["@acme"] # composer_vendors: ["acme"] +# Project inventory (disabled by default). Repositories upload an SBOM to +# PUT /api/projects/{project}/sbom, and the UI shows which project uses +# which package versions. Project names are visible on the unauthenticated UI. +# projects: +# enabled: true +# token: "${PROXY_PROJECTS_TOKEN}" +# # Drop projects that have not uploaded for this long ("" keeps them) +# max_age: "90d" + +# Re-mirror container image tags on a schedule, so a moved tag is picked up +# even when nobody pulls it. An unchanged tag costs one HEAD request. +# mirror: +# schedules: +# - images: ["pkg:docker/library/alpine@3.20", "pkg:docker/library/nginx@stable"] +# interval: "6h" +# platforms: ["linux/amd64"] +# +# Mirror new releases of the most used packages in the background, so the +# first install after a release doesn't wait on the upstream. Cooldown and +# the denylist apply. +# refresh: +# interval: "24h" +# top: 50 # packages per ecosystem, by recent downloads +# since: "14d" +# max_versions: 200 # per run; default no cap +# max_bytes: "2GB" # per run; default no cap + # Health endpoint configuration. health: # Minimum time between storage backend probes. @@ -390,6 +492,13 @@ health: # to spot malicious releases before they're pulled into projects. # Supported durations: "7d" (days), "48h" (hours), "30m" (minutes), "0" (disabled) cooldown: + # Independent policies selected through /cooldown/{name}/{registry}/. + # profiles: + # 3d: + # default: "3d" + # 7d: + # default: "7d" + # Global default cooldown for all ecosystems # default: "3d" diff --git a/deploy/charts/proxy/templates/deployment.yaml b/deploy/charts/proxy/templates/deployment.yaml index 0c8efb3..f04728a 100644 --- a/deploy/charts/proxy/templates/deployment.yaml +++ b/deploy/charts/proxy/templates/deployment.yaml @@ -33,6 +33,10 @@ spec: imagePullSecrets: {{- toYaml . | nindent 8 }} {{- end }} + {{- with .Values.extraInitContainers }} + initContainers: + {{- toYaml . | nindent 8 }} + {{- end }} containers: - name: {{ .Chart.Name }} image: {{ include "proxy.image" . | quote }} @@ -70,6 +74,11 @@ spec: readOnly: true - name: data mountPath: {{ .Values.persistence.mountPath }} + - name: tmp + mountPath: /tmp + {{- with .Values.extraVolumeMounts }} + {{- toYaml . | nindent 12 }} + {{- end }} volumes: - name: config configMap: @@ -84,6 +93,16 @@ spec: {{- else }} emptyDir: {} {{- end }} + - name: tmp + emptyDir: + {{- with .Values.tmpDir.sizeLimit }} + sizeLimit: {{ . }} + {{- else }} + {} + {{- end }} + {{- with .Values.extraVolumes }} + {{- toYaml . | nindent 8 }} + {{- end }} {{- with .Values.nodeSelector }} nodeSelector: {{- toYaml . | nindent 8 }} diff --git a/deploy/charts/proxy/values.yaml b/deploy/charts/proxy/values.yaml index 3861784..bbb253f 100644 --- a/deploy/charts/proxy/values.yaml +++ b/deploy/charts/proxy/values.yaml @@ -1,6 +1,8 @@ -# More than one replica requires config.data.database on Postgres, -# config.data.storage on object storage, deploymentStrategy: RollingUpdate, -# and a PVC access mode other than ReadWriteOnce (or persistence disabled). +# More than one replica requires config.data.database on Postgres and +# deploymentStrategy: RollingUpdate. Storage can be object storage (with +# persistence disabled) or a file:// URL on a ReadWriteMany volume +# (persistence.accessModes: [ReadWriteMany]). With upstream.git, each +# replica also needs its own git.cache_dir. replicaCount: 1 nameOverride: "" @@ -54,6 +56,35 @@ extraEnvFrom: [] # - secretRef: # name: proxy-object-storage +# Additional volumes for the pod and mounts for the proxy container, for +# example a ConfigMap holding a private CA certificate. Go adds certificates +# from the directories in SSL_CERT_DIR to its trusted roots (set it with +# extraEnv); SSL_CERT_FILE replaces the system bundle instead. All upstream +# TLS, including Git fetches, goes through the proxy process. +extraVolumes: [] +# - name: corp-ca +# configMap: +# name: corp-ca + +extraVolumeMounts: [] +# - name: corp-ca +# mountPath: /etc/proxy/ca +# readOnly: true + +# Init containers run before the proxy starts. They can use extraVolumes, but +# extraVolumeMounts applies only to the proxy container, so each init container +# needs its own volumeMounts. +extraInitContainers: [] +# - name: wait-for-db +# image: busybox:1.37 +# command: ["sh", "-c", "until nc -z postgres 5432; do sleep 2; done"] + +# With SQLite, the database file needs a local disk or block-backed volume, +# even with one replica. ReadWriteOnce doesn't guarantee that: pick a +# storageClass that isn't NFS or another network filesystem. If only network +# filesystem storage is available, set config.data.database to Postgres. +# Artifact storage can stay on NFS on a separate volume (extraVolumes and +# extraVolumeMounts, with config.data.storage.url pointing at it). persistence: enabled: true # Keep this aligned with config.data.storage.url and config.data.database.path @@ -101,6 +132,10 @@ containerSecurityContext: drop: - ALL +# /tmp is an emptyDir, since the root filesystem is read-only. +tmpDir: + sizeLimit: "" + resources: {} # requests: # cpu: 100m diff --git a/deploy/grafana/git-pkgs-proxy.json b/deploy/grafana/git-pkgs-proxy.json index e875469..2592625 100644 --- a/deploy/grafana/git-pkgs-proxy.json +++ b/deploy/grafana/git-pkgs-proxy.json @@ -365,13 +365,13 @@ "uid": "${datasource}" }, "editorMode": "code", - "expr": "sum(increase(proxy_cache_hits_total{job=~\"$job\", ecosystem=~\"$ecosystem\"}[$__range]))\n/\n(\n sum(increase(proxy_cache_hits_total{job=~\"$job\", ecosystem=~\"$ecosystem\"}[$__range]))\n +\n sum(increase(proxy_cache_misses_total{job=~\"$job\", ecosystem=~\"$ecosystem\"}[$__range]))\n)", + "expr": "sum(increase(proxy_cache_hits_total{job=~\"$job\", ecosystem=~\"$ecosystem\", kind=\"artifact\"}[$__range]))\n/\n(\n sum(increase(proxy_cache_hits_total{job=~\"$job\", ecosystem=~\"$ecosystem\", kind=\"artifact\"}[$__range]))\n +\n sum(increase(proxy_cache_misses_total{job=~\"$job\", ecosystem=~\"$ecosystem\", kind=\"artifact\"}[$__range]))\n)", "range": true, "instant": false, "refId": "A" } ], - "title": "Cache hit ratio", + "title": "Artifact cache hit ratio", "type": "stat" }, { @@ -981,11 +981,11 @@ "uid": "${datasource}" }, "editorMode": "code", - "expr": "sum(rate(proxy_cache_hits_total{job=~\"$job\", ecosystem=~\"$ecosystem\"}[$__rate_interval]))", + "expr": "sum by (kind) (rate(proxy_cache_hits_total{job=~\"$job\", ecosystem=~\"$ecosystem\"}[$__rate_interval]))", "range": true, "instant": false, "refId": "A", - "legendFormat": "hits" + "legendFormat": "{{kind}} hits" }, { "datasource": { @@ -993,11 +993,11 @@ "uid": "${datasource}" }, "editorMode": "code", - "expr": "sum(rate(proxy_cache_misses_total{job=~\"$job\", ecosystem=~\"$ecosystem\"}[$__rate_interval]))", + "expr": "sum by (kind) (rate(proxy_cache_misses_total{job=~\"$job\", ecosystem=~\"$ecosystem\"}[$__rate_interval]))", "range": true, "instant": false, "refId": "B", - "legendFormat": "misses" + "legendFormat": "{{kind}} misses" } ], "title": "Cache hits and misses", diff --git a/docs/architecture.md b/docs/architecture.md index a259e91..1d17426 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -34,7 +34,7 @@ The proxy is a caching HTTP server that sits between package manager clients and 1. Client requests `GET /npm/lodash` 2. NPMHandler receives request 3. Handler fetches metadata from upstream `registry.npmjs.org/lodash` -4. Handler rewrites tarball URLs in metadata to point at proxy +4. Handler rewrites tarball URLs in metadata to point at proxy, and filters versions withheld by cooldown or the denylist (`internal/metadata/npm`) 5. Handler returns modified metadata to client Metadata is not cached - always fetched fresh. This ensures clients see new versions immediately. @@ -51,16 +51,21 @@ Metadata is not cached - always fetched fresh. This ensures clients see new vers - Open file from storage - Record hit (increment counter, update last_accessed_at) - Return reader to handler - - Handler streams file to client + - Handler streams file to client, checking it against the recorded + SHA-256 `content_hash` (the registry's own integrity was checked when the + file was stored); a mismatch aborts the response and clears the record **Cache Miss:** - Resolve download URL using Resolver - Fetch artifact from upstream using Fetcher + - Copy the body to Storage and, for a client GET without a `Range` + header, to the client at once (`storeWhileServing`); the client's copy + is checked against the upstream's digest as it is read, and a mismatch + aborts it. A block-mode scanner, `HEAD` and range requests, and + requests joining a fetch already running wait for the stored file. - Store artifact in Storage (returns size, hash) - Create/update database records (package, version, artifact) - - Open stored file - - Return reader to handler - - Handler streams file to client + - Requests that waited open the stored file and stream it to their client Artifact handlers honor single byte ranges when the storage reader supports efficient seeking (currently the local filesystem reader). They advertise @@ -96,6 +101,8 @@ the full artifact digest because they read only part of the artifact. SQLite or PostgreSQL database for cache metadata. SQLite uses `modernc.org/sqlite` (pure Go, no CGO). PostgreSQL uses `lib/pq`. +For SQLite, `DB` holds two pools: one connection for writes and a pool of read-only (`query_only`) connections for reads. `Get`, `Select`, `Query` and `QueryRow` go to the reader; `Exec`, transactions and everything else go to the writer, so a read inside a transaction sees the transaction's writes. A write sent to the reader fails instead of running. WAL mode lets the readers run while the writer commits. PostgreSQL and in-memory SQLite use one pool for both. + The schema is compatible with [git-pkgs](https://github.com/git-pkgs) databases. The proxy adds the `artifacts` and `vulnerabilities` tables on top of the shared `packages` and `versions` tables, so both tools can point at the same database. **Tables:** @@ -200,7 +207,7 @@ metadata_dates ( ) ``` -`metadata_dates` holds the `Last-Modified` served with rewritten npm and Composer metadata. A package's date is the second it started serving its current representation, and a new representation is only dated in a later second. Keeping it in the database means replicas sharing one serve the same date, and never give one representation's date to another, so `If-Modified-Since` cannot return 304 for a body the client does not have. +`metadata_dates` holds the `Last-Modified` served with rewritten metadata, such as npm packuments, Composer documents, PyPI simple pages and Helm indexes. A package's date is the second it started serving its current representation, and a new representation is only dated in a later second. Keeping it in the database means replicas sharing one serve the same date, and never give one representation's date to another, so `If-Modified-Since` cannot return 304 for a body the client does not have. On PostgreSQL, `INTEGER PRIMARY KEY` becomes `SERIAL`, `DATETIME` becomes `TIMESTAMP`, `INTEGER DEFAULT 0` booleans become `BOOLEAN DEFAULT FALSE`, and size/count columns use `BIGINT`. @@ -290,16 +297,46 @@ HTTP protocol handlers for each registry type. **NPMHandler:** - `handlePackageMetadata()` - Proxy + rewrite metadata - `handleDownload()` - Serve cached artifact -- Rewrites tarball URLs to point at proxy +- Fetches, caches and serves packuments, and caches their rewrites; the rewrite itself is `internal/metadata/npm` **CargoHandler:** - `handleConfig()` - Return registry config - `handleIndex()` - Proxy sparse index - `handleDownload()` - Serve cached crate +**DebianHandler:** +- Serves `/debian` and `/debian/{name}` mirrors of APT archives (`upstream.debian_repositories`) +- Routes `.deb` packages to the artifact cache, `dists/…` to the metadata cache, and proxies all other paths +- Keys the artifact cache on name, version, and filename, scoped by repository for named archives + **SwiftHandler:** - Proxies the Swift Package Registry v1 read endpoints - Rewrites release URLs and caches source archives +- With `cache_metadata`, caches release metadata, release lists and manifests (with their `Link` header) and serves them when the upstream fails + +**GitHandler:** +- Serves `/git/{name}/{repo}` from `internal/gitcache`, read-only over smart HTTP +- Validates repository paths and the `repos` allowlist, and maps cache errors to statuses +- Serves the Git LFS API under `{repo}.git/info/lfs/`: forwards download batches upstream and points each object at `objects/{oid}/{size}`, which is served from the artifact cache (ecosystem `git`, name `{name}/{repo}`, version the object ID); a miss uses the download URL kept from the batch or asks the upstream batch API for a fresh one, recorded without its signed query, copies the object from another repository when its content is already stored, and checks the object against its sha256 ID; a batch the upstream can't answer is answered from the cache + +### `internal/metadata/npm` + +The npm metadata rewrite, separated from the handler so it can run where the proxy's infrastructure can't, such as WASI. It takes a packument's bytes and everything else as explicit inputs (proxy URL, cooldown policy, the time cooldown is evaluated at, denied versions, pushed versions) and returns the rewritten document with the versions it kept. It filters versions by cooldown and the denylist, moves `latest` off a withheld version, lists pushed versions in place of upstream ones, and points each tarball URL at the proxy, copying everything else byte for byte. It does no I/O and never reads the clock; callbacks report what it did, which the handler logs. `ScanPackument` and `RewriteStream` do the same rewrite over a reader in two passes, the first collecting the time map, dist-tags and version names and the second copying each kept version, so the handler can rewrite a packument from storage without holding it in memory. It imports no database, storage, metrics, HTTP or logging packages, which a test checks. + +### `internal/jsonscan` + +Reads and rewrites members of a JSON document in place, by byte offsets, without decoding the whole document. Shared by the npm and Composer metadata rewrites. + +### `internal/gitcache` + +Local bare clones of upstream Git repositories, outside the artifact cache and the database, at `{git.cache_dir}/{name}-{URL hash}/{repo}.git`. The hash of the upstream's URL means repointing an upstream starts a fresh cache; at startup only the configured upstreams' directories are loaded, and those of their old URLs removed. + +- Each request for refs checks the upstream's branches and tags with protocol v2 `ls-refs` and fetches only when they changed; concurrent requests share one refresh +- Clients are served by `git upload-pack --stateless-rpc` +- Spawned `git` reaches the upstream only through a loopback relay that forwards with the proxy's upstream client, so address checks, `upstream.auth` and the access log apply +- Commits a client asks for by ID that are on no cached branch or tag are fetched and kept under hidden `refs/proxy/wanted/{time}/{id}` refs until a branch or tag includes them or for 7 days; off for upstreams with credentials +- Evicts least recently used repositories after each fetch once `git.max_size` is passed, and drops a repository that can no longer be refreshed within `git.max_repo_size` so it is cloned again; never one in use. A commit fetched by ID that does not fit is refused instead +- Every fetched pack is kept as a pack (`transfer.unpackLimit=1`), so a transfer cut off at the size limit leaves nothing behind ### `internal/server` @@ -313,24 +350,32 @@ HTTP server setup, web UI, and API handlers. - Enrichment API for package metadata, vulnerability scanning, and outdated detection - Health, stats, and Prometheus metrics endpoints. `/health` runs an active write → size-check → read → verify → delete probe against the storage backend and returns a structured JSON response (`HealthResponse`) with `"ok"` / `"error"` status per subsystem. Probe results are cached (default 30 s, configurable via `health.storage_probe_interval`) to avoid overwhelming remote backends. The response also carries a `circuit_breakers` map reporting each upstream's artifact-fetch breaker as `"open"` or `"closed"`, keyed by the host fetched from (or an opaque placeholder where the fetch URL has no host to read); the same state is published as the `proxy_circuit_breaker_state` gauge on each `/metrics` scrape. An open breaker leaves the overall status `"ok"` — it describes an upstream, not this proxy. +### `internal/memlimit` + +Sets Go's soft memory limit to 80% of the cgroup memory limit at startup on Linux, unless `GOMEMLIMIT` is set. See "Memory limit" in the configuration docs. + ### `internal/metrics` Prometheus metrics for cache performance, upstream latency, storage operations, and active requests. See the Monitoring section of the README for the full metric list. ### Cooldown -Version age filtering for supply chain attack mitigation, provided by [github.com/git-pkgs/cooldown](https://github.com/git-pkgs/cooldown). Configurable at global, ecosystem, and per-package levels. Supported by npm, PyPI, pub.dev, and Composer handlers. +Version age filtering for supply chain attack mitigation, provided by [github.com/git-pkgs/cooldown](https://github.com/git-pkgs/cooldown). Configurable at global, ecosystem, and per-package levels. Supported by the npm, PyPI, pub.dev, Composer, Cargo, NuGet, Conda, RubyGems, Hex, Go, Maven and Helm handlers. ### `internal/enrichment` -Package metadata enrichment. Fetches license, description, homepage, repository URL, and vulnerability data from upstream registries. Powers the `/api/` endpoints and the web UI's package detail pages. +Package metadata enrichment, built on [github.com/git-pkgs/enrichment](https://github.com/git-pkgs/enrichment). Fetches license, description, homepage, repository URL, and vulnerability data from upstream registries. Powers the `/api/` endpoints and the web UI's package detail pages. ### `internal/mirror` -Selective package mirroring for pre-populating the proxy cache. Supports multiple input sources: individual PURLs (versioned or unversioned), CycloneDX/SPDX SBOM files, and full registry enumeration. Uses a bounded worker pool backed by `errgroup` to download artifacts in parallel, reusing `handler.Proxy.GetOrFetchArtifact()` for the actual fetch-and-cache work. Container images (`pkg:docker`, `pkg:oci`) go through `handler.ContainerHandler.MirrorImage()` instead, which walks index, platform manifests and blobs and stores them under the keys a pull reads. +Selective package mirroring for pre-populating the proxy cache. Supports multiple input sources: individual PURLs (versioned or unversioned), CycloneDX/SPDX SBOM files, and full registry enumeration. Uses a bounded worker pool backed by `errgroup` to download artifacts in parallel, reusing `handler.Proxy.GetOrFetchArtifact()` for the actual fetch-and-cache work. Container images (`pkg:docker`, `pkg:oci`) go through `handler.ContainerHandler.MirrorImage()` instead, which walks index, platform manifests and blobs and stores them under the keys a pull reads. Git repositories (`pkg:git`) go through `handler.GitHandler.Mirror()`, which caches the repository and the commit or tag, with its submodules, in the git cache that `/git` serves. The package also provides a `MetadataCache` for storing raw upstream metadata blobs so the proxy can serve metadata responses offline. The `JobStore` manages async mirror jobs exposed via the `/api/mirror` endpoints. +### `internal/inventory` + +Turns an SBOM uploaded to `/api/projects` into the package versions recorded for the project. Package URLs are mapped to the ecosystem names and unversioned PURLs the handlers record packages under, so a project's components join with `packages` by `purl`. Also compares versions for the outdated marker on the project pages. + ### `internal/config` Configuration loading. diff --git a/docs/configuration.md b/docs/configuration.md index ffd57fe..9717b1c 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -2,6 +2,8 @@ The proxy can be configured via command line flags, environment variables, or a configuration file. Command line flags take precedence over environment variables, which take precedence over the configuration file. +Boolean environment variables accept `true`, `t`, `1`, `yes` or `on`, and `false`, `f`, `0`, `no` or `off`, in any case. Any other value, such as a typo, is ignored: the setting keeps its value from the configuration file or default, and the proxy logs a warning at startup. + ## Configuration File Create a YAML or JSON file and pass it with `-config`: @@ -22,6 +24,26 @@ See `config.example.yaml` in the repository root for a complete example. | `trust_forwarded_for` | `PROXY_TRUST_FORWARDED_FOR` | - | `false` | Attribute requests to the leftmost `X-Forwarded-For` entry instead of the TCP peer address, in the structured log, the access log and the request-source table on `/ui/analytics`. | | `ui_request_sources` | `PROXY_UI_REQUEST_SOURCES` | - | `false` | Show the request-source table on `/ui/analytics`, which reports caller addresses, the tool each ran and how much each pulled. | | `ui_failure_details` | `PROXY_UI_FAILURE_DETAILS` | - | `false` | List the latest failures behind each failure count on `/ui/analytics`: the package, its upstream URL or storage path, and the error. URLs are shown without credentials or query strings. | +| `http_timeout` | `PROXY_HTTP_TIMEOUT` | - | `30s` | Timeout for upstream metadata and pass-through requests. | +| `write_timeout` | `PROXY_WRITE_TIMEOUT` | - | `5m` | Response write deadline, including download and scanning time before the response starts. | +| `artifact_timeout` | `PROXY_ARTIFACT_TIMEOUT` | - | `5m` | Timeout for each upstream artifact download while serving requests; excludes subsequent scanning. Does not limit `proxy mirror`. | + +These timeouts accept Go durations such as `30s`, `5m`, or `1h`. An omitted value uses the default; `"0"` disables that timeout. Invalid or negative values are rejected at startup. Environment variables override file values. + +For long scans, increase `write_timeout` to cover the download, scan, and response transfer. `scanning.timeout` controls the scan separately; changing it alone does not extend the response deadline. `artifact_timeout` is independent of both. For example: + +```yaml +write_timeout: "18m" +artifact_timeout: "10m" +scanning: + timeout: "16m" +``` + +These are independent limits, not reserved time slices: a download approaching 10 minutes followed by a 16-minute scan would still exceed an 18-minute response deadline. Any reverse proxy in front of the server also needs sufficient timeout allowance. The upstream transport's existing response-header timeout remains unchanged. + +### Memory limit + +On Linux, when the process runs under a cgroup memory limit, such as a container's `--memory` or a Kubernetes memory limit, `proxy serve` sets Go's soft memory limit to 80% of it and log the value at startup (`set Go memory limit from cgroup`). The garbage collector then runs more often as memory use approaches the limit, rather than letting the heap grow until the container is killed. The remaining 20% is left for memory Go doesn't manage, such as `git` processes the proxy runs. Set the `GOMEMLIMIT` environment variable to choose the value yourself, or `GOMEMLIMIT=off` to disable it. ## Storage @@ -45,12 +67,20 @@ storage: |--------|-------------|------|-------------| | `storage.url` | `PROXY_STORAGE_URL` | `-storage-url` | Storage URL (file:// or s3://) | | `storage.path` | `PROXY_STORAGE_PATH` | `-storage-path` | Local path (deprecated, use url) | -| `storage.max_size` | `PROXY_STORAGE_MAX_SIZE` | - | Max cache size (e.g., "10GB") | +| `storage.max_size` | `PROXY_STORAGE_MAX_SIZE` | - | Max cache size (e.g., "10GB"). Negative or out-of-range sizes are rejected at startup | | `storage.cache_artifacts` | `PROXY_STORAGE_CACHE_ARTIFACTS` | - | Store fetched artifacts (default: true); `false` streams them from upstream | | `storage.retention.default` | `PROXY_STORAGE_RETENTION_DEFAULT` | - | Evict artifacts not served for this long (e.g. "30d"); see [Retention](#retention) | | `storage.retention.sweep_interval` | `PROXY_STORAGE_RETENTION_SWEEP_INTERVAL` | - | How often expired artifacts are looked for (default: "10m", at least "1m") | -`storage.max_size` counts cached artifacts only. An artifact replaced by a refetch stays in storage for at least an hour, or `storage.direct_serve_ttl` if longer, so requests already reading it can finish, and storage use can exceed the limit by what was replaced in that time. +`storage.max_size` counts cached artifacts and cached metadata documents (`cache_metadata`). When the total goes over the limit, the least recently served entries of either kind are evicted first; an evicted metadata document is fetched from upstream again on the next request for it. Pushed artifacts are not counted or evicted. An artifact replaced by a refetch stays in storage for at least an hour, or `storage.direct_serve_ttl` if longer, so requests already reading it can finish, and storage use can exceed the limit by what was replaced in that time. + +### Cache misses + +On a cache miss the proxy sends the artifact to the client while it stores it, so the client gets its first bytes as soon as the upstream sends them, rather than after the whole artifact is stored. Clients that give up after a while without data, such as git-lfs (30 seconds) or pacman (10 seconds), no longer time out on large artifacts. The response goes out chunked, without `Content-Length`, as with `cache_artifacts: false`; once stored, the artifact is served with its size. + +The bytes are checked against the digest the upstream declares, where it declares one, as they are sent. On a mismatch the connection is aborted before the response completes, so the client never receives a tampered artifact as a good one, and nothing is cached. The upstream is read at its own speed whatever the client's: a client more than 8 MB behind continues from the stored copy once it is stored, so a slow client doesn't hold back the download, other requests waiting for it, or `artifact_timeout`. If the client goes away, the artifact is still stored. If storing it fails, for example because the disk is full, the client still gets the whole artifact; the failure is logged at error level and counted in `proxy_artifacts_served_uncached_total`, so a cache that has stopped filling doesn't go unnoticed while every request succeeds. + +Requests for the same artifact that arrive while it is being stored wait for the stored copy, as do `HEAD` requests and requests with a `Range` header, which are answered from it with its size. With a `block`-mode scanner configured for the ecosystem, a miss is stored and scanned before anything is sent, as before (see [Artifact Scanning](#artifact-scanning)). ### Serving artifacts without storing them @@ -63,7 +93,7 @@ storage: Every download is a fresh upstream fetch, and concurrent requests for the same artifact are not combined. Artifacts with a digest known up front (OCI blobs, Swift archives, Helm charts) are verified while streaming: the response is sent chunked, and on a mismatch the connection is aborted before the response completes so the client never receives a tampered artifact as a good one. The same happens when the upstream connection fails mid-download. -`cache_artifacts: false` cannot be combined with `scanning.enabled`, `storage.direct_serve` or `mirror_api`, which all need stored artifacts, and the `mirror` command refuses to run with it. +`cache_artifacts: false` cannot be combined with `scanning.enabled`, `storage.direct_serve`, `mirror_api`, `mirror.schedules` or `mirror.refresh`, which all need stored artifacts, and the `mirror` command refuses to run with it. ### Retention @@ -83,9 +113,21 @@ storage: sweep_interval: "10m" ``` -Each cached file ages on its own, counted from the last time the proxy served it, or from when it was fetched if it has not been served since. A newer release of the same package does not shorten the life of older versions. Durations take a `d` suffix for days, and `"0"` or an empty value means never evict by age. With no retention configured, artifacts stay until `max_size` evicts them. `sweep_interval` must be at least `1m`. +Each cached file ages on its own, counted from the last time the proxy served it, or from when it was fetched if it has not been served since. The blobs of an image that `mirror.schedules` keeps current also count from the last run that found them cached, so the schedule keeps them; for `max_size` eviction such a run doesn't count as use. A newer release of the same package does not shorten the life of older versions. Durations take a `d` suffix for days, and `"0"` or an empty value means never evict by age. With no retention configured, artifacts stay until `max_size` evicts them. `sweep_interval` must be at least `1m`. -A package rule wins over an ecosystem rule, which wins over `default`. Package rules are keyed by package PURL without a version, written in one of the forms the table below lists for the ecosystem. The ecosystems and package rules can only name ecosystems that support retention in the running version; anything else, including a typo, stops the proxy at startup with an error naming the setting. `default` applies only to supported ecosystems. Support is added one ecosystem at a time, so a later release can make an existing `default` cover more ecosystems. On startup the proxy logs which ecosystems retention covers (`covered`) and which ones `default` does not reach yet (`default_not_applied`). +A package rule wins over an ecosystem rule, which wins over `default`. Package rules are keyed by package PURL without a version, written in one of the forms the table below lists for the ecosystem. The ecosystems and package rules can only name ecosystems that support retention in the running version; anything else, including a typo, stops the proxy at startup with an error naming the setting. `default` applies only to supported ecosystems, except `generic`, which requires an explicit rule. Support is added one ecosystem at a time, so a later release can make an existing `default` cover more ecosystems. On startup the proxy logs which ecosystems retention supports (`covered`) and which ones `default` does not reach (`default_not_applied`), including `generic`. + +Generic retention is opt-in because release assets may disappear upstream and cannot then be downloaded again after eviction. An existing `default` never starts evicting generic downloads. Set `ecosystems.generic: "30d"` to cover all generic artifacts, or configure only selected GitHub repositories: + +```yaml +storage: + retention: + default: "30d" # Other supported ecosystems; never generic. + packages: + "pkg:generic/jqlang%2Fjq": "30d" +``` + +The package rule covers every release and asset in that repository, but each cached file ages separately. Other generic repositories remain exempt from age-based eviction. A package rule of `"0"` also exempts that repository when `ecosystems.generic` is enabled. The independent `storage.max_size` limit still applies. | Ecosystem key | Retention supported | Package rule form | |---------------|---------------------|-------------------| @@ -96,7 +138,9 @@ A package rule wins over an ecosystem rule, which wins over `default`. Package r | `conda` | yes | `pkg:conda/conda-forge/numpy`, with the channel as the namespace; the package name's case doesn't matter. A key without a channel is refused. | | `cran` | yes | `pkg:cran/ggplot2`, the package name as published, case included (`pkg:cran/Rcpp`). A rule covers source and binary builds alike. | | `deb` | yes | `pkg:deb/curl`; case doesn't matter. A vendor namespace such as `pkg:deb/debian/curl` is accepted and dropped, so a rule covers the package from every configured archive. Debian and Ubuntu archives only keep the current version per suite, so an evicted older one can't be fetched again. | +| `freebsd` | yes | `pkg:bsd/freebsd/zsh`, the package name as published, case included (`pkg:bsd/freebsd/FreeBSD-acct`). A rule covers the package in every configured repository and ABI. Only packages under `Hashed/` are cached, and mirrors keep only the current build, so an evicted older one can't be fetched again. | | `gem` | yes | `pkg:gem/rails`, the gem name as published, case included. | +| `generic` | yes, explicit rules only | `pkg:generic/owner%2Frepo` for a GitHub Release repository such as `jqlang/jq`. The ecosystem rule covers all cached version-pinned generic downloads, including GitHub Release assets and configured `generic_artifacts`. The global `default` never applies; metadata/API responses are not artifact retention candidates. | | `golang` | yes | `pkg:golang/github.com/stretchr/testify`, the module path as in `go.mod`; case doesn't matter. A major version like `/v2` (or `.v3` on gopkg.in) is a module of its own and needs its own rule. The `!`-escaped form from proxy URLs and the module cache (`github.com/!azure/...`) is refused. | | `helm` | yes | No package rules: charts are cached per repository and digest, not under the chart name. The `helm` rule and `default` cover charts from HTTP repositories; charts pulled over OCI fall under `oci`. | | `hex` | yes | `pkg:hex/phoenix`, the package name as published. | @@ -108,7 +152,7 @@ A package rule wins over an ecosystem rule, which wins over `default`. Package r | `pub` | yes | `pkg:pub/http`, the package name as published. | | `pypi` | yes | `pkg:pypi/requests`; case and single `_`/`-` don't matter. Dots and repeated separators are kept as written, so a project like `zope.interface` can be stored as `zope.interface` and `zope-interface`; add a rule for each. | | `rpm` | yes | `pkg:rpm/curl`, the name as packaged, case included (`pkg:rpm/NetworkManager`). A vendor namespace such as `pkg:rpm/fedora/curl` is accepted and dropped. Fedora and EPEL update repositories keep only the latest build of a package, so an evicted older one may not be fetchable again. | -| `swift` | yes | `pkg:swift/apple/swift-nio`, with the registry scope as the namespace, or the stored form `pkg:generic/swift-registry/apple.swift-nio`; case doesn't matter. A source repository key like `pkg:swift/github.com/apple/swift-nio` is refused, since it doesn't name a registry identity. | +| `swift` | yes | `pkg:swift/apple/swift-nio`, with the registry scope as the namespace, or the stored form `pkg:generic/swift-registry/apple.swift-nio`; case doesn't matter. A source repository key like `pkg:swift/github.com/apple/swift-nio` is looked up through `upstream.swift`'s `/identifiers` before each sweep and applies to every identity listed for it; until every such key resolves, Swift artifacts aren't swept, so a rule that keeps a package is never skipped. | An evicted artifact is fetched again from upstream on the next request. Packages preloaded with `proxy mirror` age from the time they were mirrored, so an unused mirrored package is evicted like any other. Running `proxy mirror` again over a package that is still cached counts as a download and restarts its clock, so packages a scheduled mirror job keeps listing never age out. A registry that removes old releases (Linux distribution archives in particular) cannot serve an evicted version again, so set those ecosystems' rules with that in mind. @@ -131,6 +175,8 @@ export AWS_SECRET_ACCESS_KEY=your-secret export AWS_REGION=us-east-1 ``` +Objects up to 16 MiB are buffered in memory and sent in one request. Larger ones are uploaded in 5 MiB parts, two at a time, so a large artifact being cached holds about 30 MiB of upload buffers. Azure Blob Storage uploads use the same part size and concurrency. + ### S3-Compatible (MinIO, etc.) ```yaml @@ -155,6 +201,10 @@ database: | `database.driver` | `PROXY_DATABASE_DRIVER` | `-database-driver` | `sqlite` or `postgres` | | `database.path` | `PROXY_DATABASE_PATH` | `-database-path` | SQLite file path | +The database runs in WAL mode. Writes go through a single connection, since SQLite allows one writer at a time. Reads use a separate pool of read-only connections (one per CPU, between 2 and 8), so request lookups don't wait behind writes, stats queries or eviction scans. An in-memory database (`:memory:`) uses one connection for both. + +The SQLite database needs a local disk or a block-backed volume, even with one replica. SQLite's WAL mode doesn't work on network filesystems such as NFS ([sqlite.org/wal.html](https://www.sqlite.org/wal.html)), which shows up as stalled requests and `database disk image is malformed`. A Kubernetes `ReadWriteOnce` volume doesn't guarantee suitable storage, since its storage class can still be NFS. If only network filesystem storage is available to the proxy, use `driver: postgres`. Artifact storage can stay on NFS, on a separate volume from the SQLite database. + ### PostgreSQL ```yaml @@ -167,9 +217,25 @@ database: |--------|-------------|------|-------------| | `database.url` | `PROXY_DATABASE_URL` | `-database-url` | PostgreSQL connection URL | +### Several instances + +Several instances can serve one cache when they share a PostgreSQL database and storage. The storage can be S3 or a `file://` directory on a volume every instance mounts, such as NFS, CephFS or a Kubernetes `ReadWriteMany` volume. Each fetch writes its own file and renames it into place, and records are updated with compare-and-swap, so concurrent fetches and a crashed instance leave no partial files or records that don't match a file. SQLite only supports a single instance. + +Instances coordinate through PostgreSQL advisory locks: + +- Instances started together create the schema and run migrations one after the other. +- Eviction, reclaim, retention and the Gradle build cache sweep run on one instance at a time. An instance that finds a job running elsewhere skips that pass. +- A [scheduled mirror](#scheduled-refresh) runs on whichever instance reaches it first in each interval. + +Cache misses are fetched from upstream once across instances. The instance that fetches holds a lease on the miss in the `fetch_leases` table and renews it while it downloads. Another instance missing the same file waits until it is stored and serves the stored copy; `proxy_fetch_lease_waits_total` counts those waits. If the fetch fails, the instances waiting on it stop waiting together: each serves its stale metadata copy if it has one, and otherwise fetches itself, so a failing upstream costs every instance one attempt at the same time rather than one after another. When the fetch failed because the upstream rate limited it, the waiters without a stale copy answer 503 with the upstream's `Retry-After` instead of fetching. A lease of an instance that stopped expires after 30 seconds. Metadata is shared this way only with [`cache_metadata`](#metadata-caching) and a `metadata_ttl` above zero, since without a stored copy there is nothing to wait for. A cache hit costs no extra query; a miss costs one. + +Rate-limit holds (see `upstream_holds` under [Health Check](../README.md#health-check)) are shared through the `upstream_holds` table. When one instance gets a 429, or a 503 with `Retry-After`, it records the host and the end of the hold, and the other instances stop sending to that host too instead of each waiting for its own 429. Each instance rereads the table at most every two seconds, so another instance can still send for up to two seconds after a hold starts. A hold is also recorded with SQLite, where it then outlasts a restart. + +Each instance needs its own [`git.cache_dir`](#git-repositories). + ### Hit counts -Every cache hit updates the artifact's hit count and last-access time, which the stats pages and LRU eviction use. Rather than writing each hit as its own transaction, the proxy counts hits in memory and writes them together every `hit_flush_interval`. SQLite allows one writer at a time, and the proxy uses a single SQLite connection, so with a write per hit, concurrent downloads queue behind each other. +Every cache hit updates the artifact's hit count and last-access time, which the stats pages and LRU eviction use. Rather than writing each hit as its own transaction, the proxy counts hits in memory and writes them together every `hit_flush_interval`. SQLite allows one writer at a time, and the proxy writes through a single SQLite connection, so with a write per hit, concurrent downloads queue behind each other. ```yaml database: @@ -233,11 +299,13 @@ Each upstream used by a built-in package route can be set in YAML or JSON under | `upstream.allow_loopback` | `PROXY_UPSTREAM_ALLOW_LOOPBACK` | `false` | | `upstream.npm` | `PROXY_UPSTREAM_NPM` | `https://registry.npmjs.org` | | `upstream.npm_full_metadata` | `PROXY_UPSTREAM_NPM_FULL_METADATA` | `false` | +| `upstream.npm_change_feed` | `PROXY_UPSTREAM_NPM_CHANGE_FEED` | `false` (see [change feeds](#change-feeds)) | | `upstream.cargo` | `PROXY_UPSTREAM_CARGO` | `https://index.crates.io` | | `upstream.cargo_download` | `PROXY_UPSTREAM_CARGO_DOWNLOAD` | `https://static.crates.io/crates` | | `upstream.gem` | `PROXY_UPSTREAM_GEM` | `https://rubygems.org` | | `upstream.go` | `PROXY_UPSTREAM_GO` | `https://proxy.golang.org` | | `upstream.go_sumdbs_offline` | `PROXY_UPSTREAM_GO_SUMDBS_OFFLINE` | `false` | +| `upstream.go_vulndb` | `PROXY_UPSTREAM_GO_VULNDB` | `https://vuln.go.dev` | | `upstream.hex` | `PROXY_UPSTREAM_HEX` | `https://repo.hex.pm` | | `upstream.hex_api` | `PROXY_UPSTREAM_HEX_API` | `https://hex.pm` | | `upstream.pub` | `PROXY_UPSTREAM_PUB` | `https://pub.dev` | @@ -249,7 +317,9 @@ Each upstream used by a built-in package route can be set in YAML or JSON under | `upstream.nuget_search` | `PROXY_UPSTREAM_NUGET_SEARCH` | `https://azuresearch-usnc.nuget.org` | | `upstream.composer` | `PROXY_UPSTREAM_COMPOSER` | `https://packagist.org` | | `upstream.composer_repository` | `PROXY_UPSTREAM_COMPOSER_REPOSITORY` | `https://repo.packagist.org` | +| `upstream.composer_change_feed` | `PROXY_UPSTREAM_COMPOSER_CHANGE_FEED` | `false` (see [change feeds](#change-feeds)) | | `upstream.conan` | `PROXY_UPSTREAM_CONAN` | `https://center.conan.io` | +| `upstream.chef` | `PROXY_UPSTREAM_CHEF` | `https://supermarket.chef.io` | | `upstream.conda` | `PROXY_UPSTREAM_CONDA` | `https://conda.anaconda.org` | | `upstream.cran` | `PROXY_UPSTREAM_CRAN` | `https://cloud.r-project.org` | | `upstream.julia` | `PROXY_UPSTREAM_JULIA` | `https://pkg.julialang.org` | @@ -259,9 +329,12 @@ Each upstream used by a built-in package route can be set in YAML or JSON under | `upstream.rpm` | `PROXY_UPSTREAM_RPM` | `https://dl.fedoraproject.org/pub/fedora/linux` | | `upstream.homebrew_api` | `PROXY_UPSTREAM_HOMEBREW_API` | `https://formulae.brew.sh/api` | | `upstream.homebrew_artifact` | `PROXY_UPSTREAM_HOMEBREW_ARTIFACT` | `https://ghcr.io` | +| `upstream.apk_snapshots` | `PROXY_UPSTREAM_APK_SNAPSHOTS` | disabled; see [Alpine APK snapshots](#alpine-apk-snapshots) | Private, ULA, CGNAT, and loopback addresses are rejected by default. Add each private upstream hostname or IP address to `upstream.allow_private_hosts`. The matching environment variable accepts a comma-separated list. Loopback upstreams also require `upstream.allow_loopback: true`. That setting permits upstream requests and redirects to reach any loopback address. +Upstream requests honour `HTTP_PROXY`, `HTTPS_PROXY` and `NO_PROXY`. When a request goes through a forward proxy, these rules apply twice: to the forward proxy's own address, which therefore has to be listed in `upstream.allow_private_hosts` if it is private, and to the request's destination, which the proxy resolves before handing the request over. Link-local addresses such as `169.254.169.254` are always refused. A destination the proxy cannot resolve itself is passed to the forward proxy, since some networks only resolve public names there; the forward proxy's own policy decides what such a name may reach. + ```yaml upstream: allow_private_hosts: @@ -282,8 +355,21 @@ upstream: composer_repository: "https://upstream-proxy.example.com/composer" ``` +The proxy reads `packages.json` from `upstream.composer_repository` and keeps it in memory for the metadata TTL, or an hour when the TTL is 0, whether or not `cache_metadata` is on. A failed fetch is not retried within that time: the last good copy is used, or the entries are left out. It passes on its `security-advisories` and `filter` entries (Packagist's malware list) with URLs pointing at the proxy. An upstream that offers neither is still usable; `composer audit` then reports nothing from it. A filter `api-url` is not passed on; Composer reads filter entries from package metadata instead. + `upstream.hex_api` is used for cooldown timestamps and must expose Hex's `/api/packages/{name}` JSON endpoint. +`upstream.chef` is the Supermarket served at `/chef/`, for Berkshelf (`source "https://proxy.example.com/chef"`) and Policyfiles (`default_source :supermarket, "https://proxy.example.com/chef"`). The upstream has to serve the Supermarket API: `/universe`, `/api/v1/cookbooks/{name}`, its versions and their downloads. A private Supermarket that needs credentials takes them from `upstream.auth`, scoped to its URL. A download redirect to another host, such as the storage bucket behind Supermarket, does not receive them: + +```yaml +upstream: + chef: "https://supermarket.example.com" + auth: + "https://supermarket.example.com": + type: bearer + token: "${SUPERMARKET_TOKEN}" +``` + ### Private package routes Clients that use the proxy as their only registry can still install private packages. A package route sends every package whose name matches a pattern to a private registry, and never to the default upstream: @@ -307,11 +393,13 @@ upstream: - An npm route URL is the registry base that serves `/{package}`. Tarball URLs in its packuments must be on the same host and below the same path. - A routed package is not looked up anywhere else. If the private registry does not have it, the client gets a 404. If the registry fails or rejects the credentials, the client gets a 502. A package with the same name on the public registry is never served in its place (dependency confusion). - Metadata and artifacts of routed packages are cached under keys that include the route's URL. Entries cached from the public registry before a route was added are never served for a routed package. -- With cooldown enabled, the publish time of a routed npm version always comes from the route's metadata. Times recorded for the public package of the same name, or for a route's previous URL, are not used, and routed downloads do not record times of their own. +- With cooldown enabled, the publish time of a routed npm or Composer version always comes from the route's metadata. Times recorded for the public package of the same name, or for a route's previous URL, are not used, and routed downloads do not record times of their own. - Composer metadata of routed packages carries an empty `notification-url`, so Composer does not report their installs to the default upstream's `notify-batch` endpoint. - Use `upstream.auth` for the registry's credentials. The proxy has no authentication of its own, so every client that can reach it can download routed packages. - Search (`/composer/search.json`) and the package list (`/composer/packages/list.json`) still come from the default upstream only. -- npm audit and signing-key requests still go to `upstream.npm`. An audit request lists every package in the dependency tree, routed ones included. +- Composer security advisories and filter lists come from the default upstream. Routed package names, and those in `hosted.composer_vendors`, are removed from advisories requests before they are sent, so they only get advisories that their route's own metadata carries. +- Attestations of a routed npm version (`/npm/-/npm/v1/attestations/...`) come from the route, like its tarballs. +- npm audit, signing-key, search and ping requests still go to `upstream.npm`. An audit request lists every package in the dependency tree, routed ones included. - Routes can only be set in the configuration file, not with environment variables. Helm HTTP repositories and additional OCI registries are configured as named maps: @@ -349,6 +437,13 @@ upstream: generic: github: "https://github.com" github-api: "https://api.github.com" + # Paths each upstream may serve. Required for an upstream that + # upstream.auth has credentials for. + generic_paths: + github-api: + - "repos/*/*/releases" + - "repos/*/*/releases/**" + - "repos/*/*/tags" auth: # Optional: raise the GitHub API rate limit. Scoped to this host only, # so the token is never sent to the object store GitHub redirects to. @@ -358,6 +453,19 @@ upstream: ``` Only configured upstreams are reachable, so this is not an open HTTP proxy. +`generic_paths` limits an upstream to the paths after `/generic/{name}/` that +its patterns match; any other path answers 404. The patterns use the syntax of +`upstream.git` `repos`: `path.Match`, where `*` does not cross a `/`, and a +pattern ending in `/**` also matches every path nested below its prefix. A +path containing `%`, `?`, `#` or a backslash is refused for an upstream with +`generic_paths`. An upstream without `generic_paths` serves every path. + +When `upstream.auth` has credentials for a generic upstream, `generic_paths` +is required and the proxy refuses to start without it: everyone who can reach +the proxy can send requests with those credentials, so list only the paths +they need. For GitHub, use a fine-grained personal access token limited to +public repositories with read-only access; it raises the rate limit like any +other token but cannot read anything private, even through an allowed path. Paths shaped like `{owner}/{repo}/releases/download/{tag}/{asset}` are version-pinned GitHub release assets: they are stored in the artifact cache and served from it without revalidation, including while the upstream is @@ -407,6 +515,9 @@ while `upstream.oci` selects named registries through the `upstream/{name}/` repository prefix. For example, `oci://proxy.example.com/upstream/ghcr/owner/chart` uses the `ghcr` registry with `owner/chart` as its repository. +The OCI handler only serves pulls (`GET` and `HEAD`). Pushes, such as a +BuildKit `--cache-to type=registry` export, need a separate registry. + containerd mirror requests carry the original registry host in an `ns` query parameter (see the containerd section in the README). The proxy only looks the host up and never connects to it: `docker.io`, `index.docker.io`, @@ -475,6 +586,8 @@ with the metadata TTL and served byte-for-byte unchanged so apk signature verification keeps working; `.apk` packages use the shared artifact cache. When `upstream.apk` is empty, a single repository named `alpine` pointing at the official mirror is available; configuring any entry replaces that default. +Earlier index versions can be kept and served by date; see +[Alpine APK snapshots](#alpine-apk-snapshots). ```yaml upstream: @@ -496,6 +609,79 @@ When `upstream.arch` is empty, a single repository named `archlinux` pointing at that default. Arch Linux ARM has no default: pick a regional HTTPS mirror, not the `mirror.archlinuxarm.org` redirector. +```yaml +upstream: + + # Named FreeBSD pkg mirrors, served at /freebsd/{name}/. + freebsd: + freebsd: "https://pkg.freebsd.org" +``` + +FreeBSD pkg repositories are read-only. Requests to `/freebsd/{name}/…` are +passed to the mirror unchanged, e.g. +`/freebsd/freebsd/FreeBSD:14:amd64/quarterly/packagesite.pkg`, so ports and +pkgbase repositories and repositories built with poudriere work. Catalogues +(`meta`, `meta.conf`, `packagesite` and `data` as `.pkg`, `.txz` or `.tzst`) +are cached with the metadata TTL and served byte-for-byte unchanged, which +keeps their embedded signatures valid. Packages under `Hashed/` use the shared +artifact cache. Other package files (`.pkg`, `.txz`, `.tzst`), unhashed ones +and the bootstrap package under `Latest/`, can be rebuilt under the same name, +so they are passed through uncached after the [denylist](#version-denylist) +check on their `{name}-{version}`. Only cached artifacts are scanned, so while +a scanner covers the `freebsd` ecosystem these files are refused with +`403 Forbidden`: serve repositories built with `pkg repo --hash` (as the +official mirror is) and bootstrap pkg without the proxy. Everything else, such +as signatures and keys, is passed through uncached. When `upstream.freebsd` is empty, a single +repository named `freebsd` pointing at `https://pkg.freebsd.org` is available; +configuring any entry replaces that default. + +### Alpine APK snapshots + +```yaml +upstream: + # Keep replaced APK indexes for 90 days. + apk_snapshots: "90d" +``` + +Alpine mirrors only keep the current build of each package, so after an +upgrade `apk add curl=8.5.0-r0` fails because the index no longer lists that +build. With `upstream.apk_snapshots` set, the proxy keeps every version of an +index (and of a detached signature) it stores, and serves them under a dated +repository name: + +``` +http://localhost:8080/apk/alpine@2026-10-01/v3.22/main +``` + +`/apk/{name}@{YYYY-MM-DD}/…` returns the index that was current at the end of +that day (UTC). The kept files are the signed upstream bytes, so apk verifies +them as usual. A day before the first stored version of an index, or a day +that has not started yet, is `404`. Today's snapshot can still change until the +day ends. Packages under a snapshot path are the same as under the plain path: +they come from the artifact cache, or from upstream if not cached; a build the +upstream has dropped and the proxy never cached is `404`. A configured +repository whose name contains `@` takes precedence over a snapshot path. + +Snapshots are recorded when an index is requested through the plain path, so +they only exist for repositories clients use. A version counts from the first +time the proxy served it, which can be up to `metadata_ttl` after upstream +published it. A version is deleted once it was replaced more than the +configured duration ago; the newest version of each index is always kept. +Durations take a `d` suffix; empty or `"0"` disables snapshots. Snapshots need +`cache_metadata`. Their files live under `_snapshots/` in storage and do not +count towards `storage.max_size`. + +Turning snapshots off, or `cache_metadata` off, leaves the kept versions in +place. To remove them, first set a short duration such as `"1h"` and let the +hourly prune delete everything but the newest version of each index. + +Snapshots keep indexes, not packages. A package listed by an old snapshot can +still be evicted by `storage.max_size` or [retention](#retention), and is then +only available while upstream still has it. Retention counts from a package's +last download, so a pinned build nobody installed for longer than the `alpine` +retention is evicted even while a snapshot lists it. Use package rules with +`"0"` for builds that must stay installable. + ### Go checksum database ```yaml @@ -553,6 +739,48 @@ If `upstream.go` points at a module proxy that serves the checksum database itself, such as Athens, point the entry there instead, for example `sum.golang.org: "https://athens.example/sumdb/sum.golang.org"`. +### Go vulnerability database + +```yaml +upstream: + + # The Go vulnerability database, served at /go/vulndb. + go_vulndb: "https://vuln.go.dev" +``` + +Point govulncheck at the proxy with its `-db` flag: + +```bash +govulncheck -db https://proxy.example.com/go/vulndb ./... +``` + +The proxy passes on the files the +[database API](https://go.dev/security/vuln/database#api) defines: +`index/db.json`, `index/modules.json`, `index/vulns.json` and `ID/{id}.json`, +each also as `.json.gz`, which is what govulncheck fetches. Other paths get +404 without reaching the database. The files are stored and served +byte-for-byte: a `.json.gz` file is gzip data, not a response with +`Content-Encoding: gzip`. + +With `cache_metadata` enabled, every file follows `metadata_ttl`, entries +included, since the database updates an entry when its `modified` date +changes. A response that is not JSON (after decompressing a `.json.gz` file) +is refused and not stored. When the database cannot be reached, cached files +are served however old, with a `Warning` header. Without `cache_metadata` +the requests are forwarded and nothing is stored. + +On a network where clients cannot reach `vuln.go.dev`, only files someone +fetched through the proxy before an outage are available during it. To have +every entry cached, fetch the indexes and all entries through the proxy while +it is online, for example: + +```bash +base=https://proxy.example.com/go/vulndb +for f in db modules vulns; do curl -sfo /dev/null "$base/index/$f.json.gz"; done +curl -sf "$base/index/vulns.json" | jq -r '.[].id' | + xargs -I{} curl -sfo /dev/null "$base/ID/{}.json.gz" +``` + ### Debian archives ```yaml @@ -582,13 +810,271 @@ those names unless the shadowing is intended. This field has no environment variable, as with the other named upstream maps. `PROXY_UPSTREAM_DEBIAN` still sets `upstream.debian`. +### Git repositories + +Git servers configured under `upstream.git` are served read-only at +`/git/{name}/{repo}` over Git's smart HTTP protocol, from bare repositories +cached on local disk: + +```yaml +upstream: + git: + github: "https://github.com" + wikimedia: + url: "https://gerrit.wikimedia.org/r" + repos: ["mediawiki/core", "mediawiki/extensions/**"] # optional allowlist + +git: + cache_dir: /data/git # local disk, used by this process only + max_size: 50GB # evict least recently used repositories past this + max_repo_size: 5GB # refuse a repository that grows past this + refresh_wait: 5s # then serve the cached copy if the upstream check is slow + stale_max_age: 24h # never serve a copy not checked for this long +``` + +Clients reach the proxy through Git's `insteadOf` setting, which rewrites the +start of a URL before Git connects. After + +```bash +git config --global url."http://localhost:8080/git/github/".insteadOf https://github.com/ +``` + +`git clone https://github.com/git-pkgs/purl` fetches from +`http://localhost:8080/git/github/git-pkgs/purl`, while the clone's remote +stays `https://github.com/git-pkgs/purl`. + +In CI, the same setting can come from environment variables instead of a +config file (Git 2.31 or newer), next to the variables that point package +managers at the proxy. Each `GIT_CONFIG_KEY_n` and `GIT_CONFIG_VALUE_n` pair is +one `git config` setting, and `GIT_CONFIG_COUNT` says how many pairs there are. +This sends both upstreams from the example above through the proxy: + +```bash +export GIT_CONFIG_COUNT=2 +export GIT_CONFIG_KEY_0=url.http://localhost:8080/git/github/.insteadOf +export GIT_CONFIG_VALUE_0=https://github.com/ +export GIT_CONFIG_KEY_1=url.http://localhost:8080/git/wikimedia/.insteadOf +export GIT_CONFIG_VALUE_1=https://gerrit.wikimedia.org/r/ +``` + +Every process the job starts inherits these variables, so the rewrite also +applies when a package manager runs `git` for a Git dependency, as pip, +Bundler, Composer, SwiftPM, and Go for modules it fetches directly do. Those +fetches are cached too. npm downloads GitHub dependencies as tarballs over +HTTPS where it can, without `git`, so the rewrite does not reach them. + +`repos` patterns use `path.Match` syntax, where `*` does not cross a `/`; a +pattern ending in `/**` also matches every repository nested below its +prefix, so `mediawiki/**` matches `mediawiki/skins/Vector`. An upstream +without `repos` serves every repository on it, and a repository outside +`repos` answers 404. When `upstream.auth` has credentials for an upstream, +`repos` is required: everyone who can reach the proxy can read every +repository it serves, so list only those they may read. Per-client +permissions are not supported. `upstream.auth` matches credentials by URL, so +they are sent by every route to that host, not only `/git`. A `generic` +upstream at the same URL, such as the one the mise setup in the README uses, +checks `generic_paths` instead of `repos`, and needs them too; keep Git paths +like `{owner}/{repo}.git/info/refs` out of its patterns. + +Every request for a repository's refs checks the upstream's branches and tags, +and fetches only when they changed, so a clone right after a push sees the new +commit. Requests that arrive while a check or fetch is running share it. Only +branches and tags are cached and served; other refs, such as Gerrit's +`refs/changes/*`, are left out, and protocol v2 lets the server filter them +before sending. + +A commit a client asks for by object ID that is on no cached branch or tag, +such as a pull request head fetched by `actions/checkout`, is fetched from the +upstream when the client asks for it, and kept until a cached branch or tag +includes it or for 7 days. A commit the upstream could not provide, or could +not be reached for, is not asked for again for a minute, or for an hour when +it is larger than what `max_repo_size` leaves. This is off for upstreams that `upstream.auth` has +credentials for: GitHub serves a commit from any repository in a fork network +through any other, so a fetch by ID could reach repositories outside `repos`. +Any commit the cache holds can be fetched by ID, including one a force-push +left behind, as from the upstream. + +If the upstream fails, or its check of branches and tags takes longer than +`refresh_wait`, a repository checked successfully within `stale_max_age` is +served from the cache while the refresh continues. Once the check finds new +commits, the request waits for their fetch, so a clone right after a push gets +them; if the fetch fails or stalls, the cached copy is served. A +`stale_max_age` of `0` never serves a copy the upstream has not just +confirmed. A repository the upstream reports missing (404), refuses (401, 403) +or redirects is not served from the cache, also to requests that skip the ref +listing and go straight to `git-upload-pack`, until a later check succeeds. +Redirects are never followed, so point the upstream at a repository's current +location. A `git-upload-pack` request checks the upstream only when the last +check refused the repository or the copy was last checked more than a minute +past `stale_max_age` ago, so a clone checks once, at its ref listing. + +The proxy runs `git` 2.31 or newer, which must be installed (the Docker image includes it). +The `git` processes never reach the network themselves: their fetches go +through a loopback endpoint in the proxy that forwards them with the same +upstream client as every other request, so the address checks +(`allow_loopback`, `allow_private_hosts`), `upstream.auth` and the access log +apply, and credentials are never passed to `git`. + +`max_repo_size` defaults to 5GB, and `max_size` to no limit. `max_size` also +caps `max_repo_size`, since a repository larger than the whole cache would be +evicted as soon as no request was reading it. A clone or fetch that would +pass `max_repo_size` is stopped, and nothing of it is kept. A new repository +is then refused for an hour. When a refresh of one already cached does not +fit, it is served as it is and dropped once no request is reading it, so the +next request clones it again with only its branches and tags; if that is +still too large, it is refused for an hour. A commit fetched by ID that does +not fit is refused, and the repository kept. + +`max_size` counts fetches in progress as well as cached repositories, so the +cache stays within it however many fetches run at once. As a fetch receives +data, the least recently used repositories are evicted to make room, never +one a request is reading; those are evicted once released if the cache is +still over. When evicting every idle repository would not make room, none is +evicted for the fetch, and it is stopped and nothing of it is kept, but the +repository is not refused: a clone answers 507, and a refresh serves the +cached copy, as when the upstream fails. The count is of bytes received, so +index files and garbage collection can take the cache a little past +`max_size` until the fetch ends and the repository is measured. +A transfer that receives nothing for 10 minutes is abandoned. Git's automatic +garbage collection runs as part of fetches, and files over 8MB are kept +without delta compression, so one large file does not take a fetch's memory. + +Packs for clients are built by at most two `upload-pack` processes per CPU +the proxy may use, each with one delta-search thread and 64MB of delta +window, and further clones wait for one to finish; listing refs does not +wait. An `upload-pack` request is limited to 100MB, before and after gzip. + +Repositories are kept under `{cache_dir}/{name}-{hash of the URL}/`, so +repointing an upstream starts a fresh cache, and the old URL's directory is +removed at startup. Nothing else in `cache_dir` is touched, and the +directories of upstreams no longer configured are only logged, so remove +those yourself. The proxy locks `cache_dir` while it runs, through a +`.gitcache-lock` file in it, so a second process given the same directory, +such as another replica on a shared volume, fails to start; give each its own. + +Each repository's directory is named by its path as requested. Where +`cache_dir` ignores case in file names, as on macOS and Windows by default, +paths that differ only in case (`acme/widgets` and `acme/WIDGETS`) share one +directory and are treated as one repository. Use a case-sensitive file system +for an upstream whose repositories differ only in case. + +Git LFS objects are cached in the artifact cache, so they use the configured +storage backend and retention rather than `cache_dir`. git-lfs finds the LFS +API under the rewritten remote, at `/git/{name}/{repo}.git/info/lfs`, with no +further configuration. A batch request is passed to the upstream, which +decides which objects the repository has, and each download is pointed at +the proxy. An object the cache doesn't have is fetched from the download URL +the batch returned, which the proxy keeps in memory until shortly before it +expires, or else from one a fresh batch request returns. That URL is often +on another host than the Git server, such as GitHub's or Hugging Face's +object storage; the proxy fetches from whatever host the upstream names, +with the usual address checks, and `upstream.auth` credentials only go to +the hosts they are configured for. A download that isn't the object's size +is cut off. If the object's content is already stored under another +repository, such as a fork, it is copied from there instead of downloaded, +once the upstream has confirmed this repository has it; the copy takes its +own space. + +Large LFS objects may need longer timeouts. An object the proxy doesn't +have is sent to git-lfs as it is downloaded (see [Cache misses](#cache-misses)), +but the download must finish within `artifact_timeout` and the whole response +within `write_timeout`; both default to 5 minutes. +Download URLs are often signed; only the URL without its query is logged +and recorded with the object. An object is only cached once its content +matches its sha256 object ID. Objects are cached per repository, so one +repository's objects are never served for another. When the upstream can't +be reached or fails, a batch is answered with the objects cached for the +repository, and the others are reported as unavailable; a batch the upstream +refuses is refused. A cached object stays available after it is removed +upstream, until retention removes it or you delete it through the +[cache delete API](#cache-delete-api). + +Pushing, LFS uploads and locking, and the dumb HTTP protocol are not +supported. The settings +under `git` can also be set with `PROXY_GIT_CACHE_DIR`, `PROXY_GIT_MAX_SIZE`, +`PROXY_GIT_MAX_REPO_SIZE`, `PROXY_GIT_REFRESH_WAIT` and +`PROXY_GIT_STALE_MAX_AGE`. + +### Maven repositories + +```yaml +upstream: + + # The default repository, served at /maven/. + maven: "https://repo1.maven.org/maven2" + + # Additional Maven repositories, served at /maven/{name}/. + maven_repositories: + grails: "https://repo.grails.org/grails/restricted" +``` + +Builds often need more than one Maven repository. Each entry in +`upstream.maven_repositories` is served at `/maven/{name}/` with the upstream's +layout, e.g. `/maven/grails/org/grails/grails-core/6.0.0/grails-core-6.0.0.pom`, +and is fetched from that upstream alone: unlike the default repository, a named +one doesn't fall back to the Gradle Plugin Portal. Files are cached per +repository, so the same coordinates in two repositories never share a cache +entry. + +In every repository, a file the proxy would cache (an artifact, checksum or +signature) whose group directories contain a dot or colon +(`org.foo/bar/1.0/bar-1.0.jar`), or whose artifact contains a colon, is not in +the Maven layout and gets 404 without an upstream request. Its group would read +the same as `org/foo`'s. Other paths there, such as `maven-metadata.xml` or a +directory listing, are handled as anywhere else. + +`upstream.maven_repositories` is additive. `/maven/…` keeps serving +`upstream.maven` with unchanged cache identities. A repository name is matched +before the default repository, so it hides every group ID whose first segment +is the same name there: a repository named `tools` would take +`/maven/tools/jackson/…` away from Maven Central. At config load the proxy +refuses names of two characters or less, common top-level domains such as `com` +and `io`, and every first segment of a group ID on Maven Central, the Gradle +Plugin Portal and Google's Maven repository (about 1,200 names, such as `javax`, +`junit`, `software` or `gradle`). Names are compared case-sensitively, as paths +are, and may only use letters, digits, `.`, `_` and `-`. Other repositories can +have group IDs the list doesn't know, so pick names that can't be the start of +a group ID, such as `grails` or `company-releases`. + +A repository's files are cached under its name and a hash of its upstream URL, +so pointing a repository at a different URL stops serving what the old one +sent. + +In every Maven repository, `maven-metadata.xml` follows `metadata_ttl`, and +its `.md5`, `.sha1`, `.sha256` and `.sha512` files are computed from the +cached metadata rather than fetched, so they always match it. Other files are +cached for good, except SNAPSHOT files named with `SNAPSHOT` rather than a +build timestamp (`lib-1.0-SNAPSHOT.jar`, as JitPack and non-unique snapshot +repositories publish them), which each build replaces: those are fetched +again for every `GET`, through the denylist, cooldown, scanning and the +Plugin Portal fallback like any other file. The new copy replaces the cached +one once stored; while upstream can't be reached the cached copy is served, +and `HEAD` is answered from cache. Timestamped SNAPSHOT files +(`lib-1.0-20240101.120000-1.jar`) never change and are cached. + +This field has no environment variable, as with the other named upstream maps. +`PROXY_UPSTREAM_MAVEN` still sets `upstream.maven`. + ## Authentication Configure authentication for private upstream registries. The same authentication-aware client is used for metadata and artifact downloads, and credentials can reference environment variables using `${VAR_NAME}` syntax. -OCI registries that return a Bearer challenge from a `/v2/{repository}/…` endpoint are handled automatically. The proxy discovers the token realm from `WWW-Authenticate`, applies any configured credentials for the token URL, and reuses the scoped token until shortly before it expires. +OCI registries that return a Bearer challenge from a `/v2/{repository}/…` endpoint are handled automatically. The proxy discovers the token realm from `WWW-Authenticate`, applies any configured credentials for the token URL, and reuses the token until shortly before it expires. The token is always requested for pull access to the repository being fetched (`repository:{repository}:pull`), whatever scope the challenge names. -A token fetched with credentials configured for the token URL is only fetched for, and sent to, a registry that is trusted with it: one with configured credentials of its own, or one on the same site (registrable domain) as the token service, as `registry-1.docker.io` is with `auth.docker.io`. Any other host that answers with a challenge naming that token service gets its 401 back, so it cannot obtain a token minted from your credentials. Tokens from a token service with no configured credentials are anonymous and are fetched for any registry, as before. If your registry and its token service are on different sites, configure credentials for the registry URL as well. +A token fetched with credentials configured for the token URL is only fetched for, and sent to, a registry that is trusted with it: one on the same host and port as the token service, one configured with the same credentials as the token URL, or Docker Hub (`registry-1.docker.io` and `index.docker.io` with `auth.docker.io`) and GitLab.com (`registry.gitlab.com` with `gitlab.com`). Sharing a parent domain is not enough, so `team-a.jfrog.io` is not trusted with tokens from `team-b.jfrog.io`. Any other host that answers with a challenge naming that token service gets its 401 back, so it cannot obtain a token minted from your credentials. Tokens from a token service with no configured credentials are anonymous and are fetched for any registry, as before. If your registry and its token service are on different hosts, such as a self-hosted GitLab with its registry on its own hostname, configure the same credentials for both URLs: + +```yaml +upstream: + auth: + "https://registry.gitlab.example.com": + type: basic + username: "deploy-token" + password: "${GITLAB_DEPLOY_TOKEN}" + "https://gitlab.example.com/jwt/auth": + type: basic + username: "deploy-token" + password: "${GITLAB_DEPLOY_TOKEN}" +``` ### Bearer Token @@ -674,7 +1160,7 @@ The `/gradle` endpoint supports optional safeguards for upload control and cache ```yaml gradle: build_cache: - read_only: false + read_only: true max_upload_size: "100MB" max_age: "168h" max_size: "20GB" @@ -683,14 +1169,47 @@ gradle: | Config | Environment | Description | |--------|-------------|-------------| -| `gradle.build_cache.read_only` | `PROXY_GRADLE_BUILD_CACHE_READ_ONLY` | Disable PUT uploads and keep GET/HEAD read-only | +| `gradle.build_cache.read_only` | `PROXY_GRADLE_BUILD_CACHE_READ_ONLY` | Reject PUT uploads and serve GET/HEAD only (default `true`; the variable takes `true`/`false` or `1`/`0`, any other value keeps uploads off and logs a warning) | | `gradle.build_cache.max_upload_size` | `PROXY_GRADLE_BUILD_CACHE_MAX_UPLOAD_SIZE` | Maximum accepted PUT body size (must be > 0) | | `gradle.build_cache.max_age` | `PROXY_GRADLE_BUILD_CACHE_MAX_AGE` | Delete entries older than this duration (default `168h`, also accepts days such as `7d`; set `0` to disable) | | `gradle.build_cache.max_size` | `PROXY_GRADLE_BUILD_CACHE_MAX_SIZE` | Total size cap for `_gradle/http-build-cache`, deleting oldest first (`0` disables) | | `gradle.build_cache.sweep_interval` | `PROXY_GRADLE_BUILD_CACHE_SWEEP_INTERVAL` | Frequency for background eviction sweeps | +Uploads are off by default, so a client that can reach the proxy cannot overwrite cache entries that end up in other people's builds. Set `read_only: false` (or `PROXY_GRADLE_BUILD_CACHE_READ_ONLY=false`) on the instance your CI jobs upload to, and let only CI push (`isPush = System.getenv("CI") != null`). Before this default changed, uploads were accepted without configuration; setups that upload need the setting now. + `max_age` and `max_size` are independent and can be combined. When both are set, age-based eviction runs first, then size-based eviction trims remaining entries oldest-first. +## Cooldown profiles + +Set `cooldown.profiles` to offer several policies from one instance. Clients select a profile through their package manager's registry URL: + +```yaml +cooldown: + default: "0" + profiles: + 3d: + default: "3d" + 7d: + default: "7d" + packages: + "pkg:npm/@example/tool": "0" +``` + +For the `3d` profile, use these paths after your proxy's base URL: + +| Client | Path | +|--------|------| +| npm registry | `/cooldown/3d/npm/` | +| Go `GOPROXY` | `/cooldown/3d/go` | +| Cargo registry | `sparse+https://your-proxy.example/cooldown/3d/cargo/` | +| Bundler RubyGems mirror | `/cooldown/3d/gem` | + +The prefix works with all package protocol routes. Cooldown has an effect only for [registries with cooldown support](../README.md#supported-registries). Each profile defines its own `default`, `ecosystems`, `packages` and `package_patterns`; it does not inherit the global cooldown overrides. Existing unprefixed URLs, the UI, APIs and background mirror jobs use the global policy. + +Profile names contain lowercase letters, digits, hyphens and underscores, and start with a letter or digit. Profiles must be configured before startup; an unknown profile returns 404. Nested profiles are rejected. Profile paths expose package protocols only, so `/cooldown/3d/ui/` and `/cooldown/3d/api/` return 404. + +Database records, artifacts and upstream metadata are shared. Generated download URLs retain the profile prefix, and filtered metadata and its validators are separated by profile. Because npm packuments are shared too, cooldown in the global policy or in any profile makes every URL fetch and serve full packuments, as `upstream.npm_full_metadata` does. Changing a registry URL does not rewrite artifact URLs already recorded in a lockfile; regenerate those URLs if the selected policy must cover the whole installation. + ## Cooldown The cooldown feature hides package versions published too recently, giving the community time to spot malicious releases before they reach your projects. When a version is within its cooldown period, it's stripped from metadata responses so package managers won't install it. @@ -719,15 +1238,46 @@ Durations support days (`7d`), hours (`48h`), and minutes (`30m`). Set to `0` to Package PURL keys are normalized to canonical form before matching, so `pkg:npm/@babel/core` and `pkg:npm/%40babel/core` are equivalent, as are `pkg:pypi/Django` and `pkg:pypi/django`. If both forms configure the same package, the canonical entry wins. +Go module names in exact cooldown overrides are matched case-insensitively. If both lowercase and mixed-case keys are configured, the lowercase entry wins. Go package patterns match lowercase module names. + `package_patterns` matches canonical, versionless PURLs using `*` for zero or more characters and `?` for one character. Neither wildcard crosses `/` separators. Character classes (`[...]`) and backslash escapes are rejected at startup. For example, `"pkg:npm/@example/*"` matches packages under the `@example` npm scope. Patterns accept `@` as an alias for `%40`; other characters must use their canonical PURL form. Equivalent patterns with different durations are rejected at startup. Equal durations, such as `1d` and `24h`, are accepted. Exact `packages` entries take precedence over patterns. When several patterns match, longer patterns win after excluding `*` and `?` from the length. Ties use lexical order of the normalized patterns. Resolution order: exact package override, then package pattern, then ecosystem override, then global default. This lets you set a conservative default while exempting trusted package families. -Currently supported for npm, PyPI, pub.dev, Composer, Cargo, NuGet, Conda, RubyGems, and Hex. These ecosystems include publish timestamps in their metadata. +The web UI's dashboard shows the default and the ecosystem overrides, and how many package overrides and patterns there are; their names aren't shown, since the UI has no authentication. A package's page shows the cooldown that applies to it and which kind of rule it comes from; it shows none for ecosystems without cooldown support, and the dashboard marks an ecosystem override for one as not supported. The version list marks versions held back with when they become available, and leaves out versions the proxy only saw in metadata once they're out of cooldown. `/api/package/{ecosystem}/{name}` returns the package's `cooldown` in the configuration's syntax, and a held-back version has `available_at`. -Note: Hex cooldown requires disabling registry signature verification since the proxy re-encodes the protobuf payload without the original signature. Set `HEX_NO_VERIFY_REPO_ORIGIN=1` or configure your repo with `no_verify: true`. +Currently supported for npm, PyPI, pub.dev, Composer, Cargo, NuGet, Conda, RubyGems, Hex, Go, Maven and Helm. Most of these ecosystems include publish timestamps in their metadata; Go and Maven are described below. + +Go has no publish time. The module proxy's `.info` gives the commit time of the revision a version points at, so a version tagged on an old commit counts as old. The proxy reads each listed version's `.info` once, stores the time, and leaves versions in cooldown out of `@v/list` and `@latest`. When upstream's `@latest` is in cooldown, it serves the newest release out of cooldown instead. Requests for a version in cooldown, including its `.info`, `.mod` and `.zip`, and a branch or commit query that resolves to one, get 403 rather than 404, because the go command moves on to the next `GOPROXY` entry, such as `direct`, after a 404. If a version's `.info` can't be fetched, the list or download fails with 502 instead of letting the version through. + +Maven metadata has no publish time per version. The proxy uses the `Last-Modified` header of each version's `.pom`, which on Maven Central is the time the version was deployed. It reads the header once per version and stores the time, for each repository under `upstream.maven_repositories` separately: from the response when the `.pom` or Gradle `.module` itself is downloaded, which clients do before a version's other files, and otherwise with a `HEAD` request. A `.pom` or `.module` refused this way is still cached, so it counts toward `max_size` before the version leaves cooldown. To keep requests to the upstream down, it only checks versions that can still be in cooldown: none when the metadata's `` is older than the cooldown, and otherwise the versions from the end of the list back to the first one that is old enough. Versions in cooldown are left out of `maven-metadata.xml`, `` and `` are set to the last versions left, and the metadata's `.md5`, `.sha1`, `.sha256` and `.sha512` files are computed from what is served, as they are without cooldown. Requests for any file of a version in cooldown get 403, as for a version on the denylist. If a `.pom` can't be checked, the metadata or download fails with 502 instead of letting the version through, or with 503 and `Retry-After` when the upstream rate-limits the proxy; a version without a `.pom` is let through. + +Maven caveats: + +- A Nexus or Artifactory upstream may report when it cached the `.pom` rather than when it was published, so a version can stay in cooldown longer than it should. +- On Google's Maven Central mirror, `Last-Modified` is when the file reached the mirror's bucket, a few hours after it was published, so versions stay in cooldown a little longer. The upload time is in `x-goog-meta-last-modified`, which the proxy does not read. It is missing for files from the mirror's 2019 bulk import. +- Maven Central lists versions in version order, not in the order they were published. A patch to an older release line published after a newer release that is out of cooldown stays listed while it is in cooldown, but its files are still refused. +- SNAPSHOT versions are not held back. + +Helm uses each release's `created` time from the repository's `index.yaml`. Releases in cooldown are left out of the index the proxy serves, and their archives aren't served; a release without `created` is let through. Charts pulled over OCI have no publish time and aren't held back. + +Cargo, RubyGems, Hex, pub.dev, Conda and Helm check artifact downloads against cooldown, including files cached before the policy changed. When a publish-time lookup fails, an already-cached file is still served; an uncached download fails with 502, or 503 with `Retry-After` when the rate-limit gate holds the request. Conda checks timestamps per file because builds of one version can have different publish times. As in conda, a repodata `timestamp` is read as milliseconds when it is above 253402300799 (the end of year 9999 in seconds) and as seconds otherwise, since some older entries use seconds. + +Conda repodata and Helm indexes are parsed once per cached document for download checks. With `cache_metadata` off, the parsed index is kept for one minute, including the fetch, so an install can reuse it across files. Conda streams repodata when its compressed copy exceeds `metadata_max_size`, under the same decompressed size bound as the metadata filter. + +RubyGems, Hex and PyPI keep their publish times outside the metadata clients read: the RubyGems versions API, the Hex HTTP API (`upstream.hex_api`) and the PyPI JSON API. The proxy fetches them alongside each compact index, package or simple page it filters, and for PyPI downloads. Cooldown fails closed: when it applies to a package and those times can't be fetched or parsed, or the metadata can't be rewritten, the request fails with 502, or with 503 and `Retry-After` while the upstream is rate limiting the proxy, instead of serving the metadata unfiltered. The same goes for npm, Composer and pub.dev metadata that can't be rewritten, and for npm tarball downloads whose publish time can't be read. A PyPI file or npm tarball that is already cached is still served when its publish time can't be read; only a download that would have to be fetched fails. A PyPI release's time is the upload time of its newest file. The proxy stores it when a download looks it up, and serves files of that release that are already cached against the stored time without reading the JSON API again. A file that isn't cached yet is always looked up, since it may have been added to the release since, and the newer time is stored. Packages exempted with a duration of `0` are served as before and don't need the times. A PyPI package the JSON API returns 404 for has no times to go by and is served unfiltered. + +For RubyGems and Hex, both documents go through the metadata cache. With [`cache_metadata`](#metadata-caching) they are served from it within `metadata_ttl` without asking the upstream, revalidated with their ETags after it, and filtered from the last cached copies, marked stale, while the upstream is down; without it they are still fetched once for concurrent requests. Each document has its own TTL, so the compact index or Hex package can be newer than the cached times and list a version they don't have. The times are then fetched again before filtering, and if that fails, such versions are left out until the times can be read. The filtered index or package carries an ETag of its own, so Bundler and Mix revalidate it with `304 Not Modified`. Publish times are compared with the current time on each request, and the filtered result is kept until the first version it held back leaves cooldown (see [rewritten metadata cache](#rewritten-metadata-cache)); a newly published version shows up within `metadata_ttl`, as with other cached metadata. Upstream errors are answered as for other cached metadata (404, or 502) rather than relayed. + +With cooldown on, the proxy asks npm for full packuments, since the abbreviated ones it uses otherwise carry no publish times. Abbreviated packuments cached before cooldown was turned on are fetched again in full rather than served, including as a stale copy when the upstream is down. When `latest` is in cooldown, the packument tags the newest version out of cooldown instead; other tags that name a version in cooldown are removed, as for the denylist, and `npm dist-tag ls` shows the same tags. A tarball request for a version the cached packument doesn't list yet fetches the packument again, within `metadata_ttl` or not, and is decided on what the upstream lists now; if the packument can't be fetched, the download is not let through, as when a publish time can't be read. + +In pub.dev package metadata, when `latest` is in cooldown it names the newest stable version out of cooldown instead, or the newest prerelease when no stable version is left, and it is left out when every version is in cooldown. + +Conda cooldown covers `repodata.json`, `current_repodata.json`, `repodata_from_packages.json` and sharded repodata (CEP 16). Other forms of the repodata, such as `repodata.json.zst`, `repodata.json.bz2` and `repodata.jlap` patches, would list versions still in cooldown, so with cooldown on they are answered 404 and conda and mamba fall back to `repodata.json`. With `cache_metadata`, `repodata.json` is read through the metadata cache as it is without cooldown: within `metadata_ttl` the stored copy is filtered as it is read from storage, after it the upstream is asked with its ETag, and while the upstream is down the stale copy is filtered. Once a document has been filtered, the proxy remembers the ETag of the result until the first entry it left out leaves cooldown, so a client revalidating with `If-None-Match` gets `304 Not Modified` without the document being filtered or sent again. The first response for each document has no ETag, as it is sent while it is filtered. Without `cache_metadata`, `repodata.json` is fetched and filtered on every request. Clients cache shards by the hash in the shard index, so with cooldown on the proxy serves a rewritten index whose shard hashes change every hour and filters each shard as it is fetched. Versions leaving cooldown show up within the hour, and clients fetch the shards they need again once an hour. If a channel's shard index points packages or shards somewhere the proxy doesn't route, the proxy answers 404 for it and clients fall back to `repodata.json`. + +Hex cooldown requires `HEX_UNSAFE_REGISTRY=1` because filtering releases re-encodes the protobuf payload without the original signature. The proxy preserves the package name and repository fields, so origin verification can stay enabled. `HEX_NO_VERIFY_REPO_ORIGIN` controls origin verification and does not disable signature verification. Without a cooldown, leave signature verification enabled too. ## Version denylist @@ -741,13 +1291,52 @@ denylist: - "pkg:npm/%40scope/example@4.5.6" ``` -Entries must be versioned PURLs without qualifiers or subpaths. Package names -are canonicalized (including PyPI case/separator normalization and npm scopes); +Entries must be versioned PURLs without subpaths or qualifiers (except a conda +`channel`, below). Package names are canonicalized (including npm scopes); versions match exactly, not by range or glob. Invalid entries prevent startup. An empty list disables the policy. Restart the proxy after changing the list. +Names and versions are compared the way each ecosystem treats them: + +- PyPI names ignore case, and runs of `-`, `_` and `.` are equivalent (PEP 503), + so `pkg:pypi/zope.interface@6.0` also covers `zope_interface-6.0-*.whl`. +- NuGet ids and versions ignore case. +- Debian, RPM, Alpine, Arch and FreeBSD entries ignore the distribution + namespace: `pkg:deb/debian/curl@8.5.0-2` and `pkg:deb/curl@8.5.0-2` are the + same entry. +- Debian and RPM filenames leave out the epoch, so an entry with one also + covers the version without it: `pkg:deb/foo@1:2.3-1` denies + `foo_2.3-1_amd64.deb`. An entry without an epoch only matches a version + without one. +- A RubyGems entry also covers that version's platform gems: + `pkg:gem/nokogiri@1.16.0` denies `nokogiri-1.16.0-x86_64-linux.gem`. +- Composer versions ignore a leading `v`, which Packagist keeps from the tag: + `pkg:composer/symfony/console@6.1.7` also covers `v6.1.7`. +- Go versions are matched as written, `pkg:golang/example.com/mod@v1.0.0-RC1`, + though download URLs escape uppercase letters (`v1.0.0-!r!c1`). + Go module names in denylist entries are matched case-insensitively. +- A Swift entry names the registry scope and package, ignoring case: + `pkg:swift/apple/swift-nio@2.62.0`. The stored form, + `pkg:generic/swift-registry/apple.swift-nio@2.62.0`, works too, and so does + the source repository, as SBOM tools and GHSA advisories write it: + `pkg:swift/github.com/apple/swift-nio@2.62.0`. The proxy looks a source + repository up through `upstream.swift`'s `/identifiers` when `serve` or + `proxy mirror` starts and denies every identity listed for it; neither runs + when one can't be resolved. +- An OCI entry names the repository as it is pulled through the proxy and a + digest or tag: `pkg:oci/library/alpine@sha256:` refuses the blob or + manifest with that digest, including a manifest a tag resolves to, and + `pkg:oci/library/alpine@3.19` refuses pulling that tag. Repositories on a + named upstream keep their prefix, as in `pkg:oci/upstream/ghcr/org/image@...`. + An entry covers only the digest it names: denying an image index does not + deny the platform manifests and layers it lists to a client that requests + them by digest directly. +- A conda entry covers the package in every channel. Add a `channel` qualifier, + such as `pkg:conda/numpy@1.26.4?channel=conda-forge`, to deny it in one + channel only. + Denied versions are removed from npm packuments, Cargo sparse indexes, and PyPI -simple HTML/JSON and release metadata, including responses served from cached +simple HTML/JSON (files and the JSON `versions` list) and release metadata, including responses served from cached metadata during an upstream outage. No publication timestamp or enabled cooldown is required. npm tags pointing at denied versions are removed; `latest` is moved to the highest remaining stable version when available. Other tags are not @@ -849,17 +1438,19 @@ scanning: | `scanning.scanners[].name` | - | Identifies this scanner in logs and metrics | | `scanning.scanners[].url` | - | Endpoint the proxy POSTs scan notifications to | | `scanning.scanners[].mode` | - | `block` (default) or `monitor` | -| `scanning.scanners[].ecosystems` | - | Restricts this scanner to specific ecosystems (e.g. `npm`, `pypi`). Empty means all ecosystems | +| `scanning.scanners[].ecosystems` | - | Restricts this scanner to specific ecosystems (e.g. `npm`, `pypi`). Empty means all ecosystems. Valid names: `alpine`, `arch`, `cargo`, `chef`, `composer`, `conan`, `conda`, `cran`, `deb`, `freebsd`, `gem`, `generic`, `git` (Git LFS objects), `golang`, `helm`, `hex`, `julia`, `maven`, `npm`, `nuget`, `oci`, `pub`, `pypi`, `rpm`, `swift`. The aliases `go`, `docker`, `rubygems`, `packagist`, `debian` and `apk` are accepted too; any other name stops the proxy at startup | | `scanning.scanners[].headers` | - | Extra HTTP headers sent with every scan request (e.g. for authenticating to the scanner service). Values support `${VAR_NAME}` expansion | ### How caching defers to a scan verdict -The proxy never uploads artifact bytes to a scanner. When an artifact is fetched from upstream, it's stored to the configured storage backend first, exactly as without scanning. If scanning is enabled for the artifact's ecosystem, the proxy then notifies each applicable scanner with package metadata and a short-lived, HMAC-signed URL pointing at the internal `/_internal/scan-fetch` route; each scanner GETs that URL itself to pull the exact bytes staged in storage and runs its own scan against them. +The proxy never uploads artifact bytes to a scanner. When an artifact is fetched from upstream, it's stored to the configured storage backend first, exactly as without scanning. If scanning is enabled for the artifact's ecosystem, the proxy then notifies each applicable scanner with package metadata and a short-lived, HMAC-signed URL pointing at the internal `/_internal/scan-fetch` route; each scanner GETs that URL itself to pull the exact bytes staged in storage and runs its own scan against them. With a `block`-mode scanner for the ecosystem, the client gets nothing before the verdict; with only `monitor`-mode scanners, a cache miss is sent to the client while it is stored, and the scan runs after (see [Cache misses](#cache-misses)). Scanners configured for the same ecosystem all run concurrently, never sequentially. The moment any `block`-mode scanner reports a not-allowed verdict (or errors, unless `fail_open` is set), the proxy cancels the in-flight calls to the other scanners and deletes the staged artifact — it's never committed to the cache database, so it was never visible to a client. If nothing blocks, the proxy waits for every `block`-mode scanner to finish before caching the artifact and serving it. A `monitor`-mode scanner's findings are logged and never gate the wait or the caching decision, even when it reports not-allowed. A blocked download surfaces to the client as `403 Forbidden` with the scanner's reason, across every ecosystem handler. +Because scanners pull the staged bytes from the running server, the `proxy mirror` command cannot scan what it fetches. While scanning is enabled it refuses every package and container image instead of caching them unscanned. Mirror through the `/api/mirror` endpoints of the running server, whose jobs are scanned like any other download. + ### Scanner HTTP contract Any external service that implements this contract can act as a scanner — a trivy wrapper, a clamav-rest bridge, a Wiz connector, or an in-house service. The proxy POSTs a notify request to `scanning.scanners[].url` and waits for a JSON verdict. @@ -920,12 +1511,20 @@ By default the proxy fetches metadata fresh from upstream on every request. Enab OCI manifests and tag lists are always cached because cached image blobs cannot be pulled without their manifests and offline clients may need tag resolution. Digest-addressed manifests are immutable and served directly from cache. Tag-addressed manifests and tag lists follow `metadata_ttl`, revalidate when stale, and fall back to the last cached response when the registry is unavailable. +A stale tag is revalidated with a HEAD request carrying the client's `Accept` header, and the `Docker-Content-Digest` it returns is compared with the cached one. If the tag did not move, or moved to a manifest already cached by digest, nothing else is fetched. Otherwise the new manifest is fetched once by digest and stored under the tag and the digest. Docker Hub counts manifest GETs, but not HEADs, against its pull rate limit, so an unchanged tag costs no pulls however often its TTL runs out. A registry whose HEAD response has no digest gets a conditional GET for the tag instead. A client's HEAD request for a stale or uncached tag is passed on as a HEAD; when the digest it returns is cached, the tag is pointed at it, so the GET that follows is served from cache. Concurrent requests for the same manifest share one upstream request, and instances sharing a Postgres database take turns through the same [fetch lease](#several-instances) as other metadata. + ```yaml cache_metadata: true ``` Or via environment variable: `PROXY_CACHE_METADATA=true`. +Some metadata never changes once published, and is cached like an artifact, with or without `cache_metadata`, and served without revalidation whatever `metadata_ttl` says: a Go module's `.mod` and `.info` for a canonical version (a release, pre-release, pseudo-version or `+incompatible` version; the checksum database fixes their content), and RPM repodata files named after their own checksum (`repodata/-primary.xml.gz`). A stored copy is checked against the digest recorded for it and fetched again if it doesn't match. Go branch and commit queries, `@v/list` and `@latest`, and RPM `repomd.xml` follow `metadata_ttl` as before; plainly named repodata files follow the cached `repomd.xml` (see [Metadata TTL](#metadata-ttl)). A checksum-named repodata file over `metadata_max_size` is streamed from upstream uncached. + +Composer archive downloads look up their upstream URL in the same cached metadata, so an archive is resolved without asking Packagist again and stays installable while it is down. Only a version or file the cached metadata does not list yet is looked up upstream. With or without `cache_metadata`, a cached archive of a tagged release from the default repository is served without any metadata lookup; with cooldown enabled it is checked against the publish time recorded when the archive was first resolved. Branch (dev) versions, routed packages and archives picked by a query string such as `?sha=` are always resolved from the metadata. + +Swift release lists and manifests are cached with the upstream's `Link` header, which carries the release list's pages and the version-specific manifests a client chooses from. + The `proxy mirror` command always enables metadata caching regardless of this setting. ### Metadata TTL @@ -940,17 +1539,40 @@ Or via environment variable: `PROXY_METADATA_TTL=10m`. Set to `"0"` to always revalidate with upstream (ETag-based conditional requests still avoid re-downloading unchanged content). -When upstream is unreachable and the cached entry is past its TTL, the proxy serves the stale cached copy with a `Warning: 110 - "Response is Stale"` header so clients can tell the data may be outdated. +When upstream is unreachable and the cached entry is past its TTL (with a `metadata_ttl` of `"0"`, on every such request), the proxy serves the stale cached copy with a `Warning: 110 - "Response is Stale"` header so clients can tell the data may be outdated. The `ETag` and `Last-Modified` sent with a document are always those of the bytes served, so a document fetched from upstream but not stored, for example because storage failed, carries the upstream's validators rather than the older cached copy's. + +APT and RPM clients fetch a release file first (`InRelease` or `Release`, `repomd.xml`) and reject an index file whose checksum doesn't match it. So an index file the cached release file lists (`Packages`, `Sources`, a plainly named `primary.xml.gz`, …) does not follow its own `metadata_ttl`: its cached copy is served while it matches the cached release file's sha256, however old, and otherwise it is fetched from upstream. If upstream's copy doesn't match either, the repository has changed since the release file was cached; that copy is served and the release file is expired, so the next `apt update` or `dnf makecache` gets a matching pair. Where a suite has both `InRelease` and `Release` cached, the one fetched last decides. The release file itself follows `metadata_ttl`. Index files it doesn't list, such as `by-hash` paths, follow `metadata_ttl` too. + +### Change feeds + +Within `metadata_ttl` a new release isn't seen. For npm and Composer the proxy can instead follow the registry's change feed, which lists the packages that changed, and revalidate just those: + +```yaml +cache_metadata: true +upstream: + npm_change_feed: true + composer_change_feed: true +``` + +Or via environment variables: `PROXY_UPSTREAM_NPM_CHANGE_FEED=true`, `PROXY_UPSTREAM_COMPOSER_CHANGE_FEED=true`. Both require `cache_metadata`, and do nothing with a `metadata_ttl` of `"0"`. + +Every minute the proxy reads what changed since its last read. Cached metadata of a listed package that was fetched before the read is marked as needing revalidation, and the next request for it asks the upstream with its `ETag` (a `304` when nothing changed). Artifacts are not touched. Listed packages the proxy hasn't cached cost nothing beyond the read. The feed is read in full, so the upstream doesn't learn which packages the proxy has cached. Packages in `upstream.npm_routes` or `upstream.composer_routes` are cached under other keys and never matched. + +- Composer reads `{upstream.composer}/metadata/changes.json`, which packagist.org advertises as `metadata-changes-url`. Both `vendor/package` and its `vendor/package~dev` file are covered. Packagist keeps 24 hours of changes; if the proxy's position is older than that, Packagist asks for a resync and all cached Composer metadata is revalidated. repo.packagist.org sends `Cache-Control: max-age=900`, but Packagist purges its CDN when a package changes, so revalidation gets the new file within seconds; the proxy doesn't apply that header either way. +- npm reads `https://replicate.npmjs.com/registry/_changes`, the public registry's feed, whatever `upstream.npm` is. It is only useful when `upstream.npm` is registry.npmjs.org or serves the same packages. Packuments (`/npm/{name}`) are covered; version and dist-tag documents (`/npm/{name}/latest`) still wait out `metadata_ttl`. A busy minute on npm lists a few thousand packages; the proxy reads up to 100,000 per pass and continues where it stopped on the next. + +A new release therefore shows up about a minute after the registry lists it rather than up to `metadata_ttl` later. The feed position is kept in memory: after a restart the proxy starts from the feed's current position, and changes made while it was down are covered by `metadata_ttl` as before. While a feed can't be read the proxy logs a warning and retries with a growing delay, up to 15 minutes, and `metadata_ttl` applies meanwhile. A request whose upstream fetch overlaps the change and the feed read can still store the old document for one TTL. Each instance sharing a database reads the feeds itself. `proxy_metadata_expired_by_change_feed_total` counts the cached documents marked, by ecosystem, and debug logging names each one. ### Metadata size limit -Upstream metadata responses are buffered in memory before being rewritten and served. `metadata_max_size` caps that buffer to protect against OOM from a misbehaving upstream. Some npm packages with thousands of versions (for example `renovate`) exceed the 100 MB default, so raise this if you see `metadata response exceeds size limit` in the logs. +Upstream metadata responses are buffered in memory before being rewritten and served. `metadata_max_size` caps that buffer to protect against OOM from a misbehaving upstream. Some npm packages with thousands of versions (for example `renovate`) exceed the 100 MB default, so raise this if you see `metadata response exceeds size limit` in the logs. Conda `repodata.json` with cooldown enabled is filtered as it streams and isn't held in memory decompressed. With `cache_metadata` the limit applies to the compressed document as it does without cooldown; one over it is filtered as it streams from the upstream and not cached. With `cache_metadata` and the metadata rewrite cache on, an npm packument is streamed from the upstream into storage and rewritten from there in two passes, so it isn't held in memory and the limit doesn't apply to it; the rewritten copy is kept gzip-compressed. Requests for a single version (`//`) and tarball downloads read the version from the stored copy the same way. `metadata_stream_max_size` (1 GB by default) caps a document streamed this way; one over it isn't stored, and the stored copy, if any, is served instead. ```yaml -metadata_max_size: "100MB" # default +metadata_max_size: "100MB" # default +metadata_stream_max_size: "1GB" # default ``` -Or via environment variable: `PROXY_METADATA_MAX_SIZE=250MB`. +Or via environment variable: `PROXY_METADATA_MAX_SIZE=250MB`, and `PROXY_METADATA_STREAM_MAX_SIZE=2GB` for `metadata_stream_max_size`. ### Artifact size limit @@ -964,9 +1586,11 @@ Or via environment variable: `PROXY_ARTIFACT_MAX_SIZE=2GB`. ### Rewritten metadata cache -The npm and Composer handlers rewrite every metadata document they serve, so that download URLs point at the proxy. That means decoding the whole document and encoding it again, and Composer's minified documents are also expanded, which together cost milliseconds per typical package and far more for very large ones. The proxy keeps rewritten documents in memory, so each distinct upstream document is rewritten once and requests arriving while it is being rewritten wait for that rewrite. New bytes from upstream are rewritten again. With version cooldown enabled the cache is bypassed, because cooldown filtering depends on the current time. +The npm, Composer, PyPI and Helm handlers rewrite every metadata document they serve, so that download URLs point at the proxy. That means decoding the whole document and encoding it again, and Composer's minified documents are also expanded, which together cost milliseconds per typical package and far more for very large ones; a large Helm `index.yaml` takes over a hundred milliseconds. The proxy keeps rewritten documents in memory, so each distinct upstream document is rewritten once and requests arriving while it is being rewritten wait for that rewrite. New bytes from upstream are rewritten again. A PyPI simple page is cached per representation (HTML or JSON) and per set of versions filtered out of it. With version cooldown enabled, a cached rewrite expires when the first version it held back leaves cooldown, since versions it let through stay allowed and a new upstream version changes the document. A rewrite that held nothing back is kept for the shortest cooldown configured, at least a minute and at most a day. Cached documents carry an `ETag` of their own, and are dated like any other, so clients that revalidate with `If-None-Match` or `If-Modified-Since`, such as Composer, get `304 Not Modified`. The RubyGems compact index and Hex packages filtered by cooldown are kept the same way; they are never served gzip-compressed. -Each cached document is also kept gzip-compressed, when that makes it smaller, and served with `Content-Encoding: gzip` to clients that accept it. A large packument is compressed once rather than on every request, by the proxy or by a reverse proxy in front of it. The compressed copy counts against the cache size and typically adds about an eighth to each entry. Documents rewritten outside the cache are served uncompressed. +Each cached document is kept gzip-compressed, when that makes it smaller, and served with `Content-Encoding: gzip` to clients that accept it, as npm, pnpm, Yarn and Composer do. A large packument is compressed once rather than on every request, by the proxy or by a reverse proxy in front of it. Only the compressed copy is kept, typically an eighth of the document, and it is decompressed for the clients that don't accept gzip. Documents rewritten outside the cache are served uncompressed. + +Size the cache for the metadata of the packages one install asks for. pnpm 12 checks every lockfile entry against the registry on each install unless `trustLockfile` is set, so each install reads the packument of every package in the lockfile; when they don't all fit, each install evicts what the next one needs and rewrites them all again. A lockfile of about 550 npm packages takes about 50 MB. ```yaml metadata_rewrite_cache_size: "256MB" # default; "0" rewrites on every request @@ -988,7 +1612,7 @@ Set to `"0"` to disable the timeout entirely (requests then rely only on the ser ## Hosted Packages -Operators can push a package archive into the proxy under a name and version. The proxy serves it in place of the upstream archive with the same version, or in addition to the upstream's versions. Use it to ship a patched build of a dependency without running a separate registry. +Operators can push a package archive into the proxy under a name and version. The proxy serves it in place of the upstream archive with the same version, or in addition to the upstream's versions. Use it to ship a patched build of a dependency without running a separate registry. Files that aren't packages, such as prebuilt binaries other builds download, can be pushed as [generic files](#generic-files). The `/api/hosted` endpoints are disabled by default. Because a pushed version replaces the upstream one for every client, enabling them requires a token: @@ -1005,12 +1629,14 @@ hosted: |--------|-------------|-------------| | `hosted.enabled` | `PROXY_HOSTED_ENABLED` | Register the `/api/hosted` endpoints (default `false`) | | `hosted.token` | `PROXY_HOSTED_TOKEN` | Bearer token required to push and delete; required when enabled, supports `${VAR}` | -| `hosted.max_upload_size` | `PROXY_HOSTED_MAX_UPLOAD_SIZE` | Maximum size of one pushed archive (default `100MB`) | +| `hosted.max_upload_size` | `PROXY_HOSTED_MAX_UPLOAD_SIZE` | Maximum size of one pushed archive or file (default `100MB`) | | `hosted.npm_scopes` | `PROXY_HOSTED_NPM_SCOPES` | npm scopes served from pushed packages only (comma-separated in the environment) | | `hosted.composer_vendors` | `PROXY_HOSTED_COMPOSER_VENDORS` | Composer vendors served from pushed packages only | `hosted.enabled` cannot be combined with `storage.cache_artifacts: false`. +With `hosted.enabled` off, archives pushed earlier stay in storage but are not served as hosted packages: package metadata doesn't list them, `/generic/hosted/` isn't served, and npm and Composer downloads take the normal proxy path, cooldown included. An upstream copy still never replaces a pushed archive. + ### Pushing a patched package 1. Build the archive with the original package name and the version you push in its manifest (`package.json` or `composer.json`), e.g. `request-2.88.3.tgz`. @@ -1026,13 +1652,17 @@ hosted: ```bash curl -X PUT --data-binary @request-2.88.3.tgz \ -H "Authorization: Bearer $PROXY_HOSTED_TOKEN" \ - https://proxy.example.com/api/hosted/npm/request/2.88.3 + "https://proxy.example.com/api/hosted/npm/request/2.88.3?sha256=$(sha256sum request-2.88.3.tgz | cut -d' ' -f1)" ``` + The `sha256` query parameter is optional. When it is set, a push whose bytes don't match is refused with 400. `proxy hosted push` always sends it. + 3. Install it as usual, e.g. `npm install request@2.88.3`. The version is listed in the package metadata, so ranges like `^2.88.0` resolve to it too. 4. Check what is pushed: `proxy hosted list npm request` or `GET /api/hosted/npm/request`. 5. Remove it again: `proxy hosted delete npm request 2.88.3` or `DELETE /api/hosted/npm/request/2.88.3`. If the upstream has the version, clients get the upstream archive again. +A pushed file is never replaced: pushing the same version again answers 409, also under a differently cased Composer name, before the body is uploaded when the client sends `Expect: 100-continue` (as `proxy hosted push` does). Clients that pinned the file by its hash would otherwise get different bytes under the same version. To push it again, delete it first. + ### Supported ecosystems Download handlers look archives up by the filename clients request, so a push is stored under that name: @@ -1041,19 +1671,21 @@ Download handlers look archives up by the filename clients request, so a push is |-----------|------|----------| | `npm` | `{name}` or `@{scope}/{name}` | `{name}-{version}.tgz`, without the scope | | `composer` | `{vendor}/{package}` | `{package}-{version}.zip` | +| `generic` | `{name}`, one path segment | named in the push path, see [Generic files](#generic-files) | Other ecosystems are not supported yet. -The archive must contain the package manifest: `package.json` in the top directory of an npm tarball, or `composer.json` at the root or in the single top directory of a Composer zip. Its name, and its version when it has one, must match the push. Otherwise the push is refused with 400. +npm and Composer archives must contain the package manifest: `package.json` in the top directory of an npm tarball, or `composer.json` at the root or in the single top directory of a Composer zip. Its name, and its version when it has one, must match the push. Otherwise the push is refused with 400. ### Package metadata Pushed versions are listed in the package metadata clients resolve against, with the dependencies from their manifest: - A pushed version takes the place of an upstream version with the same number. -- Pushed versions are added next to the upstream ones and are never held back by cooldown. npm `dist-tags` stay as the upstream has them. +- Pushed versions are added next to the upstream ones and are never held back by cooldown. npm `dist-tags` stay as the upstream has them, also in `npm dist-tag ls`. - A package the upstream doesn't know is served from its pushed versions alone. Its npm `latest` tag is the highest pushed version. - Pushed Composer dev versions (`dev-*`, `*-dev`) are listed in the `~dev` metadata file. +- Pushed Composer versions carry an empty `notification-url`, as routed packages do, so Composer does not report their installs to the default upstream's `notify-batch` endpoint. A pushed `composer.json` that sets its own `notification-url` keeps it, and Composer then reports installs there. - npm entries carry the archive's sha512 as `dist.integrity`. Composer entries carry its sha256 as `dist.reference` and leave `shasum` empty. Metadata of packages with pushed versions is rewritten on every request instead of being cached, so a push or delete shows up on the next request. @@ -1069,10 +1701,113 @@ For private packages: Other packages, including ones in other scopes and vendors, are proxied as usual. +### Generic files + +Files that aren't packages, such as a prebuilt binary that other builds download and check against a pinned sha256, are pushed to the `generic` ecosystem. They have no manifest; the name, version and filename come from the path, and a version can hold several files: + +```bash +proxy hosted push generic tools 1.2.0 ./tool-linux-arm64.tar.gz +# or +curl -X PUT --data-binary @tool-linux-arm64.tar.gz \ + -H "Authorization: Bearer $PROXY_HOSTED_TOKEN" \ + https://proxy.example.com/api/hosted/generic/tools/1.2.0/tool-linux-arm64.tar.gz +``` + +They are downloaded without a token from `/generic/hosted/{name}/{version}/{file}`, with the file's sha256 as `ETag`: + +```bash +curl -O https://proxy.example.com/generic/hosted/tools/1.2.0/tool-linux-arm64.tar.gz +``` + +Generic files never come from an upstream: anything not pushed answers 404. While hosting is enabled, `hosted` can't be used as an `upstream.generic` name. `proxy hosted list generic tools` lists all versions and files. `proxy hosted delete generic tools 1.2.0` removes a version with all its files, and `proxy hosted delete generic tools 1.2.0 tool-linux-arm64.tar.gz` removes only that file. + ### Storage and eviction Pushed archives are stored like cached ones but marked as local. The cache size limit and storage retention never remove them; only a delete does. Scanning, when enabled, checks pushed archives like fetched ones. +## Project inventory + +The project inventory answers "which repository uses which version of a package?". Each repository uploads an SBOM of its default branch, and the proxy records the package versions it lists. The UI then shows: + +- `/ui/projects`: every project, and per project its package versions, marked when the proxy knows a newer version. +- On a package page: which projects use each version, including versions the proxy hasn't cached. + +It is disabled by default. Uploads and deletes require a token: + +```yaml +projects: + enabled: true + token: "${PROXY_PROJECTS_TOKEN}" + max_age: "90d" +``` + +| Config | Environment | Description | +|--------|-------------|-------------| +| `projects.enabled` | `PROXY_PROJECTS_ENABLED` | Register the `/api/projects` endpoints and the UI pages (default `false`) | +| `projects.token` | `PROXY_PROJECTS_TOKEN` | Bearer token required to upload and delete; required when enabled, supports `${VAR}` | +| `projects.max_age` | `PROXY_PROJECTS_MAX_AGE` | Remove projects that haven't uploaded for this long, e.g. `90d` or `720h`; empty or `0` keeps them (default) | + +Removing old projects runs hourly. With several instances on one database, one of them does it. + +### Uploading an SBOM + +`PUT /api/projects/{project}/sbom` takes a CycloneDX (JSON or XML) or SPDX (JSON or tag-value) document of up to 32 MiB and replaces everything recorded for the project with what it lists. The optional `ref` and `branch` query parameters are stored and shown with the project. + +The project name is a path such as `group/sub/repo`: segments of letters, digits, `.`, `_` and `-`, at most 255 characters. It can be sent as path segments (`/api/projects/group/sub/repo/sbom`) or URL-encoded as one segment (`/api/projects/group%2Fsub%2Frepo/sbom`). + +```bash +syft dir:. -o cyclonedx-json > sbom.json +curl -X PUT --data-binary @sbom.json \ + -H "Authorization: Bearer $PROXY_PROJECTS_TOKEN" \ + "https://proxy.example.com/api/projects/acme/shop/web/sbom?ref=$(git rev-parse HEAD)&branch=main" +``` + +The response counts the recorded package versions and the skipped entries: + +```json +{"project":"acme/shop/web","components":9,"skipped":6} +``` + +Entries are recorded by their package URL, with the package named the way the proxy caches it: NuGet IDs lowercased, PyPI names normalized as in PEP 503 (`zope.interface` becomes `zope-interface`), the distribution dropped from `deb`, `rpm` and `apk` package URLs. Entries without a package URL (files, the operating system), package types the proxy doesn't serve (such as `pkg:github`), entries without a version, and conda entries without a `channel` qualifier (the proxy records conda packages as `channel/name`) are skipped. So is the project's own package: the root of a lock file such as `package-lock.json`, and with syft, the Go module its binaries were built from. Duplicates are recorded once. + +A GitLab CI job on the default branch could look like this: + +```yaml +sbom: + image: alpine:3.20 + rules: + - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH + script: + - apk add --no-cache curl + - curl -sSfL https://raw.githubusercontent.com/anchore/syft/main/install.sh | sh -s -- -b /usr/local/bin + - syft dir:. -o cyclonedx-json > sbom.json + - > + curl -sSf -X PUT --data-binary @sbom.json + -H "Authorization: Bearer $PROXY_PROJECTS_TOKEN" + "https://proxy.example.com/api/projects/$CI_PROJECT_PATH/sbom?ref=$CI_COMMIT_SHA&branch=$CI_COMMIT_BRANCH" +``` + +### Querying + +```bash +curl https://proxy.example.com/api/projects # all projects +curl https://proxy.example.com/api/projects/acme/shop/web # one project's package versions +curl 'https://proxy.example.com/api/projects?purl=pkg:npm/lodash' # projects using lodash +curl 'https://proxy.example.com/api/projects?purl=pkg:npm/lodash@4.17.20' # projects using lodash 4.17.20 +curl -X DELETE -H "Authorization: Bearer $PROXY_PROJECTS_TOKEN" \ + https://proxy.example.com/api/projects/acme/shop/web +``` + +Reading needs no token, like the rest of `/api`. With `?purl=`, each project carries the `version` it uses and no `component_count`. A delete names the project itself: `DELETE /api/projects/acme/shop/web/sbom` is answered with 400 unless a project `acme/shop/web/sbom` exists. + +A project's page in the UI also has a delete button. It asks for the token and sends it to `DELETE /ui/api/projects/{project}`, which works like the API endpoint and also requires the token; the token is kept for the browser session. Like `/ui/api/cache`, it sits under `/ui`, so rules for the UI at an ingress cover it. + +### What it shows + +The inventory reflects what the projects' SBOMs list, not what was downloaded through the proxy: a project that installs from another registry still shows up, and the proxy may not have cached any of its packages. The outdated marker compares the version a project uses with the latest version the proxy has recorded for the package; a package the proxy has no record of has none. Versions are compared as the SBOM gives them: a version spelled differently from how the proxy caches it, such as Composer's `v6.4.1` for `6.4.1` or a Debian version with or without its epoch, shows as "not cached" on the package page. + +Project names and the packages they use are shown on `/ui` and `/api/projects` without authentication. If that is sensitive, restrict both at your ingress or reverse proxy. + ## Mirror API The `/api/mirror` endpoints are disabled by default. Enable them to allow starting mirror jobs via HTTP: @@ -1085,7 +1820,7 @@ Or via environment variable: `PROXY_MIRROR_API=true`. When disabled, the endpoints are not registered and return 404. -Start a mirror job with either PURLs or an inline CycloneDX or SPDX JSON document: +Start a mirror job with either PURLs or an inline CycloneDX or SPDX JSON document. Requests without `Content-Type: application/json` get 415, so other websites cannot start jobs through a visitor's browser: ```bash curl -X POST http://localhost:8080/api/mirror \ @@ -1101,16 +1836,66 @@ curl -X POST http://localhost:8080/api/mirror \ -d '{"purls":["pkg:docker/library/alpine@3.20"],"platforms":["linux/amd64"]}' ``` +`latest` mirrors only the newest version of PURLs without a version, like the command's `--latest` flag: + +```bash +curl -X POST http://localhost:8080/api/mirror \ + -H "Content-Type: application/json" \ + -d '{"purls":["pkg:npm/lodash"],"latest":true}' +``` + +## Cache Delete API + +Deleting cached artifacts is disabled by default. Enable it to register `DELETE /api/cache` and show Delete buttons on the version page of the web UI: + +```yaml +cache_delete: true +``` + +Or via environment variable: `PROXY_CACHE_DELETE=true`. + +The endpoint has no authentication. Before enabling it, restrict `/api/cache` and `/ui` to trusted users at your ingress or reverse proxy. The UI sends its deletes to `/ui/api/cache`, so whatever protects `/ui` protects those too. + +Delete every cached file of a version, or only the one named by `filename`: + +```bash +curl -X DELETE http://localhost:8080/api/cache/maven/com.google.guava:guava/32.1.3-jre +curl -X DELETE 'http://localhost:8080/api/cache/maven/com.google.guava:guava/32.1.3-jre?filename=guava-32.1.3-jre.jar' +``` + +The name is the package name the UI shows, for example `group:artifact` for Maven. An RPM package's `filename` is its path under `upstream.rpm` (`updates/40/Everything/x86_64/Packages/c/curl-8.6.0-10.fc40.x86_64.rpm`), since repositories under one upstream can ship different files under one name. The response lists the deleted files. The next request for a deleted file fetches it from the upstream again. The stored bytes are removed after the same delay as a replaced artifact, so downloads already in progress can finish. + +Pushed archives are not touched: a whole-version delete skips them, and naming one answers 409. Delete those through the [hosted API](#hosted-packages). + ## Mirror Command The `proxy mirror` command pre-populates the cache from various sources. It accepts the same storage and database flags as `serve`. +Packages are downloaded from the configured upstreams: npm, cargo, gem, golang, hex, pub, maven and nuget from `upstream.npm`, `upstream.cargo_download`, `upstream.gem`, `upstream.go`, `upstream.hex`, `upstream.pub`, `upstream.maven` and `upstream.nuget`. npm packages in `upstream.npm_routes` come from their route and are cached under the route's keys, so clients get them from the cache as they would after an install. Mirror API jobs do the same. + +A PyPI version is mirrored with every file `upstream.pypi` lists for it: the sdist and each wheel, checked against the listed sha256 and cached under the name and version the download handler reads from the filename. Add the `file_name` qualifier to mirror one file, for example `pkg:pypi/zope.interface@7.2?file_name=zope.interface-7.2-cp312-cp312-macosx_11_0_arm64.whl`. + +A conda version is mirrored with every build anaconda.org lists for it, across all subdirs, and each build is cached the way `/conda/{channel}/{subdir}/{file}` serves it. Give the channel as the namespace or the `channel` qualifier, for example `pkg:conda/conda-forge/numpy@2.1.0`; a package without one is refused. The `subdir`, `build` and `type` qualifiers select builds, for example `pkg:conda/conda-forge/numpy@2.1.0?subdir=linux-64&type=conda`. Builds with a listed sha256 are checked against it. Files are listed from anaconda.org, so mirroring conda fails while `upstream.conda` points somewhere else. + +A Composer release is mirrored with the dist archive `upstream.composer` lists for it, checked against its shasum when one is listed, and cached under the name `/composer/files/...` serves it as. Give the version as the repository lists it, for example `pkg:composer/monolog/monolog@3.8.1`. Branches such as `dev-main` aren't mirrored, since their archive changes with every push, and neither are packages in `upstream.composer_routes`. + +A Helm chart is mirrored from a repository in `upstream.helm`, named as the namespace, for example `pkg:helm/prometheus-community/prometheus@27.1.0` with `prometheus-community` configured. The chart is fetched from the first URL the repository's `index.yaml` lists for that version, checked against the listed digest, and cached under the repository and digest `/helm/{name}/charts/...` serves it from. The index is cached as well, so with [`cache_metadata`](#metadata-caching) on `helm pull` works while the repository is down. Without a version every version in the index is mirrored. Charts named without a repository, or from one that isn't configured, are refused, and so are charts the index lists in an OCI registry: helm pulls those through `/v2`, so mirror them as `pkg:oci` images. + +A Julia package is mirrored with the source tarball `upstream.julia` serves at `/package/{uuid}/{tree-hash}`, cached under the package's name and tree hash as `/julia/package/...` serves it. The PURL needs the `uuid` qualifier, for example `pkg:julia/Example@0.5.5?uuid=7876af07-990d-54b4-ab0e-23690620f79a`. Only packages of the General registry can be mirrored: the uuid and tree hash are read from General on GitHub, also with another `upstream.julia`, since they are the same on every Pkg server serving General. The tarball isn't checked by the proxy, as when serving; Pkg checks the tree hash of what it unpacks, except on Windows. Dependencies, the artifacts in a package's `Artifacts.toml` and the registry aren't mirrored. An offline `Pkg.add` also needs the registry: one installed on the client, or the one the proxy cached when a client last fetched it, which it serves offline with `cache_metadata` on. + +A Swift release is mirrored from `upstream.swift` with its source archive, checked against the SHA-256 checksum in the release metadata and cached under the key `/swift/{scope}/{name}/{version}.zip` serves. Give the registry scope as the namespace, for example `pkg:swift/apple/swift-argument-parser@1.5.0` for `apple.swift-argument-parser`, or the source repository, as SBOM tools write it: `pkg:swift/github.com/apple/swift-argument-parser@1.5.0` is looked up through the upstream's `/identifiers`, and the first identity it lists is mirrored. The release metadata, the package's release list and the release's `Package.swift` with its version-specific manifests are stored in the metadata cache too, so `swift package resolve` works with the upstream unreachable. Serving them, and the archive, offline needs `cache_metadata` on the server, since the archive is served with the checksum from the release metadata. + +A CRAN version is mirrored as its source package from `upstream.cran`, for example `pkg:cran/glue@1.8.1`, and cached under the file name, so it is served for both `/cran/src/contrib/{file}` and `/cran/src/contrib/Archive/{name}/{file}`, where CRAN moves it once a newer version is published. The current version is fetched from `src/contrib` and checked against the MD5 sum in `src/contrib/PACKAGES.gz`; older versions are fetched unchecked from `src/contrib/Archive/{name}/`, as the CRAN handler fetches them. Binary packages aren't mirrored, and neither are the `PACKAGES` indexes, so `install.packages` needs the upstream or an index the proxy already cached; installing the tarball by URL works without either. + +An Alpine package is mirrored from the repository in `upstream.apk` named as the namespace, `alpine` by default, as syft writes it in image SBOMs: `pkg:apk/alpine/busybox@1.36.1-r29?arch=x86_64&distro=alpine-3.20.3`. The `distro` qualifier gives the release (`v3.20`) and `arch` the architecture; packages without either are refused. Edge isn't mirrored: a `distro` with a pre-release suffix, such as `alpine-3.21.0_alpha20240807`, is refused, but an edge system that reports a plain release number can't be told apart and is mirrored from that release. The package is looked up in the `main` and then the `community` `APKINDEX.tar.gz` of that release and cached under the path `/apk/{repository}/{release}/{repo}/{arch}/{file}` serves it from. The file isn't checked by the proxy, as when serving, since the index checksum covers only the package's control section; apk checks it on install. The indexes aren't mirrored, so `apk add` needs the upstream or an index the proxy already cached. Give a version: Alpine repositories keep only the current one. + | Flag | Default | Description | |------|---------|-------------| | `--sbom` | | Path to CycloneDX or SPDX SBOM file | | `--concurrency` | `4` | Number of parallel downloads | | `--dry-run` | `false` | Show what would be mirrored without downloading | | `--platform` | | Comma-separated `os/arch[/variant]` list limiting which platforms of container images are mirrored | +| `--latest` | `false` | Mirror only the newest version of PURLs without a version | | `--config` | | Path to configuration file | | `--storage-url` | | Storage URL | | `--database-driver` | | Database driver | @@ -1123,6 +1908,16 @@ Positional arguments are treated as PURLs: proxy mirror pkg:npm/lodash@4.17.21 pkg:cargo/serde@1.0.0 ``` +### Unversioned PURLs + +A PURL without a version, here or in a mirror API job, mirrors every version the configured upstream lists, through the same client, so `upstream.auth` and `upstream.allow_private_hosts` apply. npm packages in `upstream.npm_routes` are listed from their route. Listing works for npm, gem, golang, hex (from `upstream.hex_api`), pub, pypi, maven, nuget, composer, cran, brew and swift. For cargo and conda the upstream doesn't serve the API used for listing, so versions come from the public registry while the upstream is the default one; with another upstream, and for Composer packages in `upstream.composer_routes` or any other ecosystem, give a version. Julia versions are always listed from the General registry. + +With `--latest`, or `"latest": true` in a mirror API job, only the latest version is mirrored, as git-pkgs/registries picks it: the version the registry advertises as latest where it has one, such as npm's `dist-tags.latest`, and otherwise the newest by publish time, leaving out yanked, retracted and deprecated versions. PURLs with a version, including those in an SBOM, are mirrored as given. Run it from cron to keep the newest releases of a list of packages cached: + +```bash +proxy mirror --latest pkg:npm/lodash pkg:pypi/requests pkg:cargo/serde +``` + ### Container images `pkg:docker` and `pkg:oci` PURLs mirror a container image the way a pull does: the manifest or index, the platform manifests, then config and layer blobs. Everything is stored under the keys a pull through `/v2` reads, so a later `docker pull` or containerd pull is served from cache, also when the upstream is unreachable. @@ -1141,6 +1936,95 @@ proxy mirror 'pkg:oci/debian@sha256:...?repository_url=docker.io/library/debian& - Non-distributable (foreign) layers are skipped. - While `scanning.enabled` is set, the command refuses images, because scanners fetch staged layers from the running server. Use the mirror API instead. +### Homebrew bottles + +`pkg:brew` PURLs mirror a homebrew/core formula's bottles, which Homebrew publishes as an image on `upstream.homebrew_artifact`. They are mirrored like that image, under the keys brew reads through `HOMEBREW_ARTIFACT_DOMAIN`, so `brew install` is served from cache, also when the upstream is unreachable: + +```bash +proxy mirror --platform linux/arm64 pkg:brew/hello@2.12.3 pkg:brew/openssl%403 +``` + +- A formula name with `@` is written with `%40`, since `@` starts the version: `pkg:brew/openssl%403` is `openssl@3`, and `pkg:brew/openssl@3` is version 3 of `openssl`. +- The formula's JSON API on `upstream.homebrew_api` gives the image tag for the current version, which carries the formula's revision and the bottles' rebuild (`hello` 2.12.3 is tagged `2.12.3-1`). Only the current version is described there; another version is used as the tag as given, so give the full tag, such as `2.12.2` or `2.12.3-1`, for older bottles. +- A PURL without a version mirrors the current version. +- `--platform` selects bottles like image platforms: `linux/arm64`, `linux/amd64`, or `darwin/arm64` for every macOS release's arm64 bottle. Without it every bottle of the version is mirrored. +- Dependencies aren't mirrored with a formula; list them too. brew also needs the JSON API, which the proxy keeps with `cache_metadata`. +- Casks, source archives and taps other than homebrew/core aren't mirrored. + +### Git repositories + +`pkg:git` PURLs mirror a repository of an [`upstream.git`](#git-repositories) host into the git cache, so a clone through `/git` is served from it, also when the upstream is unreachable. The PURL names the repository by host and path, and the version is a full commit ID or a tag: + +```bash +proxy mirror pkg:git/github.com/git-pkgs/purl@0123456789abcdef0123456789abcdef01234567 +proxy mirror pkg:git/github.com/git-pkgs/purl@v0.2.1 +proxy mirror pkg:git/github.com/git-pkgs/purl +``` + +- The repository is served by the `upstream.git` host whose URL its host and path start with, the longest one if several do, and has to match that host's `repos`. Others fail. +- The repository's branches and tags are cached, as a clone through the proxy caches them. A commit on none of them is fetched by ID and kept, like one a client fetches by ID, until a branch or tag includes it, or for seven days from the last mirror run that named it, as long as `git.max_size` doesn't evict the repository. Where `upstream.auth` has credentials for the host, commits aren't fetched by ID, and one on no branch or tag that isn't cached yet fails. +- Without a version the repository's branches and tags are mirrored. A tag as the version has to be one of them, so a tag the upstream doesn't have fails. When the upstream can't be reached, a cached tag is mirrored at the commit it last pointed to, with a warning in the log. A branch name or an abbreviated commit ID as the version fails too; give the full commit ID. +- With a version, the submodules that commit records are mirrored at the commits it pins, with their submodules in turn. A relative submodule URL is resolved against the repository's, and an `ssh://`, `git://` or `git@host:path` URL names the repository by its host and path. A submodule no `upstream.git` host serves is skipped with a warning in the log, as are all of a commit's submodules when git can't read its `.gitmodules`. +- The git cache is used by one process. While the server runs, the command can't open `git.cache_dir`, so `pkg:git` items fail and the rest are mirrored; use the mirror API instead. + +### Scheduled refresh + +Tags such as `alpine:3.20` move. The server can re-mirror them on its own, so the cache follows the tag even when nobody pulls it or the proxy is offline later: + +```yaml +mirror: + schedules: + - images: [pkg:docker/library/alpine@3.20, pkg:docker/library/nginx@stable] + interval: 6h + platforms: [linux/amd64] +``` + +| Setting | Env | Description | +|---------|-----|-------------| +| `mirror.schedules[].images` | - | `pkg:docker` or `pkg:oci` PURLs with a tag, resolved like the `mirror` command | +| `mirror.schedules[].interval` | - | How often the images are mirrored, at least `1m` | +| `mirror.schedules[].platforms` | - | `os/arch[/variant]` entries limiting the platforms; empty mirrors all | + +Each run checks the tag with a HEAD request. If the tag still points to the cached digest, nothing else is fetched. If it moved, the new manifests and blobs are fetched first and the tag is switched only when all of them are cached, so a failed run leaves the previous image pullable. Images of one schedule are mirrored one after the other. + +- The first run starts within ten minutes of startup, later runs every `interval` ±10 %, so restarts and several instances don't hit the registry at once. Instances sharing a PostgreSQL database run each schedule once per interval: the first to reach it records the run, and the others skip it. A run cut off by a shutdown is not recorded, so the next instance to reach the schedule runs it. +- Digest-pinned PURLs never move and are rejected. A `pkg:oci` digest with `tag=` is accepted; the tag is refreshed and a warning is logged when it no longer matches the digest. +- The previous digest stays cached, so pulls by digest keep working, until eviction or retention removes it. +- Docker Hub does not count HEAD requests against its pull limit, but every changed manifest is a pull. Set `platforms` and `upstream.auth` for `registry-1.docker.io` to stay under the anonymous limit. +- Mirrored layers are scanned when `scanning.enabled` is set. A blocked layer fails the run and keeps the previous image. +- Schedules are read at startup; changes need a restart. They do not need `mirror_api`. + +### Refreshing the most used packages + +For packages, the cache learns about a new release only when a client asks for it, and that first install waits on the upstream or fails while it is down. `mirror.refresh` mirrors new releases of the packages clients download most, so they are cached before anyone asks: + +```yaml +mirror: + refresh: + interval: 24h + top: 50 + since: 14d + max_versions: 200 + max_bytes: 2GB +``` + +| Setting | Env | Description | +|---------|-----|-------------| +| `mirror.refresh.interval` | - | How often the refresh runs, at least `1m` | +| `mirror.refresh.top` | - | Packages per ecosystem to refresh, the ones with the most downloads among those downloaded within `since`. Default: `50` | +| `mirror.refresh.since` | - | How recently a package must have been downloaded, with a `d` suffix for days. Default: `14d` | +| `mirror.refresh.max_versions` | - | Stop a run after mirroring this many new versions. Default: no cap | +| `mirror.refresh.max_bytes` | - | Stop a run once it has downloaded this much, such as `2GB`. It is checked before each version, so the last one can go over it. Default: no cap | + +For each of those packages a run lists the releases on the configured upstream and mirrors, for each major line a version is cached on, the newest release of that line. A major line is the major version, or `0.minor` below 1.0. Versions numbered by year, such as certifi's `2025.1.31`, are all one line. Prereleases and yanked, retracted or deprecated releases are skipped, and so are releases cooldown still withholds or the denylist names, so a run mirrors what clients would be served rather than the newest published. A release that leaves cooldown later is mirrored by a later run. + +- PyPI and conda versions publish many files. Only the kinds clients fetched of earlier versions are mirrored: wheels with the same python and ABI tags for the same OS and architecture, whatever glibc or macOS version they need (and, for `abi3` wheels, whatever minimum Python version), and the sdist, or conda packages of the same subdir, build variant (such as `py312` or `_cpython`) and file type. +- Debian, Alpine and RPM clients find new versions in repository indexes. A run fetches the `InRelease`, `APKINDEX.tar.gz` and `repomd.xml` files clients fetched within `since` again from upstream, which doesn't count as a client fetching them, reads the `Packages` and primary indexes they point at for the components and architectures of the cached packages, and mirrors the newest file each index lists of a package and architecture when it isn't cached but an older version is. Suites sharing a pool, such as bookworm and trixie, are refreshed each on its own that way. Files are checked against the SHA-256 the index lists, where it lists one. Indexes are found by the URL the metadata cache records with them, which caches from before this release lack until they are next revalidated. This requires `cache_metadata`; without it the proxy logs a warning at startup and refreshes the other ecosystems only. +- Container images are not refreshed; list the tags to follow in `mirror.schedules`. Arch Linux and FreeBSD packages, Julia packages, which are cached by tree hash, and other ecosystems the mirror can't list versions of are left out too. +- Hit counts are kept per file since it was cached, so `top` ranks by all downloads of the files used within `since`. A file a run mirrored counts as used only once a client downloads it, so a package nobody fetches drops out after `since`. +- Runs are spread and shared between instances like schedules: the first run comes within ten minutes of startup, later ones every `interval` ±10 %, and instances sharing a PostgreSQL database take turns. A run fetches one version at a time. +- What a run mirrors is evicted by `storage.max_size` and retention like any other file. With `max_versions` and `max_bytes` a run stays bounded when many packages release at once. + ## Docker ### SQLite with Local Storage diff --git a/docs/docker-builds.md b/docs/docker-builds.md new file mode 100644 index 0000000..8509b9d --- /dev/null +++ b/docs/docker-builds.md @@ -0,0 +1,168 @@ +# Using proxy in Docker builds + +Docker builds can share proxy's package cache even when their builders and local +package caches are new. Configure the package manager inside the build to use +proxy. Cached archives still need to be downloaded from proxy and installed; +native extensions still need to be compiled. + +## Run a persistent proxy + +Run proxy outside the image build and keep its database and artifact storage +between builds. For a proxy running on your development machine: + +```sh +PROXY_CACHE_METADATA=true proxy serve \ + -listen :8080 \ + -base-url http://host.docker.internal:8080 \ + -storage-url "file://$PWD/proxy-cache/artifacts" \ + -database-path ./proxy-cache/proxy.db +``` + +Docker Desktop provides `host.docker.internal` for reaching the host. On Linux +Docker Engine, add the host mapping when building: + +```sh +docker build \ + --add-host host.docker.internal=host-gateway \ + --build-arg PROXY_URL=http://host.docker.internal:8080 \ + -t app . +``` + +`localhost` inside a build refers to the build container. Both the build's proxy +URL and proxy's `base_url` must be reachable from that container, since some +registry responses contain download URLs derived from `base_url`. The proxy +must listen on an interface reachable from the builder, with access restricted +to the machines that should use it. + +For CI or a remote builder, use a persistent service reachable from the builder, +such as `https://proxy.example.com`, and set proxy's `base_url` to that address. +Use the same service across jobs and pass its URL with `--build-arg PROXY_URL=...`. +Creating an empty proxy for every job loses the shared cache unless its database +and storage persist. If proxy runs in a container, mount persistent storage for +both. See [configuration](configuration.md) for storage and deployment options. + +Metadata caching is optional, but avoids repeated metadata fetches within +`metadata_ttl`. Artifact caching is enabled by default. Proxy's configured +cooldown, denylist and scanning policies also apply to Docker builds. + +## npm + +In your Node build stage, copy the manifests before application source so an +unchanged dependency set can reuse Docker's installation layer: + +```dockerfile +ARG PROXY_URL +COPY package.json package-lock.json ./ +RUN npm ci --no-audit --no-fund --registry="${PROXY_URL:?PROXY_URL build arg required}/npm/" +COPY . . +``` + +Pass `PROXY_URL` without a trailing slash. With Docker Desktop: + +```sh +docker build \ + --build-arg PROXY_URL=http://host.docker.internal:8080 \ + -t app . +``` + +Keep `node_modules` out of the build context so `COPY . .` does not overwrite +the installed dependencies. Lockfiles with custom registry or download URLs +may still direct requests to those hosts; check proxy's access log when using +private registries or non-registry dependencies. `--no-audit` skips the audit +request, which proxy would otherwise forward upstream. + +## Ruby / Bundler + +Keep `https://rubygems.org` as the source in your Gemfile and configure its mirror +inside the Ruby build stage. Install any system packages needed to compile +native extensions before this step: + +```dockerfile +ARG PROXY_URL +COPY Gemfile Gemfile.lock ./ +RUN bundle config set --local mirror.https://rubygems.org "${PROXY_URL:?PROXY_URL build arg required}/gem" \ + && bundle install \ + && bundle config unset --local mirror.https://rubygems.org +COPY . . +``` + +Use the same build command as the npm example. The mirror setting is removed +after installation so it is not retained in the image, but the URL still +appears in `docker history` because Docker records the build args used by `RUN` +lines. Keep credentials out of `PROXY_URL`. Exclude host Bundler +configuration and installed gems from the build context. Copy any local path +dependencies required by the Gemfile before `bundle install`. + +The RubyGems mirror covers gems fetched from that source. Git dependencies and +other gem sources need their own configuration. Without +`mirror.https://rubygems.org.fallback_timeout`, `bundle install` fails if proxy +is unreachable. Setting it lets Bundler fall back to rubygems.org, so this setup +does not enforce network isolation either way. + +## Layer caches and package caches + +Keep existing Docker caching optimizations. If Docker reuses the installation +layer, the package manager does not run and proxy receives no requests. A +BuildKit cache mount can also preserve downloaded packages when that layer must +be rebuilt. For example, the npm step can use: + +```dockerfile +RUN --mount=type=cache,target=/root/.npm \ + npm ci --no-audit --no-fund --registry="${PROXY_URL:?PROXY_URL build arg required}/npm/" +``` + +Cache mounts are stored by the builder and are excluded from ordinary +`--cache-to` exports. Proxy can supply packages when a fresh builder has neither +the installation layer nor the package-manager cache. See Docker's +[cache guidance](https://docs.docker.com/build/cache/optimize/) and +[cache-mount reference](https://docs.docker.com/reference/dockerfile/#run---mounttypecache). + +To check the configuration, enable proxy's JSONL log with `-access-log` and +rebuild with `docker build --no-cache`. Look for requests to `/npm/` or `/gem/`, +then repeat and check `proxy_cache_hits_total` on `/metrics`. Cache mounts still +retain their contents with `--no-cache`; omit them when testing proxy cache +hits. Upstream metadata revalidation can still occur. + +## Base-image pulls + +Package-manager configuration affects commands such as `npm ci` and +`bundle install`. To cache images referenced by `FROM`, configure a registry +mirror in the builder as well. For a proxy served at +`https://proxy.example.com`, put this in `buildkitd.toml`: + +```toml +[registry."docker.io"] + mirrors = ["proxy.example.com"] +``` + +Create a Buildx builder with that configuration and select it explicitly: + +```sh +docker buildx create --name proxy-builder \ + --driver docker-container \ + --buildkitd-config ./buildkitd.toml + +docker buildx build --builder proxy-builder \ + --build-arg PROXY_URL=https://proxy.example.com \ + --load -t app . +``` + +For local Docker Desktop testing over HTTP, the configuration is: + +```toml +[registry."docker.io"] + mirrors = ["host.docker.internal:8080"] + +[registry."host.docker.internal:8080"] + http = true +``` + +The registry mirror address must be reachable from the BuildKit daemon itself. +The build's `--add-host` flag only adds a mapping inside build containers. A +separate Buildx builder has its own registry configuration; setting Docker +Engine's `registry-mirrors` does not configure that builder. See Docker's +[BuildKit configuration guide](https://docs.docker.com/build/buildkit/configure/). + +Proxy's OCI endpoint is pull-only. BuildKit registry-cache exports with +`--cache-to type=registry` need a separate writable registry. Other cache export +backends can be used alongside proxy. diff --git a/docs/swagger/docs.go b/docs/swagger/docs.go index 7a8387d..fe8723d 100644 --- a/docs/swagger/docs.go +++ b/docs/swagger/docs.go @@ -115,6 +115,73 @@ const docTemplate = `{ } } }, + "/api/cache/{ecosystem}/{name}/{version}": { + "delete": { + "description": "Removes the cached files of name@version, or only the one named by filename, so the next request fetches them from the upstream again. Pushed archives are not touched; delete those through /api/hosted.", + "produces": [ + "application/json" + ], + "tags": [ + "cache" + ], + "summary": "Delete cached artifacts", + "parameters": [ + { + "type": "string", + "description": "Ecosystem", + "name": "ecosystem", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "Package name as shown in the UI, e.g. com.google.guava:guava for Maven", + "name": "name", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "Version", + "name": "version", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "Delete only this file", + "name": "filename", + "in": "query" + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/server.CacheDeleteResponse" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/server.ErrorResponse" + } + }, + "404": { + "description": "Not Found", + "schema": { + "$ref": "#/definitions/server.ErrorResponse" + } + }, + "409": { + "description": "Conflict", + "schema": { + "$ref": "#/definitions/server.ErrorResponse" + } + } + } + } + }, "/api/hosted/{ecosystem}/{name}": { "get": { "produces": [ @@ -163,7 +230,7 @@ const docTemplate = `{ "BearerAuth": [] } ], - "description": "Stores the request body as the archive for name@version. It is served in place of the upstream archive with the same version and is never evicted.", + "description": "Stores the request body as the archive for name@version. It is served in place of the upstream archive with the same version and is never evicted. Generic files are pushed to /api/hosted/generic/{name}/{version}/{file} and served at /generic/hosted/{name}/{version}/{file}. A file that was already pushed is refused with 409; delete it first to push it again.", "consumes": [ "application/octet-stream" ], @@ -177,7 +244,7 @@ const docTemplate = `{ "parameters": [ { "type": "string", - "description": "Ecosystem (npm or composer)", + "description": "Ecosystem (npm, composer or generic)", "name": "ecosystem", "in": "path", "required": true @@ -195,6 +262,12 @@ const docTemplate = `{ "name": "version", "in": "path", "required": true + }, + { + "type": "string", + "description": "Expected sha256 of the body, hex-encoded; a mismatch is refused", + "name": "sha256", + "in": "query" } ], "responses": { @@ -222,6 +295,12 @@ const docTemplate = `{ "$ref": "#/definitions/server.ErrorResponse" } }, + "409": { + "description": "Conflict", + "schema": { + "$ref": "#/definitions/server.ErrorResponse" + } + }, "413": { "description": "Request Entity Too Large", "schema": { @@ -236,7 +315,7 @@ const docTemplate = `{ "BearerAuth": [] } ], - "description": "Removes the archives pushed for name@version. If the upstream has the version, clients get the upstream archive again.", + "description": "Removes the archives pushed for name@version. If the upstream has the version, clients get the upstream archive again. For generic files, /api/hosted/generic/{name}/{version}/{file} removes only that file.", "tags": [ "hosted" ], @@ -381,6 +460,194 @@ const docTemplate = `{ } } }, + "/api/projects": { + "get": { + "description": "Lists the projects that uploaded an SBOM. With purl, lists the projects using that package, or only that version of it when the purl has one; each entry then carries the version the project uses.", + "produces": [ + "application/json" + ], + "tags": [ + "projects" + ], + "summary": "List projects", + "parameters": [ + { + "type": "string", + "description": "Package URL, e.g. pkg:npm/lodash or pkg:npm/lodash@4.17.20", + "name": "purl", + "in": "query" + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/server.ProjectListResponse" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/server.ErrorResponse" + } + } + } + } + }, + "/api/projects/{project}": { + "get": { + "description": "Returns the project with the package versions recorded for it.", + "produces": [ + "application/json" + ], + "tags": [ + "projects" + ], + "summary": "Get a project", + "parameters": [ + { + "type": "string", + "description": "Project path, e.g. group/sub/repo", + "name": "project", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/server.ProjectResponse" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/server.ErrorResponse" + } + }, + "404": { + "description": "Not Found", + "schema": { + "$ref": "#/definitions/server.ErrorResponse" + } + } + } + }, + "delete": { + "security": [ + { + "BearerAuth": [] + } + ], + "description": "Removes the project and the package versions recorded for it. The path names the project itself, without the /sbom of the upload path: a path ending in /sbom that names no project is answered with 400.", + "tags": [ + "projects" + ], + "summary": "Delete a project", + "parameters": [ + { + "type": "string", + "description": "Project path, e.g. group/sub/repo", + "name": "project", + "in": "path", + "required": true + } + ], + "responses": { + "204": { + "description": "No Content" + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/server.ErrorResponse" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/server.ErrorResponse" + } + }, + "404": { + "description": "Not Found", + "schema": { + "$ref": "#/definitions/server.ErrorResponse" + } + } + } + } + }, + "/api/projects/{project}/sbom": { + "put": { + "security": [ + { + "BearerAuth": [] + } + ], + "description": "Replaces the package versions recorded for the project with the ones the SBOM lists. CycloneDX (JSON or XML) and SPDX (JSON or tag-value) are accepted, e.g. the output of ` + "`" + `syft dir:. -o cyclonedx-json` + "`" + `. Entries without a package URL or version, of a package type the proxy doesn't serve, and the project's own packages are skipped and counted. The project may be given as path segments or URL-encoded as one segment.", + "consumes": [ + "application/json", + "application/xml", + "text/plain" + ], + "produces": [ + "application/json" + ], + "tags": [ + "projects" + ], + "summary": "Upload a project's SBOM", + "parameters": [ + { + "type": "string", + "description": "Project path, e.g. group/sub/repo", + "name": "project", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "Commit the SBOM was generated from", + "name": "ref", + "in": "query" + }, + { + "type": "string", + "description": "Branch the SBOM was generated from", + "name": "branch", + "in": "query" + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/server.ProjectUploadResponse" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/server.ErrorResponse" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/server.ErrorResponse" + } + }, + "413": { + "description": "Request Entity Too Large", + "schema": { + "$ref": "#/definitions/server.ErrorResponse" + } + } + } + } + }, "/api/search": { "get": { "produces": [ @@ -753,6 +1020,20 @@ const docTemplate = `{ } } }, + "server.CacheDeleteResponse": { + "type": "object", + "properties": { + "deleted": { + "type": "array", + "items": { + "type": "string" + } + }, + "purl": { + "type": "string" + } + } + }, "server.EcosystemStatsEntry": { "type": "object", "properties": { @@ -969,6 +1250,10 @@ const docTemplate = `{ "server.PackageResponse": { "type": "object", "properties": { + "cooldown": { + "description": "Cooldown is the cooldown that applies to the package, in the\nconfiguration's syntax (\"3d\", \"0\").", + "type": "string" + }, "description": { "type": "string" }, @@ -1027,6 +1312,106 @@ const docTemplate = `{ } } }, + "server.ProjectComponent": { + "type": "object", + "properties": { + "ecosystem": { + "type": "string" + }, + "name": { + "type": "string" + }, + "purl": { + "type": "string" + }, + "version": { + "type": "string" + } + } + }, + "server.ProjectListResponse": { + "type": "object", + "properties": { + "projects": { + "type": "array", + "items": { + "$ref": "#/definitions/server.ProjectSummary" + } + } + } + }, + "server.ProjectResponse": { + "type": "object", + "properties": { + "branch": { + "type": "string" + }, + "component_count": { + "description": "ComponentCount is the number of package versions recorded. It is not\nset when listing the projects using a package.", + "type": "integer" + }, + "components": { + "type": "array", + "items": { + "$ref": "#/definitions/server.ProjectComponent" + } + }, + "name": { + "type": "string" + }, + "ref": { + "type": "string" + }, + "uploaded_at": { + "type": "string" + }, + "version": { + "description": "Version is set when listing the projects using a package: the version\nof it this project uses.", + "type": "string" + } + } + }, + "server.ProjectSummary": { + "type": "object", + "properties": { + "branch": { + "type": "string" + }, + "component_count": { + "description": "ComponentCount is the number of package versions recorded. It is not\nset when listing the projects using a package.", + "type": "integer" + }, + "name": { + "type": "string" + }, + "ref": { + "type": "string" + }, + "uploaded_at": { + "type": "string" + }, + "version": { + "description": "Version is set when listing the projects using a package: the version\nof it this project uses.", + "type": "string" + } + } + }, + "server.ProjectUploadResponse": { + "type": "object", + "properties": { + "components": { + "description": "Components is the number of package versions recorded.", + "type": "integer" + }, + "project": { + "type": "string" + }, + "skipped": { + "description": "Skipped is the number of SBOM entries not recorded: without a package\nURL or a version, of a package type the proxy doesn't serve, conda\nentries without a channel, and the project's own packages.", + "type": "integer" + } + } + }, "server.SearchPackageResult": { "type": "object", "properties": { @@ -1076,9 +1461,6 @@ const docTemplate = `{ "cached_artifacts": { "type": "integer" }, - "database_path": { - "type": "string" - }, "downloaded": { "type": "string" }, @@ -1099,9 +1481,6 @@ const docTemplate = `{ "description": "StatsUnavailable distinguishes a proxy that has served nothing from one\nwhose aggregation failed with no snapshot to fall back on. Without it\nboth report zeros and an empty array.", "type": "boolean" }, - "storage_url": { - "type": "string" - }, "total_size": { "type": "string" }, @@ -1113,7 +1492,7 @@ const docTemplate = `{ }, "securityDefinitions": { "BearerAuth": { - "description": "\"Bearer \" followed by hosted.token", + "description": "\"Bearer \" followed by hosted.token, or projects.token for /api/projects", "type": "apiKey", "name": "Authorization", "in": "header" diff --git a/docs/swagger/swagger.json b/docs/swagger/swagger.json index aad0cea..496aecd 100644 --- a/docs/swagger/swagger.json +++ b/docs/swagger/swagger.json @@ -108,6 +108,73 @@ } } }, + "/api/cache/{ecosystem}/{name}/{version}": { + "delete": { + "description": "Removes the cached files of name@version, or only the one named by filename, so the next request fetches them from the upstream again. Pushed archives are not touched; delete those through /api/hosted.", + "produces": [ + "application/json" + ], + "tags": [ + "cache" + ], + "summary": "Delete cached artifacts", + "parameters": [ + { + "type": "string", + "description": "Ecosystem", + "name": "ecosystem", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "Package name as shown in the UI, e.g. com.google.guava:guava for Maven", + "name": "name", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "Version", + "name": "version", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "Delete only this file", + "name": "filename", + "in": "query" + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/server.CacheDeleteResponse" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/server.ErrorResponse" + } + }, + "404": { + "description": "Not Found", + "schema": { + "$ref": "#/definitions/server.ErrorResponse" + } + }, + "409": { + "description": "Conflict", + "schema": { + "$ref": "#/definitions/server.ErrorResponse" + } + } + } + } + }, "/api/hosted/{ecosystem}/{name}": { "get": { "produces": [ @@ -156,7 +223,7 @@ "BearerAuth": [] } ], - "description": "Stores the request body as the archive for name@version. It is served in place of the upstream archive with the same version and is never evicted.", + "description": "Stores the request body as the archive for name@version. It is served in place of the upstream archive with the same version and is never evicted. Generic files are pushed to /api/hosted/generic/{name}/{version}/{file} and served at /generic/hosted/{name}/{version}/{file}. A file that was already pushed is refused with 409; delete it first to push it again.", "consumes": [ "application/octet-stream" ], @@ -170,7 +237,7 @@ "parameters": [ { "type": "string", - "description": "Ecosystem (npm or composer)", + "description": "Ecosystem (npm, composer or generic)", "name": "ecosystem", "in": "path", "required": true @@ -188,6 +255,12 @@ "name": "version", "in": "path", "required": true + }, + { + "type": "string", + "description": "Expected sha256 of the body, hex-encoded; a mismatch is refused", + "name": "sha256", + "in": "query" } ], "responses": { @@ -215,6 +288,12 @@ "$ref": "#/definitions/server.ErrorResponse" } }, + "409": { + "description": "Conflict", + "schema": { + "$ref": "#/definitions/server.ErrorResponse" + } + }, "413": { "description": "Request Entity Too Large", "schema": { @@ -229,7 +308,7 @@ "BearerAuth": [] } ], - "description": "Removes the archives pushed for name@version. If the upstream has the version, clients get the upstream archive again.", + "description": "Removes the archives pushed for name@version. If the upstream has the version, clients get the upstream archive again. For generic files, /api/hosted/generic/{name}/{version}/{file} removes only that file.", "tags": [ "hosted" ], @@ -374,6 +453,194 @@ } } }, + "/api/projects": { + "get": { + "description": "Lists the projects that uploaded an SBOM. With purl, lists the projects using that package, or only that version of it when the purl has one; each entry then carries the version the project uses.", + "produces": [ + "application/json" + ], + "tags": [ + "projects" + ], + "summary": "List projects", + "parameters": [ + { + "type": "string", + "description": "Package URL, e.g. pkg:npm/lodash or pkg:npm/lodash@4.17.20", + "name": "purl", + "in": "query" + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/server.ProjectListResponse" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/server.ErrorResponse" + } + } + } + } + }, + "/api/projects/{project}": { + "get": { + "description": "Returns the project with the package versions recorded for it.", + "produces": [ + "application/json" + ], + "tags": [ + "projects" + ], + "summary": "Get a project", + "parameters": [ + { + "type": "string", + "description": "Project path, e.g. group/sub/repo", + "name": "project", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/server.ProjectResponse" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/server.ErrorResponse" + } + }, + "404": { + "description": "Not Found", + "schema": { + "$ref": "#/definitions/server.ErrorResponse" + } + } + } + }, + "delete": { + "security": [ + { + "BearerAuth": [] + } + ], + "description": "Removes the project and the package versions recorded for it. The path names the project itself, without the /sbom of the upload path: a path ending in /sbom that names no project is answered with 400.", + "tags": [ + "projects" + ], + "summary": "Delete a project", + "parameters": [ + { + "type": "string", + "description": "Project path, e.g. group/sub/repo", + "name": "project", + "in": "path", + "required": true + } + ], + "responses": { + "204": { + "description": "No Content" + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/server.ErrorResponse" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/server.ErrorResponse" + } + }, + "404": { + "description": "Not Found", + "schema": { + "$ref": "#/definitions/server.ErrorResponse" + } + } + } + } + }, + "/api/projects/{project}/sbom": { + "put": { + "security": [ + { + "BearerAuth": [] + } + ], + "description": "Replaces the package versions recorded for the project with the ones the SBOM lists. CycloneDX (JSON or XML) and SPDX (JSON or tag-value) are accepted, e.g. the output of `syft dir:. -o cyclonedx-json`. Entries without a package URL or version, of a package type the proxy doesn't serve, and the project's own packages are skipped and counted. The project may be given as path segments or URL-encoded as one segment.", + "consumes": [ + "application/json", + "application/xml", + "text/plain" + ], + "produces": [ + "application/json" + ], + "tags": [ + "projects" + ], + "summary": "Upload a project's SBOM", + "parameters": [ + { + "type": "string", + "description": "Project path, e.g. group/sub/repo", + "name": "project", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "Commit the SBOM was generated from", + "name": "ref", + "in": "query" + }, + { + "type": "string", + "description": "Branch the SBOM was generated from", + "name": "branch", + "in": "query" + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/server.ProjectUploadResponse" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/server.ErrorResponse" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/server.ErrorResponse" + } + }, + "413": { + "description": "Request Entity Too Large", + "schema": { + "$ref": "#/definitions/server.ErrorResponse" + } + } + } + } + }, "/api/search": { "get": { "produces": [ @@ -746,6 +1013,20 @@ } } }, + "server.CacheDeleteResponse": { + "type": "object", + "properties": { + "deleted": { + "type": "array", + "items": { + "type": "string" + } + }, + "purl": { + "type": "string" + } + } + }, "server.EcosystemStatsEntry": { "type": "object", "properties": { @@ -962,6 +1243,10 @@ "server.PackageResponse": { "type": "object", "properties": { + "cooldown": { + "description": "Cooldown is the cooldown that applies to the package, in the\nconfiguration's syntax (\"3d\", \"0\").", + "type": "string" + }, "description": { "type": "string" }, @@ -1020,6 +1305,106 @@ } } }, + "server.ProjectComponent": { + "type": "object", + "properties": { + "ecosystem": { + "type": "string" + }, + "name": { + "type": "string" + }, + "purl": { + "type": "string" + }, + "version": { + "type": "string" + } + } + }, + "server.ProjectListResponse": { + "type": "object", + "properties": { + "projects": { + "type": "array", + "items": { + "$ref": "#/definitions/server.ProjectSummary" + } + } + } + }, + "server.ProjectResponse": { + "type": "object", + "properties": { + "branch": { + "type": "string" + }, + "component_count": { + "description": "ComponentCount is the number of package versions recorded. It is not\nset when listing the projects using a package.", + "type": "integer" + }, + "components": { + "type": "array", + "items": { + "$ref": "#/definitions/server.ProjectComponent" + } + }, + "name": { + "type": "string" + }, + "ref": { + "type": "string" + }, + "uploaded_at": { + "type": "string" + }, + "version": { + "description": "Version is set when listing the projects using a package: the version\nof it this project uses.", + "type": "string" + } + } + }, + "server.ProjectSummary": { + "type": "object", + "properties": { + "branch": { + "type": "string" + }, + "component_count": { + "description": "ComponentCount is the number of package versions recorded. It is not\nset when listing the projects using a package.", + "type": "integer" + }, + "name": { + "type": "string" + }, + "ref": { + "type": "string" + }, + "uploaded_at": { + "type": "string" + }, + "version": { + "description": "Version is set when listing the projects using a package: the version\nof it this project uses.", + "type": "string" + } + } + }, + "server.ProjectUploadResponse": { + "type": "object", + "properties": { + "components": { + "description": "Components is the number of package versions recorded.", + "type": "integer" + }, + "project": { + "type": "string" + }, + "skipped": { + "description": "Skipped is the number of SBOM entries not recorded: without a package\nURL or a version, of a package type the proxy doesn't serve, conda\nentries without a channel, and the project's own packages.", + "type": "integer" + } + } + }, "server.SearchPackageResult": { "type": "object", "properties": { @@ -1069,9 +1454,6 @@ "cached_artifacts": { "type": "integer" }, - "database_path": { - "type": "string" - }, "downloaded": { "type": "string" }, @@ -1092,9 +1474,6 @@ "description": "StatsUnavailable distinguishes a proxy that has served nothing from one\nwhose aggregation failed with no snapshot to fall back on. Without it\nboth report zeros and an empty array.", "type": "boolean" }, - "storage_url": { - "type": "string" - }, "total_size": { "type": "string" }, @@ -1106,7 +1485,7 @@ }, "securityDefinitions": { "BearerAuth": { - "description": "\"Bearer \" followed by hosted.token", + "description": "\"Bearer \" followed by hosted.token, or projects.token for /api/projects", "type": "apiKey", "name": "Authorization", "in": "header" diff --git a/go.mod b/go.mod index 670f884..dce5841 100644 --- a/go.mod +++ b/go.mod @@ -1,82 +1,82 @@ module github.com/git-pkgs/proxy -go 1.26.7 +go 1.27.3 require ( github.com/BurntSushi/toml v1.6.0 - github.com/CycloneDX/cyclonedx-go v0.12.0 github.com/Masterminds/semver/v3 v3.5.0 - github.com/aws/aws-sdk-go-v2/config v1.33.7 - github.com/aws/aws-sdk-go-v2/service/ecr v1.66.2 - github.com/git-pkgs/archives v0.8.1 + github.com/aws/aws-sdk-go-v2/config v1.33.12 + github.com/aws/aws-sdk-go-v2/service/ecr v1.67.1 + github.com/git-pkgs/archives v0.10.0 github.com/git-pkgs/artifacts v0.2.1 - github.com/git-pkgs/cooldown v0.2.0 - github.com/git-pkgs/enrichment v0.7.2 + github.com/git-pkgs/cooldown v0.3.1 + github.com/git-pkgs/enrichment v0.7.5 github.com/git-pkgs/gcs v0.1.0 github.com/git-pkgs/integrity v0.2.0 - github.com/git-pkgs/magic v0.5.0 - github.com/git-pkgs/purl v0.1.21 - github.com/git-pkgs/registries v0.9.3 + github.com/git-pkgs/magic v0.6.0 + github.com/git-pkgs/purl v0.2.1 + github.com/git-pkgs/registries v0.13.0 + github.com/git-pkgs/sbom v0.1.9 github.com/git-pkgs/spdx v0.3.3 github.com/git-pkgs/vers v0.7.2 - github.com/git-pkgs/vulns v0.2.4 - github.com/go-chi/chi/v5 v5.3.2 + github.com/go-chi/chi/v5 v5.5.0 github.com/jmoiron/sqlx v1.4.0 + github.com/klauspost/compress v1.20.3 github.com/lib/pq v1.12.3 github.com/opencontainers/go-digest v1.0.0 github.com/prometheus/client_golang v1.25.0 github.com/prometheus/client_model v0.6.3 - github.com/spdx/tools-golang v0.5.7 github.com/swaggo/swag v1.16.6 - gocloud.dev v0.46.0 - golang.org/x/mod v0.41.0 - golang.org/x/net v0.59.0 + github.com/ulikunitz/xz v0.5.17 + github.com/vmihailenco/msgpack/v5 v5.4.1 + gocloud.dev v0.47.0 + golang.org/x/mod v0.42.0 + golang.org/x/net v0.62.0 golang.org/x/sync v0.24.0 google.golang.org/protobuf v1.36.12 gopkg.in/yaml.v3 v3.0.1 - modernc.org/sqlite v1.60.1 + modernc.org/sqlite v1.61.0 ) require ( - cloud.google.com/go/auth v0.21.0 // indirect + cloud.google.com/go/auth v0.23.2 // indirect cloud.google.com/go/auth/oauth2adapt v0.2.8 // indirect cloud.google.com/go/compute/metadata v0.9.0 // indirect - github.com/Azure/azure-sdk-for-go/sdk/azcore v1.21.0 // indirect - github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.13.1 // indirect - github.com/Azure/azure-sdk-for-go/sdk/internal v1.11.2 // indirect - github.com/Azure/azure-sdk-for-go/sdk/storage/azblob v1.6.4 // indirect - github.com/AzureAD/microsoft-authentication-library-for-go v1.7.0 // indirect + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.23.1 // indirect + github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.14.1 // indirect + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + github.com/Azure/azure-sdk-for-go/sdk/storage/azblob v1.8.0 // indirect + github.com/AzureAD/microsoft-authentication-library-for-go v1.9.0 // indirect github.com/KyleBanks/depth v1.2.1 // indirect github.com/PuerkitoBio/purell v1.1.1 // indirect github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578 // indirect - github.com/anchore/go-struct-converter v0.1.0 // indirect github.com/apapsch/go-jsonmerge/v2 v2.0.0 // indirect - github.com/aws/aws-sdk-go-v2 v1.47.1 // indirect - github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.11 // indirect - github.com/aws/aws-sdk-go-v2/credentials v1.20.7 // indirect - github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.20.1 // indirect - github.com/aws/aws-sdk-go-v2/feature/s3/transfermanager v0.2.3 // indirect - github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.4 // indirect - github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.4 // indirect - github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.4 // indirect - github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.19 // indirect - github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.18 // indirect - github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.4 // indirect - github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.25 // indirect - github.com/aws/aws-sdk-go-v2/service/s3 v1.102.2 // indirect - github.com/aws/aws-sdk-go-v2/service/signin v1.10.2 // indirect - github.com/aws/aws-sdk-go-v2/service/sso v1.38.2 // indirect - github.com/aws/aws-sdk-go-v2/service/ssooidc v1.43.2 // indirect - github.com/aws/aws-sdk-go-v2/service/sts v1.51.2 // indirect - github.com/aws/smithy-go v1.28.1 // indirect + github.com/aws/aws-sdk-go-v2 v1.47.5 // indirect + github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.20 // indirect + github.com/aws/aws-sdk-go-v2/credentials v1.20.12 // indirect + github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.20.5 // indirect + github.com/aws/aws-sdk-go-v2/feature/s3/transfermanager v0.4.3 // indirect + github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.8 // indirect + github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.8 // indirect + github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.8 // indirect + github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.23 // indirect + github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.11.2 // indirect + github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.8 // indirect + github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.20.2 // indirect + github.com/aws/aws-sdk-go-v2/service/s3 v1.111.0 // indirect + github.com/aws/aws-sdk-go-v2/service/signin v1.12.0 // indirect + github.com/aws/aws-sdk-go-v2/service/sso v1.39.0 // indirect + github.com/aws/aws-sdk-go-v2/service/ssooidc v1.44.0 // indirect + github.com/aws/aws-sdk-go-v2/service/sts v1.51.6 // indirect + github.com/aws/smithy-go v1.28.7 // indirect github.com/beorn7/perks v1.0.1 // indirect github.com/cenk/backoff v2.2.1+incompatible // indirect github.com/cespare/xxhash/v2 v2.3.0 // indirect - github.com/dustin/go-humanize v1.0.1 // indirect + github.com/dustin/go-humanize v1.1.0 // indirect github.com/ecosyste-ms/ecosystems-go v0.5.0 // indirect github.com/facebookgo/clock v0.0.0-20150410010913-600d898af40a // indirect - github.com/felixge/httpsnoop v1.1.0 // indirect github.com/git-pkgs/pom v0.1.8 // indirect + github.com/git-pkgs/vulns v0.2.4 // indirect github.com/github/go-spdx/v2 v2.7.0 // indirect github.com/go-logr/logr v1.4.4 // indirect github.com/go-logr/stdr v1.2.2 // indirect @@ -88,15 +88,14 @@ require ( github.com/google/s2a-go v0.1.9 // indirect github.com/google/uuid v1.6.0 // indirect github.com/google/wire v0.7.0 // indirect - github.com/googleapis/enterprise-certificate-proxy v0.3.18 // indirect - github.com/googleapis/gax-go/v2 v2.23.0 // indirect + github.com/googleapis/enterprise-certificate-proxy v0.3.21 // indirect + github.com/googleapis/gax-go/v2 v2.24.1 // indirect github.com/josharian/intern v1.0.0 // indirect - github.com/klauspost/compress v1.20.1 // indirect github.com/kylelemons/godebug v1.1.0 // indirect github.com/mailru/easyjson v0.7.7 // indirect github.com/mattn/go-isatty v0.0.24 // indirect github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect - github.com/ncruces/go-strftime v1.0.0 // indirect + github.com/ncruces/go-strftime v1.1.0 // indirect github.com/oapi-codegen/nullable v1.2.0 // indirect github.com/oapi-codegen/runtime v1.7.0 // indirect github.com/package-url/packageurl-go v0.1.7 // indirect @@ -108,26 +107,25 @@ require ( github.com/rogpeppe/go-internal v1.16.0 // indirect github.com/rs/dnscache v0.0.0-20230804202142-fc85eb664529 // indirect github.com/rubyist/circuitbreaker v2.2.1+incompatible // indirect - github.com/ulikunitz/xz v0.5.16 // indirect + github.com/vmihailenco/tagparser/v2 v2.0.0 // indirect go.opentelemetry.io/auto/sdk v1.2.1 // indirect - go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.69.0 // indirect - go.opentelemetry.io/otel v1.45.0 // indirect - go.opentelemetry.io/otel/metric v1.45.0 // indirect - go.opentelemetry.io/otel/sdk v1.45.0 // indirect - go.opentelemetry.io/otel/sdk/metric v1.45.0 // indirect - go.opentelemetry.io/otel/trace v1.45.0 // indirect + go.opentelemetry.io/otel v1.46.0 // indirect + go.opentelemetry.io/otel/metric v1.46.0 // indirect + go.opentelemetry.io/otel/sdk v1.46.0 // indirect + go.opentelemetry.io/otel/sdk/metric v1.46.0 // indirect + go.opentelemetry.io/otel/trace v1.46.0 // indirect go.yaml.in/yaml/v3 v3.0.5 // indirect - golang.org/x/crypto v0.57.0 // indirect + golang.org/x/crypto v0.58.0 // indirect golang.org/x/oauth2 v0.37.0 // indirect - golang.org/x/sys v0.48.0 // indirect - golang.org/x/text v0.42.0 // indirect - golang.org/x/tools v0.50.0 // indirect + golang.org/x/sys v0.49.0 // indirect + golang.org/x/text v0.43.0 // indirect + golang.org/x/tools v0.52.0 // indirect golang.org/x/xerrors v0.0.0-20240903120638-7835f813f4da // indirect - google.golang.org/api v0.288.0 // indirect - google.golang.org/genproto/googleapis/rpc v0.0.0-20260706201446-f0a921348800 // indirect + google.golang.org/api v0.297.0 // indirect + google.golang.org/genproto/googleapis/rpc v0.0.0-20260904194346-d0f1323225a4 // indirect google.golang.org/grpc v1.83.2 // indirect gopkg.in/yaml.v2 v2.4.0 // indirect - modernc.org/libc v1.77.1 // indirect + modernc.org/libc v1.79.0 // indirect modernc.org/mathutil v1.7.1 // indirect modernc.org/memory v1.12.1 // indirect ) diff --git a/go.sum b/go.sum index d2ed244..cb9226b 100644 --- a/go.sum +++ b/go.sum @@ -1,48 +1,46 @@ -cel.dev/expr v0.25.2 h1:K6j46C81hXtZQfuX60cVWQFBJahKSE2gfRbNuvr5bFs= -cel.dev/expr v0.25.2/go.mod h1:hrXvqGP6G6gyx8UAHSHJ5RGk//1Oj5nXQ2NI02Nrsg4= +cel.dev/expr v0.25.3 h1:A2jO8jwOugrrovveCWfj0KEZOfqiLgAcwjpHPhzIGw0= +cel.dev/expr v0.25.3/go.mod h1:hrXvqGP6G6gyx8UAHSHJ5RGk//1Oj5nXQ2NI02Nrsg4= cloud.google.com/go v0.123.0 h1:2NAUJwPR47q+E35uaJeYoNhuNEM9kM8SjgRgdeOJUSE= cloud.google.com/go v0.123.0/go.mod h1:xBoMV08QcqUGuPW65Qfm1o9Y4zKZBpGS+7bImXLTAZU= -cloud.google.com/go/auth v0.21.0 h1:g/QwYfYb2Ai6HH8oomAOyBaIHLbscZ4+T/F/f5JZHkE= -cloud.google.com/go/auth v0.21.0/go.mod h1:M9o2Oz+YI2jAfxewJgb1vyI3vceHF+eohmxyzmrl+9s= +cloud.google.com/go/auth v0.23.2 h1:pxSCpfiji41hpzpPdMCftEUCezpgpqmmDdYiAjCKXxo= +cloud.google.com/go/auth v0.23.2/go.mod h1:4DhBRcqvtljQN3dJ57qtqbib5ZGCYE5f2crfiiC2EM0= cloud.google.com/go/auth/oauth2adapt v0.2.8 h1:keo8NaayQZ6wimpNSmW5OPc283g65QNIiLpZnkHRbnc= cloud.google.com/go/auth/oauth2adapt v0.2.8/go.mod h1:XQ9y31RkqZCcwJWNSx2Xvric3RrU88hAYYbjDWYDL+c= cloud.google.com/go/compute/metadata v0.9.0 h1:pDUj4QMoPejqq20dK0Pg2N4yG9zIkYGdBtwLoEkH9Zs= cloud.google.com/go/compute/metadata v0.9.0/go.mod h1:E0bWwX5wTnLPedCKqk3pJmVgCBSM6qQI1yTBdEb3C10= -cloud.google.com/go/iam v1.5.3 h1:+vMINPiDF2ognBJ97ABAYYwRgsaqxPbQDlMnbHMjolc= -cloud.google.com/go/iam v1.5.3/go.mod h1:MR3v9oLkZCTlaqljW6Eb2d3HGDGK5/bDv93jhfISFvU= -cloud.google.com/go/monitoring v1.24.3 h1:dde+gMNc0UhPZD1Azu6at2e79bfdztVDS5lvhOdsgaE= -cloud.google.com/go/monitoring v1.24.3/go.mod h1:nYP6W0tm3N9H/bOw8am7t62YTzZY+zUeQ+Bi6+2eonI= -cloud.google.com/go/storage v1.61.3 h1:VS//ZfBuPGDvakfD9xyPW1RGF1Vy3BWUoVZXgW1KMOg= -cloud.google.com/go/storage v1.61.3/go.mod h1:JtqK8BBB7TWv0HVGHubtUdzYYrakOQIsMLffZ2Z/HWk= +cloud.google.com/go/iam v1.13.0 h1:ufT3FPT5rFFXu6UtLkNoxaOaV5EuA1dsSkmemCSTo6U= +cloud.google.com/go/iam v1.13.0/go.mod h1:gHXdDEiPDvqd1q1KwBDGQlgZY/BwY760zU2LhOZS5w0= +cloud.google.com/go/monitoring v1.30.0 h1:r/d+JUbyKmJ8b07iznuKfzVzrIXTWxHQ3lBRm3x2LlY= +cloud.google.com/go/monitoring v1.30.0/go.mod h1:htlUR0QWVMrjFzZmN4LGnMAve9xB/eduwjmINxVZ8RM= +cloud.google.com/go/storage v1.67.0 h1:8xD3NvKuHE4c+b/kmSIVBdTc0BiOjplx+KecKGR9fr8= +cloud.google.com/go/storage v1.67.0/go.mod h1:UsS9OgFg/XHOSYakQ8ZtLWWeyGkk1WnmD/GsGfN0BHM= filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4= filippo.io/edwards25519 v1.2.0 h1:crnVqOiS4jqYleHd9vaKZ+HKtHfllngJIiOpNpoJsjo= filippo.io/edwards25519 v1.2.0/go.mod h1:xzAOLCNug/yB62zG1bQ8uziwrIqIuxhctzJT18Q77mc= -github.com/Azure/azure-sdk-for-go/sdk/azcore v1.21.0 h1:fou+2+WFTib47nS+nz/ozhEBnvU96bKHy6LjRsY4E28= -github.com/Azure/azure-sdk-for-go/sdk/azcore v1.21.0/go.mod h1:t76Ruy8AHvUAC8GfMWJMa0ElSbuIcO03NLpynfbgsPA= -github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.13.1 h1:Hk5QBxZQC1jb2Fwj6mpzme37xbCDdNTxU7O9eb5+LB4= -github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.13.1/go.mod h1:IYus9qsFobWIc2YVwe/WPjcnyCkPKtnHAqUYeebc8z0= -github.com/Azure/azure-sdk-for-go/sdk/azidentity/cache v0.3.2 h1:yz1bePFlP5Vws5+8ez6T3HWXPmwOK7Yvq8QxDBD3SKY= -github.com/Azure/azure-sdk-for-go/sdk/azidentity/cache v0.3.2/go.mod h1:Pa9ZNPuoNu/GztvBSKk9J1cDJW6vk/n0zLtV4mgd8N8= -github.com/Azure/azure-sdk-for-go/sdk/internal v1.11.2 h1:9iefClla7iYpfYWdzPCRDozdmndjTm8DXdpCzPajMgA= -github.com/Azure/azure-sdk-for-go/sdk/internal v1.11.2/go.mod h1:XtLgD3ZD34DAaVIIAyG3objl5DynM3CQ/vMcbBNJZGI= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.23.1 h1:zvXfGJCWvywnCA814d8ZiVyt+fm9nnTE8xSb99zRyfo= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.23.1/go.mod h1:iptorS+VYKFL2N6PnebpS91dubG35eAOEERnT4PJbQU= +github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.14.1 h1:u93s+zU2JD62im61Bm5CZIc1ZrOJaIAWEg0WOrMVkEo= +github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.14.1/go.mod h1:oXtinPO4OLj9d1DOTrqrL1oRwGhcqadvAmrl6wTeGlk= +github.com/Azure/azure-sdk-for-go/sdk/azidentity/cache v0.4.0 h1:xFaZZ+IubdftrDHnGGwZ6QvQ3KHTtWl2MCK+GMt2vxs= +github.com/Azure/azure-sdk-for-go/sdk/azidentity/cache v0.4.0/go.mod h1:mCBhUhlMjLLJKr5aqw2TNS/VqJOie8MzWq3DAMJeKso= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage v1.8.1 h1:/Zt+cDPnpC3OVDm/JKLOs7M2DKmLRIIp3XIx9pHHiig= github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage v1.8.1/go.mod h1:Ng3urmn6dYe8gnbCMoHHVl5APYz2txho3koEkV2o2HA= -github.com/Azure/azure-sdk-for-go/sdk/storage/azblob v1.6.4 h1:jWQK1GI+LeGGUKBADtcH2rRqPxYB1Ljwms5gFA2LqrM= -github.com/Azure/azure-sdk-for-go/sdk/storage/azblob v1.6.4/go.mod h1:8mwH4klAm9DUgR2EEHyEEAQlRDvLPyg5fQry3y+cDew= +github.com/Azure/azure-sdk-for-go/sdk/storage/azblob v1.8.0 h1:irsmOWwkp0KCTTNS5e2hdFeIvSQClQo2No3IaNmL3Vw= +github.com/Azure/azure-sdk-for-go/sdk/storage/azblob v1.8.0/go.mod h1:GWcBkQj3MqN7ozHKLaCCAuNLiXoIGv2RtanfAwSjY/Y= github.com/AzureAD/microsoft-authentication-extensions-for-go/cache v0.1.1 h1:WJTmL004Abzc5wDB5VtZG2PJk5ndYDgVacGqfirKxjM= github.com/AzureAD/microsoft-authentication-extensions-for-go/cache v0.1.1/go.mod h1:tCcJZ0uHAmvjsVYzEFivsRTN00oz5BEsRgQHu5JZ9WE= -github.com/AzureAD/microsoft-authentication-library-for-go v1.7.0 h1:4iB+IesclUXdP0ICgAabvq2FYLXrJWKx1fJQ+GxSo3Y= -github.com/AzureAD/microsoft-authentication-library-for-go v1.7.0/go.mod h1:HKpQxkWaGLJ+D/5H8QRpyQXA1eKjxkFlOMwck5+33Jk= +github.com/AzureAD/microsoft-authentication-library-for-go v1.9.0 h1:MDT4FxAPve5FnYn6vOL1r7RCRDG+l9cI7a5LlCuHsqA= +github.com/AzureAD/microsoft-authentication-library-for-go v1.9.0/go.mod h1:Y33QHnf0FfdVewFFISOGe20mkZbxX4H839o955/PoeI= github.com/BurntSushi/toml v1.6.0 h1:dRaEfpa2VI55EwlIW72hMRHdWouJeRF7TPYhI+AUQjk= github.com/BurntSushi/toml v1.6.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho= -github.com/CycloneDX/cyclonedx-go v0.12.0 h1:/7Jum36UA6V043tQZ/fE3jf+Nf9gn/qxUFfd7QReMy8= -github.com/CycloneDX/cyclonedx-go v0.12.0/go.mod h1:V2577HhxDDCDLYfkm55WJrz16nHTfyQZwcWUBSG7Z28= -github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.33.0 h1:l7+6kwRMJNwdCvYdDl7Eax+wzEYHSnNY7zrrfbhDdTA= -github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.33.0/go.mod h1:pJTkW8hEUIIi3Pf65lPZOnn4Y81yCllX6IWk2jNXdkM= -github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.55.0 h1:UnDZ/zFfG1JhH/DqxIZYU/1CUAlTUScoXD/LcM2Ykk8= -github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.55.0/go.mod h1:IA1C1U7jO/ENqm/vhi7V9YYpBsp+IMyqNrEN94N7tVc= -github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapping v0.55.0 h1:0s6TxfCu2KHkkZPnBfsQ2y5qia0jl3MMrmBhu3nCOYk= -github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapping v0.55.0/go.mod h1:Mf6O40IAyB9zR/1J8nGDDPirZQQPbYJni8Yisy7NTMc= +github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.37.0 h1:edOuLWehuDlQ68roBF900Y09jvBoJP5W5d/wusz9nWY= +github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.37.0/go.mod h1:iIyrdhveU5Ow84ipRlxtjCOQnIM0DiqSMxuxm50xwZY= +github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.61.0 h1:BeC1Bub7Ttk33TF8v3ZeQ2L8acvz4ZLqtQuLyJAZquc= +github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.61.0/go.mod h1:UgG/Xn9+NXb1/ueSczIFxyuya3hs3srFDiZG2JrpJwY= +github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapping v0.61.0 h1:KhpL26/GviYITHMCEGGqT/l50siFaBCBBKrjv6Z0G/k= +github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapping v0.61.0/go.mod h1:sg6Wqbl0BKKZ5zKnQj2q0qic/3ziF894SCx1LpbX37Y= github.com/KyleBanks/depth v1.2.1 h1:5h8fQADFrWtarTdtDudMmGsC7GPbOAu6RVB3ffsVFHc= github.com/KyleBanks/depth v1.2.1/go.mod h1:jzSb9d0L43HxTQfT+oSA1EEp2q+ne2uh6XgeJcm8brE= github.com/Masterminds/semver/v3 v3.5.0 h1:kQceYJfbupGfZOKZQg0kou0DgAKhzDg2NZPAwZ/2OOE= @@ -52,55 +50,51 @@ github.com/PuerkitoBio/purell v1.1.1/go.mod h1:c11w/QuzBsJSee3cPx9rAFu61PvFxuPbt github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578 h1:d+Bc7a5rLufV/sSk/8dngufqelfh6jnri85riMAaF/M= github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578/go.mod h1:uGdkoq3SwY9Y+13GIhn11/XLaGBb4BfwItxLd5jeuXE= github.com/RaveNoX/go-jsoncommentstrip v1.0.0/go.mod h1:78ihd09MekBnJnxpICcwzCMzGrKSKYe4AqU6PDYYpjk= -github.com/anchore/go-struct-converter v0.1.0 h1:2rDRssAl6mgKBSLNiVCMADgZRhoqtw9dedlWa0OhD30= -github.com/anchore/go-struct-converter v0.1.0/go.mod h1:rYqSE9HbjzpHTI74vwPvae4ZVYZd1lue2ta6xHPdblA= github.com/apapsch/go-jsonmerge/v2 v2.0.0 h1:axGnT1gRIfimI7gJifB699GoE/oq+F2MU7Dml6nw9rQ= github.com/apapsch/go-jsonmerge/v2 v2.0.0/go.mod h1:lvDnEdqiQrp0O42VQGgmlKpxL1AP2+08jFMw88y4klk= -github.com/aws/aws-sdk-go-v2 v1.47.1 h1:uOIZnp4PK3ZhKI0dNrJrhTEsLxbpXHTAJlwoS1pvAtw= -github.com/aws/aws-sdk-go-v2 v1.47.1/go.mod h1:bttEH6JqnUL8LepvDVfdrds/fZ5bCIxzpe3abyUrhDU= -github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.11 h1:h5+3VT69KUBK24grGuuA5saDJTj2IIjLb9au668Fo5I= -github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.11/go.mod h1:dnakxebH6UwFvcvujL0LVggYQ8nEvBGjU4G/V79Nv94= -github.com/aws/aws-sdk-go-v2/config v1.33.7 h1:vgG8uuhm7vNsxr6BsXNG+Ciesh9iLdNPzarAAu/dB6A= -github.com/aws/aws-sdk-go-v2/config v1.33.7/go.mod h1:5KWNY38altxnd5cxcNoOTrFtJ7asFEiCiWfb2m+M2pE= -github.com/aws/aws-sdk-go-v2/credentials v1.20.7 h1:mit8rRVnmt+wvT4U6putiWSlwe3eKD2n6ElgyfcP/Mw= -github.com/aws/aws-sdk-go-v2/credentials v1.20.7/go.mod h1:/2pPi2qhPug21z6l3M0+AKUqAT1zn2MhRCtnQv8R5Zg= -github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.20.1 h1:8gALAAmacnIXh+z6VkdDanv4/IkG5APdg4DZLDTmLog= -github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.20.1/go.mod h1:Z7IJhJU+poOdJjUR2wpyY21ossQ1XS/R3Lk9Msq5kM4= -github.com/aws/aws-sdk-go-v2/feature/s3/transfermanager v0.2.3 h1:w5OoDiMN6x53ROmiIImGzmVcxXv2q1GXY+aKV4WAJYM= -github.com/aws/aws-sdk-go-v2/feature/s3/transfermanager v0.2.3/go.mod h1:dAhgYp776bX3LuWvnSCFwQEjNs6fuFg7YXIy5PXcP3Q= -github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.4 h1:CLq4+8UHCI+ZZYl/EuJxXovaIVN2xeeT8JV+dsApQ5E= -github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.4/go.mod h1:Wv4q5sAM04xAMkoOedxLx2inVf6K5FdxYp+A61L+q/0= -github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.4 h1:dD4MR81I7YkpEBRk6UP9rocC2QnT3qVuXwzlYTtfGEs= -github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.4/go.mod h1:EcXV1kAFd5XwSkDHlj94gnF3q5CkJyYiIJfH8N0VmrE= -github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.4 h1:7Wo47d/xn/7KttCSBd8EGYeZ7ULRFRkUHr6vkZPBzVQ= -github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.4/go.mod h1:tDB2IVC1xC3vX8o+6uRlzhTxP3g1b77CZXFX/oD2FnQ= -github.com/aws/aws-sdk-go-v2/service/ecr v1.66.2 h1:SNECRj8ZN0qPG1L33dLnqQ4EfmIQkGcFW7cv4Obw28M= -github.com/aws/aws-sdk-go-v2/service/ecr v1.66.2/go.mod h1:WglfLchOYcHrYOwNV7jERuy0Xc+7jArLkEnQay93auY= -github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.19 h1:bAdDl/HkGCcGPoe25ToSHEw23VIxt6CT5fLcg111BKg= -github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.19/go.mod h1:KaUzbLxv4CeSxh6ZCl9B4m7CuFenS8kUEaDs+f/DQr4= -github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.18 h1:W/EyPFl9A5rXrtoilfwHYEvzHER+K4SpBPtMXi24Mos= -github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.18/go.mod h1:UG50K+pvd/uy6xExbobg0rjqFBFZe6I3l75EPDZw4tg= -github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.4 h1:29SvnfGhXjTl8ONxFwbj2rs6lbhiFXD2CgFQmbT/bXY= -github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.4/go.mod h1:wm04I5DMuNVvZHFe/dHnUxincvNbbK7AiNBbYsQivek= -github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.25 h1:2pQEbwf+/6EDbiit/GcBE2K4IUpMZymaA0kOz3xK978= -github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.25/go.mod h1:KvT6NCcQ0EZ+ZkVRrlBMt04Po3ok23YELEp7WimhLhM= -github.com/aws/aws-sdk-go-v2/service/s3 v1.102.2 h1:ie4ElCmUKS26pzrZcIk/lmt4yWjAqLLcawstyQCh298= -github.com/aws/aws-sdk-go-v2/service/s3 v1.102.2/go.mod h1:zjsomFeX5duj+4PlMB+o4JoWTIx+G0XMyzjYrUbQkN0= -github.com/aws/aws-sdk-go-v2/service/signin v1.10.2 h1:vrPP4O9VABnquYrDHfU+Fu0Fp6TuzaqPUu9Fh7VBBVY= -github.com/aws/aws-sdk-go-v2/service/signin v1.10.2/go.mod h1:xpo/geVldu8payT375WekctUzopG/hBU7miiqItMUlw= -github.com/aws/aws-sdk-go-v2/service/sso v1.38.2 h1:I8F/K5ahKJ4npqeGBBmMPftQy3/o1A55VRq2eUcP9Ts= -github.com/aws/aws-sdk-go-v2/service/sso v1.38.2/go.mod h1:rRD/dnm7q0HYE/I5TMaPgkWyyUGLcwuxHLABsLnQ3e0= -github.com/aws/aws-sdk-go-v2/service/ssooidc v1.43.2 h1:i5nn7Ri5CgFfNRzwlUiZOIIUA+5Vgg+unNEC0PzF1+s= -github.com/aws/aws-sdk-go-v2/service/ssooidc v1.43.2/go.mod h1:skwM/xsbR/1ReUTesv9BhpJp1VjajR7DWQnuVLwiXsQ= -github.com/aws/aws-sdk-go-v2/service/sts v1.51.2 h1:AWSPqynwEJV8J2pl/p7aizCf7a23/NGHR+rK/KLOxi4= -github.com/aws/aws-sdk-go-v2/service/sts v1.51.2/go.mod h1:26zA0GhDrLo+yiLI2yXWxqB1PdsShfLikoI7GOEgugM= -github.com/aws/smithy-go v1.28.1 h1:R/nXH00c8qcfCzQVELtRw+eLQWtzv+VAIEFJ1/xxXlQ= -github.com/aws/smithy-go v1.28.1/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqxX9i1Fc= +github.com/aws/aws-sdk-go-v2 v1.47.5 h1:5yA+A+BiXbDq1ZLbYwPViwhEGDMdR0MEhL8Jh2LnLS4= +github.com/aws/aws-sdk-go-v2 v1.47.5/go.mod h1:iNIkogrRvFwm+1OQIUOP2lPBtlXZboOIUWiCa+pHEMw= +github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.20 h1:GPRlPwz40I2B2VrBEASOA3Bi77NyeqejNLkifosX0rs= +github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.20/go.mod h1:g7PNzKcsOKWb4fkSRBA7BZVAS6Y8IcxzN+nRohhQ1Q8= +github.com/aws/aws-sdk-go-v2/config v1.33.12 h1:IV1YARaXahwCqUIyP8IlWsP85Lil+5ozTozDQXPumRk= +github.com/aws/aws-sdk-go-v2/config v1.33.12/go.mod h1:h51R06bzMVwNBRZOX5ylHhNDnkB/azZeq/LvxM6q2pQ= +github.com/aws/aws-sdk-go-v2/credentials v1.20.12 h1:6P7Q7yH/GIwHg6MLKv3ySsBqaCoE1z+C0OTzYMenhEY= +github.com/aws/aws-sdk-go-v2/credentials v1.20.12/go.mod h1:Kw/SaoW/wc7IqJErqXJIzKo8b7Aelxfbuc6XlbrRnsc= +github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.20.5 h1:iXjy2SFhGYNB1jWZBhQqq8HbhsbPF23w+/zbMvPXsTg= +github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.20.5/go.mod h1:k0RUiBnyXU0AXRJ9tJmY2jQke6XUIX2PNVnWtvgaPtc= +github.com/aws/aws-sdk-go-v2/feature/s3/transfermanager v0.4.3 h1:vsFkmFrfzODkxVbyuPLscv5j5lC8KbG48LZwV+p56Y0= +github.com/aws/aws-sdk-go-v2/feature/s3/transfermanager v0.4.3/go.mod h1:pjQYVtvVBEtlsf2p6nXMsjPuDaWs9GM44FMdHbmnmYU= +github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.8 h1:gzIWc3DTPfPbWKrQnmL6BV6WD7NPD1htxzgdk/bQ/Z4= +github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.8/go.mod h1:vvUA5cDAZWGo4R14FZPZfXfJCmgsafOWEq78Kg0D+ug= +github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.8 h1:PWv+vG8aCLS8qd+HPdYhK7Vees90aKHWFFQ1AGYD/8E= +github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.8/go.mod h1:xxPZEpflYHJA12366ZGyq66z9dHPCoeCIu99Jck+MPw= +github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.8 h1:WOp5De9iWdEHDPh2Kb0tBP3vGBm/dVAuRGh4a4tqduo= +github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.8/go.mod h1:z8W8YgfhbWl62XqcTtK+CxPrE+iHGRVUOtrrbIOp7ZY= +github.com/aws/aws-sdk-go-v2/service/ecr v1.67.1 h1:EJlz0wSlZDKaCN2FHwg9RBR+C+gsuVdYblJnEnrq3M4= +github.com/aws/aws-sdk-go-v2/service/ecr v1.67.1/go.mod h1:6rVJFO9ZO+4j/QL5/FbtAsbb8xHC85j79wXA9ndOCTY= +github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.23 h1:MCIR6iZaCKO4UE0hUvoWWLI6JVjppopV64JfAJaMjng= +github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.23/go.mod h1:pphWFS+z0MmIPivj8c/6bATd1Z+Av7Ust75DPdEFsPA= +github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.11.2 h1:CO485zrLOZBeq8mrdsudc8cjyhvC4LY4JFt8ZfHvXZ0= +github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.11.2/go.mod h1:cBAjVUKBr+5wnx1K3XWS8u5AZsqpA2S/0z7YtI6BGFc= +github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.8 h1:+PMpWlJYOn2tm7sm6OZ/ZLd4jStl17T7wjNapd1Rczs= +github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.8/go.mod h1:cnG3xZLGQL4c/bt8pjdzlFtZsW7epBBuNS04a5xMjdo= +github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.20.2 h1:Enx5JcIy/o90kio1LFZ/HguxIsos3clbGuSpGdyshX8= +github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.20.2/go.mod h1:Ldmll8/2VqaVerWWDf8IGG+6pAvZY04gs3tevq3nIFs= +github.com/aws/aws-sdk-go-v2/service/s3 v1.111.0 h1:4PokON/ISKuD6Zl062n4WfQNnEFBMHvfeJy73Jp7K+g= +github.com/aws/aws-sdk-go-v2/service/s3 v1.111.0/go.mod h1:6ZFrmv/qIAYFmG+2WhA7mFU8+edldRlISwT+tNnyLuA= +github.com/aws/aws-sdk-go-v2/service/signin v1.12.0 h1:3vu/eUqh0rjh7Zy4N4YKcpZX4Aud+zinB3VsLhhlQFw= +github.com/aws/aws-sdk-go-v2/service/signin v1.12.0/go.mod h1:wxAk0D2oVBSjuXEIzvcKxTZfM90zticdAbh/VD42L0Y= +github.com/aws/aws-sdk-go-v2/service/sso v1.39.0 h1:kIEpD5dUry7VET3Ybl7zj7PPHRB4lb52G9iTz+a1Tqk= +github.com/aws/aws-sdk-go-v2/service/sso v1.39.0/go.mod h1:UGsEYgWz4Gi+46vDQ5zkFLqUgJziyOE2SXjZjgmfmHc= +github.com/aws/aws-sdk-go-v2/service/ssooidc v1.44.0 h1:WfFev+HgTodggcNon5HieiLxxwWwb8Br8R2+nDkixvk= +github.com/aws/aws-sdk-go-v2/service/ssooidc v1.44.0/go.mod h1:gJSdIY6YUzDvqQLcMtPVZgBRHrFwzHryvpE8Igzbxps= +github.com/aws/aws-sdk-go-v2/service/sts v1.51.6 h1:BVjKrtRUtSYKztBCCfE1oAB+d3ViKcW2cKZfserOqMQ= +github.com/aws/aws-sdk-go-v2/service/sts v1.51.6/go.mod h1:eSukFLeLkPMm+1OxDR+F0joauZdyBkF47Ow7MqjZiJw= +github.com/aws/smithy-go v1.28.7 h1:h/n1SHrwVtaDYLz8mR1/Kq4Xh4RaFbFW7bOYckg9mfE= +github.com/aws/smithy-go v1.28.7/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqxX9i1Fc= github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= github.com/bmatcuk/doublestar v1.1.1/go.mod h1:UD6OnuiIn0yFxxA2le/rnRU1G4RaI4UvFv1sNto9p6w= -github.com/bradleyjkemp/cupaloy/v2 v2.8.0 h1:any4BmKE+jGIaMpnU8YgH/I2LPiLBufr6oMMlVBbn9M= -github.com/bradleyjkemp/cupaloy/v2 v2.8.0/go.mod h1:bm7JXdkRd4BHJk9HpwqAI8BoAY1lps46Enkdqw6aRX0= github.com/cenk/backoff v2.2.1+incompatible h1:djdFT7f4gF2ttuzRKPbMOWgZajgesItGLwG5FTQKmmE= github.com/cenk/backoff v2.2.1+incompatible/go.mod h1:7FtoeaSnHoZnmZzz47cM35Y9nSW7tNyaidugnHTaFDE= github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= @@ -110,41 +104,41 @@ github.com/cncf/xds/go v0.0.0-20260202195803-dba9d589def2/go.mod h1:qwXFYgsP6T7X github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= -github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY= -github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= +github.com/dustin/go-humanize v1.1.0 h1:dbKTrvD0klcbBV/h4AWJdMuZogJACoMlvWIWZ5b2xWg= +github.com/dustin/go-humanize v1.1.0/go.mod h1:hc1CvRkJMsgxqjmjMQF3QNRAZBwY8AXBAzKYoSX9sFI= github.com/ecosyste-ms/ecosystems-go v0.5.0 h1:qZqgar3Do9RrtW327OXlsrGKiRvNdeX8CmXb1aX4Njo= github.com/ecosyste-ms/ecosystems-go v0.5.0/go.mod h1:IhsYBZfxkofxya0O1O2DlhDt281utWJ6VQO0mPVb99I= github.com/envoyproxy/go-control-plane v0.14.0 h1:hbG2kr4RuFj222B6+7T83thSPqLjwBIfQawTkC++2HA= -github.com/envoyproxy/go-control-plane/envoy v1.37.0 h1:u3riX6BoYRfF4Dr7dwSOroNfdSbEPe9Yyl09/B6wBrQ= -github.com/envoyproxy/go-control-plane/envoy v1.37.0/go.mod h1:DReE9MMrmecPy+YvQOAOHNYMALuowAnbjjEMkkWOi6A= +github.com/envoyproxy/go-control-plane/envoy v1.39.0 h1:1uwRDYPYG8BIBU9Mj1sUAebNmlM6beu/ZKKweSLDxk8= +github.com/envoyproxy/go-control-plane/envoy v1.39.0/go.mod h1:5e4ylfTZO723MEEFsCpSW4ZEBWR8mwkEyXfwJBTCZ9c= github.com/envoyproxy/protoc-gen-validate v1.3.3 h1:MVQghNeW+LZcmXe7SY1V36Z+WFMDjpqGAGacLe2T0ds= github.com/envoyproxy/protoc-gen-validate v1.3.3/go.mod h1:TsndJ/ngyIdQRhMcVVGDDHINPLWB7C82oDArY51KfB0= github.com/facebookgo/clock v0.0.0-20150410010913-600d898af40a h1:yDWHCSQ40h88yih2JAcL6Ls/kVkSE8GFACTGVnMPruw= github.com/facebookgo/clock v0.0.0-20150410010913-600d898af40a/go.mod h1:7Ga40egUymuWXxAe151lTNnCv97MddSOVsjpPPkityA= github.com/felixge/httpsnoop v1.1.0 h1:3YtUj32ZZkqZtt3sZZsClsymw/QDuVfpNhoA31zeORc= github.com/felixge/httpsnoop v1.1.0/go.mod h1:Zqxgdd+1Rkcz8euOqdr7lqgCRJztwr5hp9vDSi5UZCE= -github.com/git-pkgs/archives v0.8.1 h1:IcT1bVsAec8SqJ4m9vTnD644KiadQZ4ERrWnm/30t3o= -github.com/git-pkgs/archives v0.8.1/go.mod h1:gIyPXPQr5e+YrMqA5KQ7x6pLrFXHNF1+CjdedNJdGUU= +github.com/git-pkgs/archives v0.10.0 h1:/qgk0MI6VK2sKOoVTd0B4zs5hwTo+St0X8cYYftzumc= +github.com/git-pkgs/archives v0.10.0/go.mod h1:GJ/h7NPTUYiPinOUxpYNsHFCUikYZcJXvugBvP1VGNc= github.com/git-pkgs/artifacts v0.2.1 h1:VwdxR4yTDaqBZ34h0slxQBVyr2Xfa+QGOKCKviMx2xk= github.com/git-pkgs/artifacts v0.2.1/go.mod h1:Otosgq52pXT5UNN7lh6s/lszpWKVDO8XrOjN1M70/IA= -github.com/git-pkgs/cooldown v0.2.0 h1:0MWPHtkzZgvCR0wdiQeyvMea/dxgw9tParH1zzaFopc= -github.com/git-pkgs/cooldown v0.2.0/go.mod h1:v7APuK/UouTiu8mWQZbdDmj7DfxxkGUeuhjaRB5gv9E= -github.com/git-pkgs/enrichment v0.7.2 h1:flD/M89HxkOegUi6tC8EOspFiIMsl7m0o576IQKOp48= -github.com/git-pkgs/enrichment v0.7.2/go.mod h1:xGyc/iz7u1UnbrOHk8lIX5ZaNF3mKFDEZc3VqBJ/LOk= +github.com/git-pkgs/cooldown v0.3.1 h1:XDt54+ZuYoJclTLysaQ2GUZPhYYuJdjpaqeLSwjMdto= +github.com/git-pkgs/cooldown v0.3.1/go.mod h1:FnTg8wufEALATC9Sm/9AHjLdA+u9eVn96e9BqXXjGB0= +github.com/git-pkgs/enrichment v0.7.5 h1:jbfFzf7+HSS7el8AuMri4vHXq2izIIZDVIU0uYI5LFM= +github.com/git-pkgs/enrichment v0.7.5/go.mod h1:TbxC/nGQN96YCbdoiDs8a9z3gk2zXmLVS1989/jvnsU= github.com/git-pkgs/gcs v0.1.0 h1:E3awGtsO0xZyHT9FUfEwMHjMkRxw41Bh+c7lgTmPvBo= github.com/git-pkgs/gcs v0.1.0/go.mod h1:bdkCFD66ryaWnU8MBhokVA3WkJfyAEchm9qec5woBpE= github.com/git-pkgs/integrity v0.2.0 h1:sxpAk7EUllZnTYttOoPTW/Yfe5J2imglpuJiuBUZOxM= github.com/git-pkgs/integrity v0.2.0/go.mod h1:vPLb2RB+hR/iCMIgqph0PZbQ7iktXDTK+uupoHQikKk= -github.com/git-pkgs/magic v0.5.0 h1:Pm+4fkHR+K6kg9pwJM4hnwWUuBlkYdLmF1yIAI8lU9Q= -github.com/git-pkgs/magic v0.5.0/go.mod h1:SXOqcsNmbmpZjJZHEEWnwxprbsFvpwWgTAZrgXp4Jm4= +github.com/git-pkgs/magic v0.6.0 h1:fINPe67FEIaFRVlZzhOIDClMkm+gftBroBENa8bHSxQ= +github.com/git-pkgs/magic v0.6.0/go.mod h1:SXOqcsNmbmpZjJZHEEWnwxprbsFvpwWgTAZrgXp4Jm4= github.com/git-pkgs/pom v0.1.8 h1:mXCuWw6XkrKKZb6IurRZyIznYLPhV5AYg5ZO38Uj/l8= github.com/git-pkgs/pom v0.1.8/go.mod h1:sQBeYRzjCUn77fcABPn6I/a1aBHFxm55jTmkNxYtGtw= -github.com/git-pkgs/purl v0.1.21 h1:PDZUX43lxIiXPn2eHcsNiiiwQo+HajntZ/4TwSvCGlw= -github.com/git-pkgs/purl v0.1.21/go.mod h1:4dOmris48ehjiKmWBqSmMHguUQht48BLeXW+hQUnuj0= -github.com/git-pkgs/registries v0.9.3 h1:nXIP//6kVqLKqYXOWhEMoWUkJPDAZYVLRUYfHz3jM2Y= -github.com/git-pkgs/registries v0.9.3/go.mod h1:BpXlfRCfu4S5bTzm7u7igppVu94mXgll/PENe0AjKmI= +github.com/git-pkgs/purl v0.2.1 h1:b46hRlOMbrG6aXjjFJdYixGi5WTh0TLlAnH9iNeuOS0= +github.com/git-pkgs/purl v0.2.1/go.mod h1:l8rCfvt5iXVrFIcoQ8+vCLOaHhrtEW2id0LENP+IzMw= +github.com/git-pkgs/registries v0.13.0 h1:5i9dHnbiXseIbXLIZ61YnuFySJ9dQX+KEu1MrmwB2BU= +github.com/git-pkgs/registries v0.13.0/go.mod h1:1g/jXVi1M/3jWvW1Wom1NMnPrhglJ7UVEZ215l2Zh0M= +github.com/git-pkgs/sbom v0.1.9 h1:sfF5cJAwmgrm2N4HTXQWjiBe8tdu8xwhjwfAOyDNMfc= +github.com/git-pkgs/sbom v0.1.9/go.mod h1:KIkZX0v31l62SeFsi2qsQXcZRVrAXvIdPQ4x4en+G2M= github.com/git-pkgs/spdx v0.3.3 h1:xXlUoZzjDSkwxC6mWHfaW+kc8a0+LH6d+gGHuZWftqI= github.com/git-pkgs/spdx v0.3.3/go.mod h1:n9rAicgw+Wqtfursju6oKaAL6cUCTiIS926mb1KWoKU= github.com/git-pkgs/vers v0.7.2 h1:Ctex1O+Ai/FONmyDaw37EolBXg0og6UdxbCjjYbeRHs= @@ -153,10 +147,10 @@ github.com/git-pkgs/vulns v0.2.4 h1:QnsQg9sWUfM8ZzA7A/1LSl8DJ/0/6Yrm7vfRwkpyXUY= github.com/git-pkgs/vulns v0.2.4/go.mod h1:csd+UWvmYWVVAkka7FNbyz840/1R3QXS7LwD2Irsf4Q= github.com/github/go-spdx/v2 v2.7.0 h1:GzfXx4wFdlilARxmFRXW/mgUy3A4vSqZocCMFV6XFdQ= github.com/github/go-spdx/v2 v2.7.0/go.mod h1:Ftc45YYG1WzpzwEPKRVm9Jv8vDqOrN4gWoCkK+bHer0= -github.com/go-chi/chi/v5 v5.3.2 h1:5YQkICvTCSZ25hoRsyJazN0scjzKGiu4VAUc7H1o1nY= -github.com/go-chi/chi/v5 v5.3.2/go.mod h1:R+tYY2hNuVUUjxoPtqUdgBqevM9s9njzkTLutVsOCto= -github.com/go-jose/go-jose/v4 v4.1.4 h1:moDMcTHmvE6Groj34emNPLs/qtYXRVcd6S7NHbHz3kA= -github.com/go-jose/go-jose/v4 v4.1.4/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08= +github.com/go-chi/chi/v5 v5.5.0 h1:xdKQ1dJmVJsmgahrXSKhUx8NyVPzpwdlyrrQFpMPJgg= +github.com/go-chi/chi/v5 v5.5.0/go.mod h1:d1IG7GtKPSjPyBP365PH8sAGVHk3qfB/IhjFNRH1wWM= +github.com/go-jose/go-jose/v4 v4.1.5 h1:RjgjO2LOtWOJKUC5wpwY9LR3B3vwVAz6JS2YHfYU6eA= +github.com/go-jose/go-jose/v4 v4.1.5/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08= github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= github.com/go-logr/logr v1.4.4 h1:tG4xh9yMsRCAiodLVTxyrkzSZ9+o0L1Kg/+cPVcbP/8= github.com/go-logr/logr v1.4.4/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= @@ -173,32 +167,32 @@ github.com/go-openapi/swag v0.19.5/go.mod h1:POnQmlKehdgb5mhVOsnJFsivZCEZ/vjK9gh github.com/go-openapi/swag v0.19.15 h1:D2NRCBzS9/pEY3gP9Nl8aDqGUcPFrwG2p+CNFrLyrCM= github.com/go-openapi/swag v0.19.15/go.mod h1:QYRuS/SOXUCsnplDa677K7+DxSOj6IPNl/eQntq43wQ= github.com/go-sql-driver/mysql v1.8.1/go.mod h1:wEBSXgmK//2ZFJyE+qWnIsVGmvmEKlqwuVSjsCm7DZg= -github.com/go-sql-driver/mysql v1.9.3 h1:U/N249h2WzJ3Ukj8SowVFjdtZKfu9vlLZxjPXV1aweo= -github.com/go-sql-driver/mysql v1.9.3/go.mod h1:qn46aNg1333BRMNU69Lq93t8du/dwxI64Gl8i5p1WMU= +github.com/go-sql-driver/mysql v1.10.1 h1:arlSnNLq6a5yxGxV7qg9lF4j0C+KwD6NbQyKr9QL6ME= +github.com/go-sql-driver/mysql v1.10.1/go.mod h1:M+cqaI7+xxXGG9swrdeUIoPG3Y3KCkF0pZej+SK+nWk= github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY= github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE= github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek= github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps= github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= -github.com/google/go-replayers/grpcreplay v1.3.0 h1:1Keyy0m1sIpqstQmgz307zhiJ1pV4uIlFds5weTmxbo= -github.com/google/go-replayers/grpcreplay v1.3.0/go.mod h1:v6NgKtkijC0d3e3RW8il6Sy5sqRVUwoQa4mHOGEy8DI= +github.com/google/go-replayers/grpcreplay v1.5.1 h1:R90FMYaA6GQNhi/GG0D4zS14HEQ+wpO8bQAV0Qwyt08= +github.com/google/go-replayers/grpcreplay v1.5.1/go.mod h1:42YCe31fkUrhRo+haVAfLse+gNqGI1iO1wdNR+sWY9U= github.com/google/go-replayers/httpreplay v1.2.0 h1:VM1wEyyjaoU53BwrOnaf9VhAyQQEEioJvFYxYcLRKzk= github.com/google/go-replayers/httpreplay v1.2.0/go.mod h1:WahEFFZZ7a1P4VM1qEeHy+tME4bwyqPcwWbNlUI1Mcg= github.com/google/martian/v3 v3.3.3 h1:DIhPTQrbPkgs2yJYdXU/eNACCG5DVQjySNRNlflZ9Fc= github.com/google/martian/v3 v3.3.3/go.mod h1:iEPrYcgCF7jA9OtScMFQyAlZZ4YXTKEtJ1E6RWzmBA0= -github.com/google/pprof v0.0.0-20260802141513-ef3492d7dac3 h1:LMLX+LgTNWpfvCBdFebv6EsYotImrt/Ppc5cXIriCSo= -github.com/google/pprof v0.0.0-20260802141513-ef3492d7dac3/go.mod h1:jl5iWTm0/hd5PjEYEOuwAJ57L/CibdZfrqZ5XA5GrCk= +github.com/google/pprof v0.0.0-20261016150608-1facf8f91b50 h1:PlNWJRxu5APSV0pWqfIsZ0qt9OOGHSWfZQ4zvx+WgWs= +github.com/google/pprof v0.0.0-20261016150608-1facf8f91b50/go.mod h1:yUo1AMMpsPIDFGuwDK8nLcf8+vvAd5l2O6JDZ6hpwrM= github.com/google/s2a-go v0.1.9 h1:LGD7gtMgezd8a/Xak7mEWL0PjoTQFvpRudN895yqKW0= github.com/google/s2a-go v0.1.9/go.mod h1:YA0Ei2ZQL3acow2O62kdp9UlnvMmU7kA6Eutn0dXayM= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/wire v0.7.0 h1:JxUKI6+CVBgCO2WToKy/nQk0sS+amI9z9EjVmdaocj4= github.com/google/wire v0.7.0/go.mod h1:n6YbUQD9cPKTnHXEBN2DXlOp/mVADhVErcMFb0v3J18= -github.com/googleapis/enterprise-certificate-proxy v0.3.18 h1:hvVi34VucdrV1IIsiWuqYM8kutw/92MxNEFxCJZEh0k= -github.com/googleapis/enterprise-certificate-proxy v0.3.18/go.mod h1:rSEsBUemEBZEexP2y6jPp16LUmUbjmSbcPMQizR0o4k= -github.com/googleapis/gax-go/v2 v2.23.0 h1:Tchl7qkvE7Ip3y+ztvNufYFvkfqTe7NfLTYGIdJRLuE= -github.com/googleapis/gax-go/v2 v2.23.0/go.mod h1:rBQKOVJCdb8IFEzg+FCwlt1LP/xMDGuqUXhUG+XMXEg= +github.com/googleapis/enterprise-certificate-proxy v0.3.21 h1:OFdQ3tnCX/zaQ0Cedur3D3z7kI6HiLX9g3TiAN4/DFU= +github.com/googleapis/enterprise-certificate-proxy v0.3.21/go.mod h1:L3D/IQExI6LqEjBdXcZQ1WluSgigQmSwBboFstVPM4w= +github.com/googleapis/gax-go/v2 v2.24.1 h1:AtqTN21IXMMWo99LiEVAiBfNNQmO40d8xUfZI640mc0= +github.com/googleapis/gax-go/v2 v2.24.1/go.mod h1:bWeBei0NVwaNZKb2y1HUBS7gLXIF3/Tu3pq7j8D2Tb0= github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k= github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM= github.com/jmoiron/sqlx v1.4.0 h1:1PLqN7S1UYp5t4SrVVnt4nUVNemrDAtxlulVe+Qgm3o= @@ -208,8 +202,8 @@ github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFF github.com/juju/gnuflag v0.0.0-20171113085948-2ce1bb71843d/go.mod h1:2PavIy+JPciBPrBUjwbNvtwB6RQlve+hkpll6QSNmOE= github.com/keybase/go-keychain v0.0.1 h1:way+bWYa6lDppZoZcgMbYsvC7GxljxrskdNInRtuthU= github.com/keybase/go-keychain v0.0.1/go.mod h1:PdEILRW3i9D8JcdM+FmY6RwkHGnhHxXwkPPMeUgOK1k= -github.com/klauspost/compress v1.20.1 h1:T7kKElXUMXrUJ2E9QhQhxFtcK5rPyLdsGZvdbLMPdiQ= -github.com/klauspost/compress v1.20.1/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI= +github.com/klauspost/compress v1.20.3 h1:zWNoFqq/lSuYQRim3dUXlXeA0IqwuZGicdG5ZTfY5j4= +github.com/klauspost/compress v1.20.3/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI= github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= @@ -233,8 +227,8 @@ github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y= github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA= github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ= -github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w= -github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls= +github.com/ncruces/go-strftime v1.1.0 h1:vtPmPWMkb539RGV9WpWT9EwJGvrOCKvMNI4obWL47Hk= +github.com/ncruces/go-strftime v1.1.0/go.mod h1:yVaq7iwCN09vHRrKBrrflXT0M9tTMG2KmZ9Fj7xeG/g= github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno= github.com/oapi-codegen/nullable v1.2.0 h1:VflFkDW980KhBPiFF7nWSyjg+r4Obqj8lXipV0UkP5w= github.com/oapi-codegen/nullable v1.2.0/go.mod h1:KUZ3vUzkmEKY90ksAmit2+5juDIhIZhfDl+0PwOQlFY= @@ -253,8 +247,6 @@ github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c/go.mod h1:7rwL4CYBLnjL github.com/planetscale/vtprotobuf v0.6.1-0.20240319094008-0393e58bdf10 h1:GFCKgmp0tecUJ0sJuv4pzYCqS9+RGSn52M3FUwPs+uo= github.com/planetscale/vtprotobuf v0.6.1-0.20240319094008-0393e58bdf10/go.mod h1:t/avpk3KcrXxUnYOhZhMXJlSEyie6gQbtLq5NM3loB8= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= -github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/prometheus/client_golang v1.25.0 h1:cDtW1TcFsMi1RJc8khwCKB4VhzwV04aKqbYtNOXuiK0= github.com/prometheus/client_golang v1.25.0/go.mod h1:j2X/4/kaQHLPnmyEU8zjmkndo1T317VpCIQEml8LTKk= github.com/prometheus/client_model v0.6.3 h1:O0jaTVAYNxTHYInEPFJt5I3+sN8zqBtVMPTB1qyxiEo= @@ -271,10 +263,8 @@ github.com/rs/dnscache v0.0.0-20230804202142-fc85eb664529 h1:18kd+8ZUlt/ARXhljq+ github.com/rs/dnscache v0.0.0-20230804202142-fc85eb664529/go.mod h1:qe5TWALJ8/a1Lqznoc5BDHpYX/8HU60Hm2AwRmqzxqA= github.com/rubyist/circuitbreaker v2.2.1+incompatible h1:KUKd/pV8Geg77+8LNDwdow6rVCAYOp8+kHUyFvL6Mhk= github.com/rubyist/circuitbreaker v2.2.1+incompatible/go.mod h1:Ycs3JgJADPuzJDwffe12k6BZT8hxVi6lFK+gWYJLN4A= -github.com/spdx/tools-golang v0.5.7 h1:+sWcKGnhwp3vLdMqPcLdA6QK679vd86cK9hQWH3AwCg= -github.com/spdx/tools-golang v0.5.7/go.mod h1:jg7w0LOpoNAw6OxKEzCoqPC2GCTj45LyTlVmXubDsYw= -github.com/spiffe/go-spiffe/v2 v2.7.0 h1:uXe1MflJoHw58wAUvxVlcM7WpKtijWG7I1UidcGh6g4= -github.com/spiffe/go-spiffe/v2 v2.7.0/go.mod h1:47Q0Q9/AqGha8QLHp+kxpH4Wca7X7EnOtlIJy3mxZ3U= +github.com/spiffe/go-spiffe/v2 v2.8.1 h1:eXZMLsu+3MLEPJyGJkolqtVrteZfQdUpOWj6LTiDl/E= +github.com/spiffe/go-spiffe/v2 v2.8.1/go.mod h1:47Q0Q9/AqGha8QLHp+kxpH4Wca7X7EnOtlIJy3mxZ3U= github.com/spkg/bom v0.0.0-20160624110644-59b7046e48ad/go.mod h1:qLr4V1qq6nMqFKkMo8ZTx3f+BZEkzsRUY10Xsm2mwU0= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= @@ -283,51 +273,47 @@ github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWD github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg= github.com/swaggo/swag v1.16.6 h1:qBNcx53ZaX+M5dxVyTrgQ0PJ/ACK+NzhwcbieTt+9yI= github.com/swaggo/swag v1.16.6/go.mod h1:ngP2etMK5a0P3QBizic5MEwpRmluJZPHjXcMoj4Xesg= -github.com/terminalstatic/go-xsd-validate v0.1.8 h1:UVrTCy1j3DhwaYTTUF+QYO/Nan13S0tf+Jwi+p45Bf0= -github.com/terminalstatic/go-xsd-validate v0.1.8/go.mod h1:1kb47fi2c6onlf+B7UrrQ9VYraOhcYwFm3iG+J6F4Zo= -github.com/ulikunitz/xz v0.5.16 h1:ld6NyySjx5lowVKwJvMRLnW5nxKX/xnpSiFYZ/Lxur0= -github.com/ulikunitz/xz v0.5.16/go.mod h1:H9Rt/W6/Qj27PGauhQc6nfCDy7vHpzsOThBSaYDoEhw= -github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f h1:J9EGpcZtP0E/raorCMxlFGSTBrsSlaDGf3jU/qvAE2c= -github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f/go.mod h1:N2zxlSyiKSe5eX1tZViRH5QA0qijqEDrYZiPEAiq3wU= -github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 h1:EzJWgHovont7NscjpAxXsDA8S8BMYve8Y5+7cuRE7R0= -github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415/go.mod h1:GwrjFmJcFw6At/Gs6z4yjiIwzuJ1/+UwLxMQDVQXShQ= -github.com/xeipuuv/gojsonschema v1.2.0 h1:LhYJRs+L4fBtjZUfuSZIKGeVu0QRy8e5Xi7D17UxZ74= -github.com/xeipuuv/gojsonschema v1.2.0/go.mod h1:anYRn/JVcOK2ZgGU+IjEV4nwlhoK5sQluxsYJ78Id3Y= +github.com/ulikunitz/xz v0.5.17 h1:flR0y/x1hgM8EGV1AW3Xll6T413G0glV8UfBwR617V4= +github.com/ulikunitz/xz v0.5.17/go.mod h1:H9Rt/W6/Qj27PGauhQc6nfCDy7vHpzsOThBSaYDoEhw= +github.com/vmihailenco/msgpack/v5 v5.4.1 h1:cQriyiUvjTwOHg8QZaPihLWeRAAVoCpE00IUPn0Bjt8= +github.com/vmihailenco/msgpack/v5 v5.4.1/go.mod h1:GaZTsDaehaPpQVyxrf5mtQlH+pc21PIudVV/E3rRQok= +github.com/vmihailenco/tagparser/v2 v2.0.0 h1:y09buUbR+b5aycVFQs/g70pqKVZNBmxwAhO7/IwNM9g= +github.com/vmihailenco/tagparser/v2 v2.0.0/go.mod h1:Wri+At7QHww0WTrCBeu4J6bNtoV6mEfg5OIWRZA9qds= go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64= go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y= -go.opentelemetry.io/contrib/detectors/gcp v1.44.0 h1:NmLfL734pJhM0JKaYd2Y28+nY9dPRWYAAbxhRCrKXPw= -go.opentelemetry.io/contrib/detectors/gcp v1.44.0/go.mod h1:tNAsgd8avTGke1+MndXlU5Cru4PQ9Ai/cCNWQv/ZJ/s= -go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.67.0 h1:yI1/OhfEPy7J9eoa6Sj051C7n5dvpj0QX8g4sRchg04= -go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.67.0/go.mod h1:NoUCKYWK+3ecatC4HjkRktREheMeEtrXoQxrqYFeHSc= -go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.69.0 h1:8tvICD4vSTOOsNrsI4Ljf6C+6UKvpTEH5XY3JMoyPoo= -go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.69.0/go.mod h1:z9+yiacE0IHRqM4qFfkbt/JYlmYXgss8GY/jXoNuPJI= -go.opentelemetry.io/otel v1.45.0 h1:pdrWmLHofpubmArBv1LgFSv1Z0Ie/ppdZzu+kUN5EeU= -go.opentelemetry.io/otel v1.45.0/go.mod h1:XZxIqPapzEYnhNSScF5DIqXhm/rYi0FzCe2XddAwZfQ= -go.opentelemetry.io/otel/metric v1.45.0 h1:7Eg1uH7CJ5cXv9is6tnBe1FI6rj1nwUdbFypRm3br/M= -go.opentelemetry.io/otel/metric v1.45.0/go.mod h1:HAPbm1nd3p1PmFH7v2dR+6BjXxw+Lq4a2+pndMAm08s= -go.opentelemetry.io/otel/metric/x v0.67.0 h1:PcicCNZFkZ4bXfSooXdo3WN7RBOVOtjVdo1wD358Uns= -go.opentelemetry.io/otel/metric/x v0.67.0/go.mod h1:FBjCWZe6wgcqxcMtjdGiClDKXb2YxxXii0CXftE4QtI= -go.opentelemetry.io/otel/sdk v1.45.0 h1:4VVSMgQ83dUgW2aoX5f6JgLvHwIvzcuLnF9lUdCSpCw= -go.opentelemetry.io/otel/sdk v1.45.0/go.mod h1:Sr40LgXV7DsKMMJMKOhUWOgMWTfAaqvm2kF0g7ilwuA= -go.opentelemetry.io/otel/sdk/metric v1.45.0 h1:oVFszMfyj1Am6s24Vtc7wBb8BKLcwepJjNEYILuiE3o= -go.opentelemetry.io/otel/sdk/metric v1.45.0/go.mod h1:vUWUxDZvu1WVRj8JA8S0AdhsPrZoDpA2DdZauIh4mDA= -go.opentelemetry.io/otel/trace v1.45.0 h1:l/mP6Uv7oNO7/TblbhpbgMidxhq1uO/rPsikOyVhxag= -go.opentelemetry.io/otel/trace v1.45.0/go.mod h1:qoJJA2xNMnxRrdISU/kLtfUH2wNeQbiv+jhs/CxI8bc= +go.opentelemetry.io/contrib/detectors/gcp v1.46.0 h1:PI8dGkqDaQkwJ8kOopqMhDTbrnK3UIeG/RCHH4HErbo= +go.opentelemetry.io/contrib/detectors/gcp v1.46.0/go.mod h1:nsrN5c/sOLoY2vsPxN/rQ0V0nvGrWJCqcW4UXLtqNG8= +go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.71.0 h1:B2h3uqicet1CT2N5TOFhS+Gq++9i0/CLmaxvhmhtP5s= +go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.71.0/go.mod h1:dylvB+ZiiwMvsDij9O84Uy7SijLgHMX4mbkncds+4Sw= +go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.71.0 h1:3g7B90UzBltIDKq1/5mrTGxTnOFDV0ICOhLoxiZ8jlg= +go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.71.0/go.mod h1:Ef8SuTh59BT7+ofpDxN9z+yOlc4t2GjLmKDgYNJL/NU= +go.opentelemetry.io/otel v1.46.0 h1:FHt5/CDyVxi/8IM1CH7VE/rRgq3kLHa2mSTVMO8AWyc= +go.opentelemetry.io/otel v1.46.0/go.mod h1:Gj3SEScelsNC45tp4nSxRYlS+f5iez7W8XPMCt905kE= +go.opentelemetry.io/otel/metric v1.46.0 h1:yBnkXvgV7AXFILZc5K6IZe/CBFF3OS7BJ8ov6/lj0K8= +go.opentelemetry.io/otel/metric v1.46.0/go.mod h1:iPmdWqifKUdzziPkvvzIJXITl56fQx2mGM/DHLB3/2o= +go.opentelemetry.io/otel/metric/x v0.68.0 h1:TA/cBT23D3MnxYPwHL7YFOdYGdx0A0v+s7Mzotpd1dU= +go.opentelemetry.io/otel/metric/x v0.68.0/go.mod h1:agudOmvWhwUTjgibWDzxD2PoWYnpw5Ht5jISYOD2Hd4= +go.opentelemetry.io/otel/sdk v1.46.0 h1:h5CNQQjEbuQXY/JfZtgt3i7HVFV3aHPO2OAwO2eTYPI= +go.opentelemetry.io/otel/sdk v1.46.0/go.mod h1:GAERFXFt5SYCEB+YiKUbMBeza6UaDH7GmGOZEfh2gSM= +go.opentelemetry.io/otel/sdk/metric v1.46.0 h1:0piZ26EG4RBfebb2jhDH6ERCYHoVWduc3kLgPCwSnSE= +go.opentelemetry.io/otel/sdk/metric v1.46.0/go.mod h1:I1PbKrdVc8Qu8HYVDNtqVIwLwjNrhsV/uFuxfwg8mO4= +go.opentelemetry.io/otel/trace v1.46.0 h1:OULy7ccdJnZtJ0UDYFOIGaCmiWzJ8Vi2G/Rsu60qs1c= +go.opentelemetry.io/otel/trace v1.46.0/go.mod h1:J7GAXweO77XSFkB/rmAqk9D6ihszhFjLU+d9WuUxDLI= go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE= go.yaml.in/yaml/v2 v2.4.4 h1:tuyd0P+2Ont/d6e2rl3be67goVK4R6deVxCUX5vyPaQ= go.yaml.in/yaml/v2 v2.4.4/go.mod h1:gMZqIpDtDqOfM0uNfy0SkpRhvUryYH0Z6wdMYcacYXQ= go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw= go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg= -gocloud.dev v0.46.0 h1:niIuZwSjMtBx8K+ITB2s5kZullB13PGOS2ZoQPZxQ4Q= -gocloud.dev v0.46.0/go.mod h1:ACQe+2qO+hEO+pdcvvsM+RB63r8TyGD1W3ESCLFyzvM= -golang.org/x/crypto v0.57.0 h1:3ZVCjf8Ggz7zneR/EHRVx68Ctf+2pmIMP2UFhh9cC6M= -golang.org/x/crypto v0.57.0/go.mod h1:Fdz0i5U6CoizGwLda9DttjSk6qlZo25zYNtR+ycvuZA= -golang.org/x/mod v0.41.0 h1:qJmnOUb4YB+FsEuM3HcWucdZASCPGhsX6uljO6pog0c= -golang.org/x/mod v0.41.0/go.mod h1:Ek9pY8RKWXwsWvd3rQiHYtMqkjSUV+s1Rj7j4H5Ur6o= +gocloud.dev v0.47.0 h1:qN4/0vtutn97f1X5ziisf3WXuaFL9AR0FIRnyJRYzgA= +gocloud.dev v0.47.0/go.mod h1:OdMnyXQRhM17U0a0DwU57pe0c01qN3lJNmaeeRYW0D0= +golang.org/x/crypto v0.58.0 h1:COkYLr4k7nDI4r6QtMML2AfzeIswWHAJthLS6K/M/54= +golang.org/x/crypto v0.58.0/go.mod h1:Xh+kl5A+M0gMiWDytH2Hhr5Z7WbNCpv/eB/EFgfSk+w= +golang.org/x/mod v0.42.0 h1:ICeL3t2L30ljSPHHxDnR4fqVcBt/zR2zJAb9juavmQg= +golang.org/x/mod v0.42.0/go.mod h1:u5fzIrRInkL8MaO1cbRkUHT64v303YIT5KEqpNr7jRs= golang.org/x/net v0.0.0-20210421230115-4e50805a0758/go.mod h1:72T/g9IO56b78aLF+1Kcs5dz7/ng1VjMUvfKvpfy+jM= -golang.org/x/net v0.59.0 h1:5zfYln+w5XCxwrnMMJPufRgNoXEaGxl0wo5GqPXyues= -golang.org/x/net v0.59.0/go.mod h1:2DA/G1UfVbCpQPeWTmMPGY7Cs2PkBkwu743bVX5PIVg= +golang.org/x/net v0.62.0 h1:18ELalfM5+XNRwzM2nYqXsZQ9ByS1uhj2O/U7+5jqRY= +golang.org/x/net v0.62.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI= golang.org/x/oauth2 v0.37.0 h1:JUlcxA8oAtauLfiH8FX2/FkAWHAdi0QtGCGc+hofE98= golang.org/x/oauth2 v0.37.0/go.mod h1:IxwZNxUULJmpBFf9K/9NTMSIfZZuvuTy1gGxhigP/58= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= @@ -336,30 +322,30 @@ golang.org/x/sync v0.24.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210420072515-93ed5bcd2bfe/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo= -golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= +golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA= +golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= -golang.org/x/text v0.42.0 h1:JbOZXgfeCPU9gacVtYliJqOhD+zhrEqK4LfdpmlUZqI= -golang.org/x/text v0.42.0/go.mod h1:ojzP1Z+2QtioaF8DTtO8K5q7JWVVYwZKenzujK0Zd0E= +golang.org/x/text v0.43.0 h1:1QivrlhwAsnMOcqgOdl9my7s9OyZl8O5/UGUTJVXoWc= +golang.org/x/text v0.43.0/go.mod h1:hbSIYA/amXcRXTFSZqh8tWHEoqRvvbKPJ2uz/KU+a+s= golang.org/x/time v0.15.0 h1:bbrp8t3bGUeFOx08pvsMYRTCVSMk89u4tKbNOZbp88U= golang.org/x/time v0.15.0/go.mod h1:Y4YMaQmXwGQZoFaVFk4YpCt4FLQMYKZe9oeV/f4MSno= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= -golang.org/x/tools v0.50.0 h1:c2ifzfcuY7L90lZ2aKd8S4K2NpASF08SZx9ZuJkHmSU= -golang.org/x/tools v0.50.0/go.mod h1:7ulVMw3831Mwi5EZD6RomGyffr4VFjuNYXf2BbCEAV0= +golang.org/x/tools v0.52.0 h1:ryxg4U63oaUYk7uOLTF37n43f4qgtGvqV4Ioit1BaEs= +golang.org/x/tools v0.52.0/go.mod h1:ItcP5UNaVGG+Yc4eIYmaFLNJ4soEopkx5Y2d4lcEurs= golang.org/x/xerrors v0.0.0-20240903120638-7835f813f4da h1:noIWHXmPHxILtqtCOPIhSt0ABwskkZKjD3bXGnZGpNY= golang.org/x/xerrors v0.0.0-20240903120638-7835f813f4da/go.mod h1:NDW/Ps6MPRej6fsCIbMTohpP40sJ/P/vI1MoTEGwX90= gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4= gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E= -google.golang.org/api v0.288.0 h1:glhO/J88obKP5I269W3hB73dvBKrjU56ZfmNlNXpgTU= -google.golang.org/api v0.288.0/go.mod h1:lM2kYRzYUCBY91P9h6VF1PYmvhxii3O5hji37qRvIcY= -google.golang.org/genproto v0.0.0-20260319201613-d00831a3d3e7 h1:XzmzkmB14QhVhgnawEVsOn6OFsnpyxNPRY9QV01dNB0= -google.golang.org/genproto v0.0.0-20260319201613-d00831a3d3e7/go.mod h1:L43LFes82YgSonw6iTXTxXUX1OlULt4AQtkik4ULL/I= -google.golang.org/genproto/googleapis/api v0.0.0-20260630182238-925bb5da69e7 h1:jQ9p21COKWjP3VwuFrNRiiOTMh3mPpN45R7SLrH/HUU= -google.golang.org/genproto/googleapis/api v0.0.0-20260630182238-925bb5da69e7/go.mod h1:KqHwBx2upmfa1XSi1WuRvC+2VGCLtooKkfmyvRbUmqA= -google.golang.org/genproto/googleapis/rpc v0.0.0-20260706201446-f0a921348800 h1:qEHAMpSaUhtD0p3NbEEI83HwNGFxEwaSJ1G9PLnCBZE= -google.golang.org/genproto/googleapis/rpc v0.0.0-20260706201446-f0a921348800/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8= +google.golang.org/api v0.297.0 h1:WktxTsnnx0yZNnsR6j0q6hR21RnnK81FHTOPy/ux4OE= +google.golang.org/api v0.297.0/go.mod h1:S4m8x0M6OkQpkOzGk1y9JG2sm4fFQrMh6dxzjCTszhE= +google.golang.org/genproto v0.0.0-20260904194346-d0f1323225a4 h1:6QRNo34FxJcE1LG6XfnmaQ17m6w21oXaKlKoBaF+UqE= +google.golang.org/genproto v0.0.0-20260904194346-d0f1323225a4/go.mod h1:eifJ91nefXnfP/bMkZsACVGm14ZtEL4eUXRLTryfbY4= +google.golang.org/genproto/googleapis/api v0.0.0-20260904194346-d0f1323225a4 h1:NCe/UiklGd/9xjT+ROBVhJ1kf6TRQaFedsR+z7u1gvo= +google.golang.org/genproto/googleapis/api v0.0.0-20260904194346-d0f1323225a4/go.mod h1:fJ2lYaWjqNknJyQBOCd0fA3HnEElJqGplH71a2txi+g= +google.golang.org/genproto/googleapis/rpc v0.0.0-20260904194346-d0f1323225a4 h1:5t+ZydAFj5kGVLrgCvLmpmCf9ylGRd64hpEronfRaws= +google.golang.org/genproto/googleapis/rpc v0.0.0-20260904194346-d0f1323225a4/go.mod h1:DjtHYE8FKJLivXcBEjGwndXfIC23G0VpXiXKqG179uA= google.golang.org/grpc v1.83.2 h1:EManeRomTObA0BU7I8vXgg/78uE5MJ9M8B39EX2WscU= google.golang.org/grpc v1.83.2/go.mod h1:YPI1hK3kDked6iHvgX3tR0y+nX/qpMFKhPgFsokw1S8= google.golang.org/protobuf v1.36.12 h1:pJOKDDOyeXErUroCihFAd5LQuwXBSpVnKGrj5o/fwxc= @@ -376,20 +362,20 @@ gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C gopkg.in/yaml.v3 v3.0.0-20200615113413-eeeca48fe776/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -modernc.org/cc/v4 v4.29.7 h1:q+NXGJ0bK3b4TXFYQQVr9pYETGnmwFWkrUzJnMya/Tg= -modernc.org/cc/v4 v4.29.7/go.mod h1:OnovgIhbbMXMu1aISnJ0wvVD1KnW+cAUJkIrAWh+kVI= -modernc.org/ccgo/v4 v4.36.1 h1:ZNIUZAryN0UgnJwtyxrdEzcFc3yD4Cu4AzjfPXsLsIE= -modernc.org/ccgo/v4 v4.36.1/go.mod h1:rrtGc2QkS239nYb/mQNuBMyjq3/y3ZXWbBjPoV3wqzA= +modernc.org/cc/v4 v4.30.3 h1:aDq8gIX1X7+VFgO/JYYji6pLWL2H4tv3g8WatT3KCys= +modernc.org/cc/v4 v4.30.3/go.mod h1:OnovgIhbbMXMu1aISnJ0wvVD1KnW+cAUJkIrAWh+kVI= +modernc.org/ccgo/v4 v4.37.0 h1:BAuJCUtIHIxFIYaFhqXIw5YaoMBlNCUlFovejHfMip4= +modernc.org/ccgo/v4 v4.37.0/go.mod h1:/8627VhwWtAbqUXmPORxFQU5SgLrAx2jl9seLw9GBhY= modernc.org/fileutil v1.4.0 h1:j6ZzNTftVS054gi281TyLjHPp6CPHr2KCxEXjEbD6SM= modernc.org/fileutil v1.4.0/go.mod h1:EqdKFDxiByqxLk8ozOxObDSfcVOv/54xDs/DUHdvCUU= modernc.org/gc/v2 v2.6.5 h1:nyqdV8q46KvTpZlsw66kWqwXRHdjIlJOhG6kxiV/9xI= modernc.org/gc/v2 v2.6.5/go.mod h1:YgIahr1ypgfe7chRuJi2gD7DBQiKSLMPgBQe9oIiito= -modernc.org/gc/v3 v3.1.5 h1:21ldfPfRYE31Tb7B3mwAK8gy1AxP4+dKjrOQPfqakoc= -modernc.org/gc/v3 v3.1.5/go.mod h1:HFK/6AGESC7Ex+EZJhJ2Gni6cTaYpSMmU/cT9RmlfYY= +modernc.org/gc/v3 v3.2.0 h1:/Y3LGDMQaoYf55PebP1qsZ5FDGgAZyG1RYKEHeQzh1o= +modernc.org/gc/v3 v3.2.0/go.mod h1:HFK/6AGESC7Ex+EZJhJ2Gni6cTaYpSMmU/cT9RmlfYY= modernc.org/goabi0 v0.2.0 h1:HvEowk7LxcPd0eq6mVOAEMai46V+i7Jrj13t4AzuNks= modernc.org/goabi0 v0.2.0/go.mod h1:CEFRnnJhKvWT1c1JTI3Avm+tgOWbkOu5oPA8eH8LnMI= -modernc.org/libc v1.77.1 h1:Ct8j47QtiZ1Enj2DtFXQtUqrPCAjdCmPjtCuvrYQ0Hs= -modernc.org/libc v1.77.1/go.mod h1:87/pZ4L6nD1zqW4nItuS12YO7hN1igAah34xjnQo/W0= +modernc.org/libc v1.79.0 h1:9Dvvv++bAMSkSuBzuOFAatbTV5OIoq6Y6FohmD3e7q8= +modernc.org/libc v1.79.0/go.mod h1:uT3kR61NsbeKJSLqq83GJwSnZMVLlSjyAz4DfTaBy1M= modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU= modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg= modernc.org/memory v1.12.1 h1:nFMiWrpStgZczNl6XI9GnIk/rWhYIyHGUaR04pGbp9g= @@ -398,8 +384,8 @@ modernc.org/opt v0.2.0 h1:tGyef5ApycA7FSEOMraay9SaTk5zmbx7Tu+cJs4QKZg= modernc.org/opt v0.2.0/go.mod h1:03fq9lsNfvkYSfxrfUhZCWPk1lm4cq4N+Bh//bEtgns= modernc.org/sortutil v1.2.1 h1:+xyoGf15mM3NMlPDnFqrteY07klSFxLElE2PVuWIJ7w= modernc.org/sortutil v1.2.1/go.mod h1:7ZI3a3REbai7gzCLcotuw9AC4VZVpYMjDzETGsSMqJE= -modernc.org/sqlite v1.60.1 h1:/blz53O951KWFOso4QQvEs/Fq6cDBKLtMVrYNSeJVKw= -modernc.org/sqlite v1.60.1/go.mod h1:1dIoEagfDE72QytD5scH1lxARtaUgKgHC/NuApA27r0= +modernc.org/sqlite v1.61.0 h1:sQi63oLQ9uquAUA4CzOisH35Q3pEszkPBuHM0tFL8CY= +modernc.org/sqlite v1.61.0/go.mod h1:f4gr5tbpx2umklaT/QVtbi/50hNdM+4ng+2zMo8KXJ0= modernc.org/strutil v1.2.1 h1:UneZBkQA+DX2Rp35KcM69cSsNES9ly8mQWD71HKlOA0= modernc.org/strutil v1.2.1/go.mod h1:EHkiggD70koQxjVdSBM3JKM7k6L0FbGE5eymy9i3B9A= modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y= diff --git a/internal/config/config.go b/internal/config/config.go index a9d7c21..6f8171f 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -60,21 +60,26 @@ package config import ( + _ "embed" "encoding/base64" "encoding/json" "fmt" + "math" "net" "net/url" "os" "path" "path/filepath" "regexp" + "slices" "sort" "strconv" "strings" "time" + "github.com/git-pkgs/cooldown" "github.com/git-pkgs/proxy/internal/denylist" + "github.com/git-pkgs/proxy/internal/packageurl" "github.com/git-pkgs/proxy/internal/retention" "github.com/git-pkgs/purl" "gopkg.in/yaml.v3" @@ -167,6 +172,11 @@ type Config struct { // size return ErrMetadataTooLarge. Default: "100MB". MetadataMaxSize string `json:"metadata_max_size" yaml:"metadata_max_size"` + // MetadataStreamMaxSize is the largest metadata document the proxy + // streams from upstream into storage instead of buffering it, which + // metadata_max_size doesn't cover (e.g. "1GB"). Default: "1GB". + MetadataStreamMaxSize string `json:"metadata_stream_max_size" yaml:"metadata_stream_max_size"` + // ArtifactMaxSize is the largest upstream artifact the proxy will fetch // (e.g. "2GB"). Larger artifacts are refused and not cached. Default: "" // (unlimited). "0" is also unlimited. @@ -186,23 +196,52 @@ type Config struct { // response headers within 60 seconds. HTTPTimeout string `json:"http_timeout" yaml:"http_timeout"` + // WriteTimeout bounds response writes, including time spent downloading and + // scanning before the response starts. Default: "5m"; "0" disables it. + WriteTimeout string `json:"write_timeout" yaml:"write_timeout"` + + // ArtifactTimeout bounds each upstream artifact download while serving + // requests, excluding scanning. Default: "5m"; "0" disables it. + // The mirror command keeps its unlimited artifact download timeout. + ArtifactTimeout string `json:"artifact_timeout" yaml:"artifact_timeout"` + // MirrorAPI enables the /api/mirror endpoints for starting mirror jobs via HTTP. // Disabled by default to prevent unauthenticated users from triggering downloads. MirrorAPI bool `json:"mirror_api" yaml:"mirror_api"` + // Mirror configures scheduled mirroring. + Mirror MirrorConfig `json:"mirror" yaml:"mirror"` + + // CacheDelete enables DELETE /api/cache for removing cached artifacts, and + // the delete buttons on the UI's version page. It has no authentication of + // its own, so restrict /api/cache and /ui at the ingress when enabling it. + CacheDelete bool `json:"cache_delete" yaml:"cache_delete"` + // Hosted configures pushing packages to the proxy (/api/hosted). Hosted HostedConfig `json:"hosted" yaml:"hosted"` + // Projects configures the project inventory (/api/projects). + Projects ProjectsConfig `json:"projects" yaml:"projects"` + // Gradle configures Gradle HttpBuildCache behavior. Gradle GradleConfig `json:"gradle" yaml:"gradle"` // Health configures the /health endpoint behavior. Health HealthConfig `json:"health" yaml:"health"` + + // Git configures the Git repository cache served at /git/{name}/. + Git GitConfig `json:"git" yaml:"git"` + + // envWarnings collects environment values LoadFromEnv ignored. + envWarnings []string } // CooldownConfig configures version cooldown periods. // Versions published more recently than the cooldown are hidden from metadata responses. type CooldownConfig struct { + // Profiles are independent policies exposed at /cooldown/{name}/. + Profiles map[string]CooldownConfig `json:"profiles,omitempty" yaml:"profiles,omitempty"` + // Default is the global default cooldown (e.g., "3d", "48h", "0" to disable). Default string `json:"default" yaml:"default"` @@ -236,7 +275,7 @@ func (c *CooldownConfig) NormalizedPackages() map[string]string { for _, key := range keys { canonical := key if parsed, err := purl.Parse(key); err == nil { - canonical = parsed.String() + canonical = packageurl.PolicyPackageKey(parsed.String()) } if _, exists := normalized[canonical]; exists && key != canonical { continue @@ -246,6 +285,28 @@ func (c *CooldownConfig) NormalizedPackages() map[string]string { return normalized } +// Shortest returns the shortest cooldown configured anywhere, by default, +// ecosystem, package or package pattern, or 0 when none is. Unparsable +// durations are left out; Validate reports them. +func (c *CooldownConfig) Shortest() time.Duration { + if c == nil { + return 0 + } + var shortest time.Duration + consider := func(s string) { + if d, err := cooldown.ParseDuration(s); err == nil && d > 0 && (shortest == 0 || d < shortest) { + shortest = d + } + } + consider(c.Default) + for _, m := range []map[string]string{c.Ecosystems, c.Packages, c.PackagePatterns} { + for _, v := range m { + consider(v) + } + } + return shortest +} + // ScanningConfig configures pre-cache artifact scanning (e.g. trivy, // ClamAV, Wiz, or a custom service) to mitigate supply chain attacks. // Unlike Cooldown, which only looks at a version's publish timestamp, @@ -377,9 +438,55 @@ func (s *ScannerConfig) Validate() error { default: return fmt.Errorf("invalid mode %q (must be block or monitor)", s.Mode) } + for i, eco := range s.Ecosystems { + key, err := ScannerEcosystemKey(eco) + if err != nil { + return err + } + s.Ecosystems[i] = key + } return nil } +// scannerEcosystems are the ecosystem keys handlers pass to scanners: the +// retention keys plus the handlers retention does not cover, and git for +// Git LFS objects. +var scannerEcosystems = func() []string { + keys := append(slices.Clone(retention.KnownKeys), "arch", "chef", "git") + slices.Sort(keys) + return keys +}() + +// scannerEcosystemAliases maps common ecosystem names to handler keys. +var scannerEcosystemAliases = map[string]string{ + "apk": "alpine", + "debian": "deb", + "docker": "oci", + "go": "golang", + "packagist": "composer", + "rubygems": "gem", +} + +// NormalizeScannerEcosystem returns the handler key for a +// scanning.scanners[].ecosystems entry, resolving case and common aliases. +func NormalizeScannerEcosystem(eco string) string { + eco = strings.ToLower(strings.TrimSpace(eco)) + if key, ok := scannerEcosystemAliases[eco]; ok { + return key + } + return eco +} + +// ScannerEcosystemKey is NormalizeScannerEcosystem that also rejects +// names no handler uses. +func ScannerEcosystemKey(eco string) (string, error) { + key := NormalizeScannerEcosystem(eco) + if !slices.Contains(scannerEcosystems, key) { + return "", fmt.Errorf("unknown ecosystem %q (valid: %s)", eco, strings.Join(scannerEcosystems, ", ")) + } + return key, nil +} + // StorageConfig configures artifact storage. type StorageConfig struct { // URL is the storage backend URL. @@ -437,7 +544,7 @@ type StorageConfig struct { // for days; "0" or empty means never evict by age. type RetentionConfig struct { // Default applies to every ecosystem that supports retention and has no - // rule of its own. + // rule of its own, except generic, which requires an explicit rule. Default string `json:"default" yaml:"default"` // Ecosystems overrides the default per ecosystem key (e.g. "npm", "oci"). @@ -463,6 +570,7 @@ type GradleConfig struct { // GradleBuildCacheConfig configures Gradle HttpBuildCache safeguards. type GradleBuildCacheConfig struct { // ReadOnly disables PUT uploads and keeps cache reads (GET/HEAD) enabled. + // Default: true; set false on the instance that CI uploads to. ReadOnly bool `json:"read_only" yaml:"read_only"` // MaxUploadSize caps a single PUT body size (e.g., "100MB"). Must be > 0. @@ -565,6 +673,12 @@ type UpstreamConfig struct { // wins. NPMRoutes map[string]string `json:"npm_routes" yaml:"npm_routes"` + // NPMChangeFeed follows the public npm registry's change feed and + // revalidates cached packuments of packages listed in it on their next + // request, rather than serving them until metadata_ttl runs out. + // Requires cache_metadata. Default: false. + NPMChangeFeed bool `json:"npm_change_feed" yaml:"npm_change_feed"` + // Cargo is the upstream cargo index URL. // Default: https://index.crates.io Cargo string `json:"cargo" yaml:"cargo"` @@ -596,6 +710,11 @@ type UpstreamConfig struct { // Requires cache_metadata. Default: false. GoSumDBsOffline bool `json:"go_sumdbs_offline" yaml:"go_sumdbs_offline"` + // GoVulnDB is the Go vulnerability database served at /go/vulndb, for + // govulncheck -db pointing at the proxy. + // Default: https://vuln.go.dev + GoVulnDB string `json:"go_vulndb" yaml:"go_vulndb"` + // Hex is the upstream Hex repository URL. // Default: https://repo.hex.pm Hex string `json:"hex" yaml:"hex"` @@ -620,6 +739,14 @@ type UpstreamConfig struct { // Default: https://repo1.maven.org/maven2 Maven string `json:"maven" yaml:"maven"` + // MavenRepositories maps repository names to additional Maven repository + // base URLs, served at /maven/{name}/. upstream.maven stays the default + // at /maven/. A name must not be the first segment of a group ID, such + // as "org" or "tools", since it would hide those groups in the default + // repository; see validateMavenRepositoryName. + // Example: {"grails": "https://repo.grails.org/grails/restricted"}. + MavenRepositories map[string]string `json:"maven_repositories" yaml:"maven_repositories"` + // GradlePluginPortal is the upstream Gradle Plugin Portal Maven URL. // Used to resolve Gradle plugin marker artifacts. // Default: https://plugins.gradle.org/m2 @@ -649,10 +776,21 @@ type UpstreamConfig struct { // matching pattern wins. ComposerRoutes map[string]string `json:"composer_routes" yaml:"composer_routes"` + // ComposerChangeFeed follows the metadata change feed of + // upstream.composer and revalidates cached metadata of packages listed + // in it on their next request, rather than serving it until + // metadata_ttl runs out. Requires cache_metadata. Default: false. + ComposerChangeFeed bool `json:"composer_change_feed" yaml:"composer_change_feed"` + // Conan is the upstream Conan registry URL. // Default: https://center.conan.io Conan string `json:"conan" yaml:"conan"` + // Chef is the upstream Chef Supermarket URL, served at /chef/. Point it + // at a private Supermarket to proxy that instead of the public one. + // Default: https://supermarket.chef.io + Chef string `json:"chef" yaml:"chef"` + // Conda is the upstream Conda channel base URL. // Default: https://conda.anaconda.org Conda string `json:"conda" yaml:"conda"` @@ -706,12 +844,24 @@ type UpstreamConfig struct { // Default when empty: {"alpine": "https://dl-cdn.alpinelinux.org/alpine"}. APK map[string]string `json:"apk" yaml:"apk"` + // APKSnapshots keeps earlier versions of Alpine APK indexes for this + // long after upstream replaced them, and serves them at + // /apk/{name}@{YYYY-MM-DD}/. Accepts a "d" suffix, e.g. "90d". + // Empty or "0" disables snapshots. + APKSnapshots string `json:"apk_snapshots" yaml:"apk_snapshots"` + // Arch maps repository names to Arch Linux pacman mirror base URLs, // served at /arch/{name}/. The remaining request path mirrors the // upstream layout, e.g. /arch/archlinux/core/os/x86_64/core.db. // Default when empty: {"archlinux": "https://geo.mirror.pkgbuild.com"}. Arch map[string]string `json:"arch" yaml:"arch"` + // FreeBSD maps repository names to FreeBSD pkg mirror base URLs, served + // at /freebsd/{name}/. The remaining request path mirrors the upstream + // layout, e.g. /freebsd/freebsd/FreeBSD:14:amd64/latest/packagesite.pkg. + // Default when empty: {"freebsd": "https://pkg.freebsd.org"}. + FreeBSD map[string]string `json:"freebsd" yaml:"freebsd"` + // OCI maps names to OCI registry URLs. Requests to a named registry use // the repository prefix upstream/{name}/, for example // oci://proxy.example.com/upstream/ghcr/owner/chart. @@ -741,6 +891,21 @@ type UpstreamConfig struct { // Example: {"apache": ["dist/(?Pmaven)/maven-3/(?P[^/]+)/binaries/(?P[^/]+)"]}. GenericArtifacts map[string][]string `json:"generic_artifacts" yaml:"generic_artifacts"` + // GenericPaths maps a Generic upstream name to the paths it may serve, + // as patterns for the request path after /generic/{name}/ with the same + // syntax as GitUpstream.Repos: path.Match, where a pattern ending in + // "/**" also matches every path nested below its prefix. Other paths + // answer 404. Empty serves every path. Required when upstream.auth has + // credentials for the upstream, since everyone who can reach the proxy + // can use them for any path otherwise. + // Example: {"github-api": ["repos/*/*/releases/**"]}. + GenericPaths map[string][]string `json:"generic_paths" yaml:"generic_paths"` + + // Git maps names to Git servers, served read-only at /git/{name}/{repo} + // from a local cache of bare repositories. See GitUpstream. + // Example: {"github": {"url": "https://github.com"}}. + Git map[string]GitUpstream `json:"git" yaml:"git"` + // Auth configures authentication for upstream registries. // Keys are absolute URL scopes matched by scheme, host, effective port, // and path-segment prefix. @@ -793,9 +958,17 @@ func (u *UpstreamConfig) Validate() error { if err := validateNamedUpstreams("upstream.apk", u.APK); err != nil { return err } + if u.APKSnapshots != "" { + if _, err := parseRetentionDuration("upstream.apk_snapshots", u.APKSnapshots); err != nil { + return err + } + } if err := validateNamedUpstreams("upstream.arch", u.Arch); err != nil { return err } + if err := validateNamedUpstreams("upstream.freebsd", u.FreeBSD); err != nil { + return err + } if err := validateNamedUpstreams("upstream.go_sumdbs", u.GoSumDBs); err != nil { return err } @@ -811,6 +984,20 @@ func (u *UpstreamConfig) Validate() error { if err := u.validateGenericArtifacts(); err != nil { return err } + if err := u.validateGenericPaths(); err != nil { + return err + } + if err := u.validateGitUpstreams(); err != nil { + return err + } + if err := validateNamedUpstreams("upstream.maven_repositories", u.MavenRepositories); err != nil { + return err + } + for name := range u.MavenRepositories { + if err := validateMavenRepositoryName(name); err != nil { + return err + } + } if err := validateNamedUpstreams("upstream.debian_repositories", u.DebianRepositories); err != nil { return err } @@ -839,6 +1026,51 @@ func (u *UpstreamConfig) validateGenericArtifacts() error { return nil } +// validateGenericPaths checks upstream.generic_paths patterns. An upstream that +// upstream.auth has credentials for must list its paths, so configuring a +// token does not let everyone who can reach the proxy send any request with +// it, mirroring the repos rule for upstream.git. +func (u *UpstreamConfig) validateGenericPaths() error { + for name, patterns := range u.GenericPaths { + if _, found := u.Generic[name]; !found { + return fmt.Errorf("invalid upstream.generic_paths name %q: no upstream.generic entry", name) + } + for _, pattern := range patterns { + if _, err := path.Match(strings.TrimSuffix(pattern, "/**"), ""); pattern == "" || err != nil { + return fmt.Errorf("invalid upstream.generic_paths.%s pattern %q", name, pattern) + } + } + } + for name, upstreamURL := range u.Generic { + if len(u.GenericPaths[name]) == 0 && u.HasAuthWithin(upstreamURL) { + return fmt.Errorf("upstream.generic.%s needs upstream.generic_paths.%s: upstream.auth has credentials for %s, "+ + "and everyone who can reach the proxy could send any request with them", name, name, upstreamURL) + } + } + return nil +} + +// GenericPathAllowed reports whether p, a request path after +// /generic/{name}/, matches one of an upstream's upstream.generic_paths +// patterns. No patterns allow every path. With patterns, a path holding a +// character the upstream could read as the end of the path or as a different +// path ('%', '?', '#' or a backslash) is refused, so the path that matched is +// the one the upstream sees. +func GenericPathAllowed(patterns []string, p string) bool { + if len(patterns) == 0 { + return true + } + if strings.ContainsAny(p, `%?#\`) { + return false + } + for _, pattern := range patterns { + if matchRepoPattern(pattern, p) { + return true + } + } + return false +} + // validateUpstream checks the upstream block, including the one setting in // it that depends on a top-level option. func (c *Config) validateUpstream() error { @@ -848,9 +1080,20 @@ func (c *Config) validateUpstream() error { if c.Upstream.GoSumDBsOffline && !c.CacheMetadata { return fmt.Errorf("upstream.go_sumdbs_offline requires cache_metadata") } + if c.Upstream.NPMChangeFeed && !c.CacheMetadata { + return fmt.Errorf("upstream.npm_change_feed requires cache_metadata") + } + if c.Upstream.ComposerChangeFeed && !c.CacheMetadata { + return fmt.Errorf("upstream.composer_change_feed requires cache_metadata") + } return nil } +// HostedGenericRepository is the /generic/{name}/ path that serves files +// pushed through /api/hosted/generic. While hosted packages are enabled, no +// upstream.generic entry may use it. +const HostedGenericRepository = "hosted" + // CompileGenericArtifactPattern compiles an upstream.generic_artifacts pattern // so that it only matches a whole path, and checks it has the `version` and // `file` groups. @@ -867,6 +1110,61 @@ func CompileGenericArtifactPattern(pattern string) (*regexp.Regexp, error) { return re, nil } +// mavenGroupRootList lists the first path segments of group IDs on Maven +// Central and Google's Maven repository, one per line. +// +//go:embed maven_group_roots.txt +var mavenGroupRootList string + +// mavenGroupRoots are the first segments of group IDs a repository name +// must not take: those in mavenGroupRootList, and generic top-level domains +// group IDs are commonly reversed from. +var mavenGroupRoots = func() map[string]bool { + roots := map[string]bool{} + for _, tld := range []string{"app", "biz", "cloud", "com", "dev", "edu", "gov", "info", "int", + "io", "mil", "name", "net", "org", "pro", "tech", "xyz"} { + roots[tld] = true + } + for line := range strings.Lines(mavenGroupRootList) { + if line = strings.TrimSpace(line); line != "" && !strings.HasPrefix(line, "#") { + roots[line] = true + } + } + return roots +}() + +// mavenRepositoryNamePattern is what a repository name may look like: the +// characters of a group ID segment, which clients send unescaped. +var mavenRepositoryNamePattern = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._-]*$`) + +// countryCodeLength is the length of a country-code top-level domain. +const countryCodeLength = 2 + +// validateMavenRepositoryName refuses names that are likely the first +// segment of a group ID. /maven/{name}/ is matched before the default +// repository, so such a name would hide every group under it there: +// a repository named "tools" would take /maven/tools/jackson/... away from +// Maven Central. Names are limited to characters that reach the handler +// unescaped. Paths are case-sensitive, so names are compared as they +// are. Names of two characters or less are refused as country codes. The +// list can't be complete, since group IDs are free-form, so the +// documentation also asks for names that can't be a group root. +func validateMavenRepositoryName(name string) error { + if !mavenRepositoryNamePattern.MatchString(name) { + return fmt.Errorf("invalid upstream.maven_repositories name %q: use letters, digits, '.', '_' and '-', "+ + "starting with a letter or digit, so the name works as a URL path segment", name) + } + if len(name) <= countryCodeLength { + return fmt.Errorf("invalid upstream.maven_repositories name %q: names of two characters or less "+ + "could hide country-code group IDs in the default repository", name) + } + if mavenGroupRoots[name] { + return fmt.Errorf("invalid upstream.maven_repositories name %q: it would hide group IDs starting with %q "+ + "in the default repository; use a name such as \"%s-repo\"", name, name, name) + } + return nil +} + // debianReservedRepositoryNames are the upstream.debian archive's own root // paths, which a repository of the same name would shadow. var debianReservedRepositoryNames = []string{"pool", "dists"} @@ -954,6 +1252,12 @@ func parseAuthURL(value string) (*url.URL, error) { } func authURLMatches(configured, target *url.URL) bool { + // An upstream resolves dot segments, so /scope/../other would leave the + // configured path while still matching it by prefix. Real package URLs + // never contain them, so they get no credentials at all. + if HasDotSegment(target.Path) { + return false + } if !strings.EqualFold(configured.Scheme, target.Scheme) || !strings.EqualFold(configured.Hostname(), target.Hostname()) || authURLPort(configured) != authURLPort(target) { @@ -971,6 +1275,25 @@ func authURLMatches(configured, target *url.URL) bool { return targetPath == configuredPath || strings.HasPrefix(targetPath, configuredPath+"/") } +// HasDotSegment reports whether the URL path p, or p decoded once more, has a +// '.' or '..' segment. Backslashes count as separators, and ";params" are +// ignored, since some upstream servers (Tomcat, Jetty) treat them that way. +func HasDotSegment(p string) bool { + candidates := []string{p} + if decoded, err := url.PathUnescape(p); err == nil { + candidates = append(candidates, decoded) + } + for _, candidate := range candidates { + for segment := range strings.SplitSeq(strings.ReplaceAll(candidate, `\`, "/"), "/") { + segment, _, _ = strings.Cut(segment, ";") + if segment == "." || segment == ".." { + return true + } + } + } + return false +} + func authURLPort(value *url.URL) string { if port := value.Port(); port != "" { return port @@ -1040,6 +1363,7 @@ func Default() *Config { CargoDownload: "https://static.crates.io/crates", Gem: "https://rubygems.org", Go: "https://proxy.golang.org", + GoVulnDB: "https://vuln.go.dev", Hex: "https://repo.hex.pm", HexAPI: "https://hex.pm", Pub: "https://pub.dev", @@ -1052,6 +1376,7 @@ func Default() *Config { Composer: "https://packagist.org", ComposerRepository: "https://repo.packagist.org", Conan: "https://center.conan.io", + Chef: "https://supermarket.chef.io", Conda: "https://conda.anaconda.org", CRAN: "https://cloud.r-project.org", Julia: "https://pkg.julialang.org", @@ -1064,7 +1389,7 @@ func Default() *Config { }, Gradle: GradleConfig{ BuildCache: GradleBuildCacheConfig{ - ReadOnly: false, + ReadOnly: true, MaxUploadSize: defaultGradleMaxUploadSizeStr, MaxAge: "168h", MaxSize: "", @@ -1113,11 +1438,55 @@ func setEnvString(dst *string, key string) { } } -// setEnvBool is setEnvString for boolean fields, parsed via envBool. -func setEnvBool(dst *bool, key string) { - if v := os.Getenv(key); v != "" { - *dst = envBool(v) +// parseEnvBool accepts what strconv.ParseBool does plus yes/no/on/off, +// ignoring case and surrounding space. +func parseEnvBool(v string) (bool, bool) { + v = strings.ToLower(strings.TrimSpace(v)) + switch v { + case "yes", "on": + return true, true + case "no", "off": + return false, true } + b, err := strconv.ParseBool(v) + return b, err == nil +} + +// setEnvBool is setEnvString for boolean fields, parsed via parseEnvBool. +// Any other value leaves *dst unchanged and is reported via EnvWarnings. +func (c *Config) setEnvBool(dst *bool, key string) { + v := os.Getenv(key) + if v == "" { + return + } + b, ok := parseEnvBool(v) + if !ok { + c.envWarnings = append(c.envWarnings, fmt.Sprintf("ignoring %s=%q: not a boolean, keeping %t", key, v, *dst)) + return + } + *dst = b +} + +// setGradleReadOnlyFromEnv parses strictly: an unrecognised value keeps +// uploads off instead of opening them, and is reported via EnvWarnings. +func (c *Config) setGradleReadOnlyFromEnv() { + const key = "PROXY_GRADLE_BUILD_CACHE_READ_ONLY" + v := os.Getenv(key) + if v == "" { + return + } + readOnly, ok := parseEnvBool(v) + if !ok { + c.Gradle.BuildCache.ReadOnly = true + c.envWarnings = append(c.envWarnings, fmt.Sprintf("ignoring %s=%q: not a boolean, keeping the Gradle build cache read-only", key, v)) + return + } + c.Gradle.BuildCache.ReadOnly = readOnly +} + +// EnvWarnings returns the environment values LoadFromEnv ignored. +func (c *Config) EnvWarnings() []string { + return c.envWarnings } func setEnvStringSlice(dst *[]string, key string) { @@ -1155,16 +1524,16 @@ func (c *Config) LoadFromEnv() { setEnvString(&c.Listen, "PROXY_LISTEN") setEnvString(&c.BaseURL, "PROXY_BASE_URL") setEnvString(&c.UIBaseURL, "PROXY_UI_URL") - setEnvBool(&c.TrustForwardedFor, "PROXY_TRUST_FORWARDED_FOR") - setEnvBool(&c.UIRequestSources, "PROXY_UI_REQUEST_SOURCES") - setEnvBool(&c.UIFailureDetails, "PROXY_UI_FAILURE_DETAILS") + c.setEnvBool(&c.TrustForwardedFor, "PROXY_TRUST_FORWARDED_FOR") + c.setEnvBool(&c.UIRequestSources, "PROXY_UI_REQUEST_SOURCES") + c.setEnvBool(&c.UIFailureDetails, "PROXY_UI_FAILURE_DETAILS") setEnvString(&c.Storage.URL, "PROXY_STORAGE_URL") setEnvString(&c.Storage.Path, "PROXY_STORAGE_PATH") setEnvString(&c.Storage.MaxSize, "PROXY_STORAGE_MAX_SIZE") - setEnvBool(&c.Storage.DirectServe, "PROXY_STORAGE_DIRECT_SERVE") + c.setEnvBool(&c.Storage.DirectServe, "PROXY_STORAGE_DIRECT_SERVE") setEnvString(&c.Storage.DirectServeTTL, "PROXY_STORAGE_DIRECT_SERVE_TTL") setEnvString(&c.Storage.DirectServeBaseURL, "PROXY_STORAGE_DIRECT_SERVE_BASE_URL") - setEnvBool(&c.Storage.CacheArtifacts, "PROXY_STORAGE_CACHE_ARTIFACTS") + c.setEnvBool(&c.Storage.CacheArtifacts, "PROXY_STORAGE_CACHE_ARTIFACTS") setEnvString(&c.Storage.Retention.Default, "PROXY_STORAGE_RETENTION_DEFAULT") setEnvString(&c.Storage.Retention.SweepInterval, "PROXY_STORAGE_RETENTION_SWEEP_INTERVAL") setEnvString(&c.Database.Driver, "PROXY_DATABASE_DRIVER") @@ -1175,14 +1544,16 @@ func (c *Config) LoadFromEnv() { setEnvString(&c.Log.Format, "PROXY_LOG_FORMAT") setEnvString(&c.AccessLog.Path, "PROXY_ACCESS_LOG_PATH") setEnvStringSlice(&c.Upstream.AllowPrivateHosts, "PROXY_UPSTREAM_ALLOW_PRIVATE_HOSTS") - setEnvBool(&c.Upstream.AllowLoopback, "PROXY_UPSTREAM_ALLOW_LOOPBACK") + c.setEnvBool(&c.Upstream.AllowLoopback, "PROXY_UPSTREAM_ALLOW_LOOPBACK") setEnvString(&c.Upstream.NPM, "PROXY_UPSTREAM_NPM") - setEnvBool(&c.Upstream.NPMFullMetadata, "PROXY_UPSTREAM_NPM_FULL_METADATA") - setEnvBool(&c.Upstream.GoSumDBsOffline, "PROXY_UPSTREAM_GO_SUMDBS_OFFLINE") + c.setEnvBool(&c.Upstream.NPMFullMetadata, "PROXY_UPSTREAM_NPM_FULL_METADATA") + c.setEnvBool(&c.Upstream.NPMChangeFeed, "PROXY_UPSTREAM_NPM_CHANGE_FEED") + c.setEnvBool(&c.Upstream.GoSumDBsOffline, "PROXY_UPSTREAM_GO_SUMDBS_OFFLINE") setEnvString(&c.Upstream.Cargo, "PROXY_UPSTREAM_CARGO") setEnvString(&c.Upstream.CargoDownload, "PROXY_UPSTREAM_CARGO_DOWNLOAD") setEnvString(&c.Upstream.Gem, "PROXY_UPSTREAM_GEM") setEnvString(&c.Upstream.Go, "PROXY_UPSTREAM_GO") + setEnvString(&c.Upstream.GoVulnDB, "PROXY_UPSTREAM_GO_VULNDB") setEnvString(&c.Upstream.Hex, "PROXY_UPSTREAM_HEX") setEnvString(&c.Upstream.HexAPI, "PROXY_UPSTREAM_HEX_API") setEnvString(&c.Upstream.Pub, "PROXY_UPSTREAM_PUB") @@ -1194,40 +1565,55 @@ func (c *Config) LoadFromEnv() { setEnvString(&c.Upstream.NuGetSearch, "PROXY_UPSTREAM_NUGET_SEARCH") setEnvString(&c.Upstream.Composer, "PROXY_UPSTREAM_COMPOSER") setEnvString(&c.Upstream.ComposerRepository, "PROXY_UPSTREAM_COMPOSER_REPOSITORY") + c.setEnvBool(&c.Upstream.ComposerChangeFeed, "PROXY_UPSTREAM_COMPOSER_CHANGE_FEED") setEnvString(&c.Upstream.Conan, "PROXY_UPSTREAM_CONAN") + setEnvString(&c.Upstream.Chef, "PROXY_UPSTREAM_CHEF") setEnvString(&c.Upstream.Conda, "PROXY_UPSTREAM_CONDA") setEnvString(&c.Upstream.CRAN, "PROXY_UPSTREAM_CRAN") setEnvString(&c.Upstream.Julia, "PROXY_UPSTREAM_JULIA") setEnvString(&c.Upstream.Swift, "PROXY_UPSTREAM_SWIFT") setEnvString(&c.Upstream.OCIDefault, "PROXY_UPSTREAM_OCI_DEFAULT") setEnvString(&c.Upstream.Debian, "PROXY_UPSTREAM_DEBIAN") + setEnvString(&c.Upstream.APKSnapshots, "PROXY_UPSTREAM_APK_SNAPSHOTS") setEnvString(&c.Upstream.RPM, "PROXY_UPSTREAM_RPM") setEnvString(&c.Upstream.HomebrewAPI, "PROXY_UPSTREAM_HOMEBREW_API") setEnvString(&c.Upstream.HomebrewArtifact, "PROXY_UPSTREAM_HOMEBREW_ARTIFACT") setEnvString(&c.Cooldown.Default, "PROXY_COOLDOWN_DEFAULT") - setEnvBool(&c.Scanning.Enabled, "PROXY_SCANNING_ENABLED") - setEnvBool(&c.Scanning.FailOpen, "PROXY_SCANNING_FAIL_OPEN") + c.setEnvBool(&c.Scanning.Enabled, "PROXY_SCANNING_ENABLED") + c.setEnvBool(&c.Scanning.FailOpen, "PROXY_SCANNING_FAIL_OPEN") setEnvString(&c.Scanning.Timeout, "PROXY_SCANNING_TIMEOUT") setEnvString(&c.Scanning.SigningKey, "PROXY_SCANNING_SIGNING_KEY") setEnvString(&c.Scanning.FetchBaseURL, "PROXY_SCANNING_FETCH_BASE_URL") - setEnvBool(&c.CacheMetadata, "PROXY_CACHE_METADATA") - setEnvBool(&c.MirrorAPI, "PROXY_MIRROR_API") - setEnvBool(&c.Hosted.Enabled, "PROXY_HOSTED_ENABLED") + c.setEnvBool(&c.CacheMetadata, "PROXY_CACHE_METADATA") + c.setEnvBool(&c.MirrorAPI, "PROXY_MIRROR_API") + c.setEnvBool(&c.CacheDelete, "PROXY_CACHE_DELETE") + c.setEnvBool(&c.Hosted.Enabled, "PROXY_HOSTED_ENABLED") setEnvString(&c.Hosted.Token, "PROXY_HOSTED_TOKEN") setEnvString(&c.Hosted.MaxUploadSize, "PROXY_HOSTED_MAX_UPLOAD_SIZE") setEnvStringSlice(&c.Hosted.NPMScopes, "PROXY_HOSTED_NPM_SCOPES") setEnvStringSlice(&c.Hosted.ComposerVendors, "PROXY_HOSTED_COMPOSER_VENDORS") + c.setEnvBool(&c.Projects.Enabled, "PROXY_PROJECTS_ENABLED") + setEnvString(&c.Projects.Token, "PROXY_PROJECTS_TOKEN") + setEnvString(&c.Projects.MaxAge, "PROXY_PROJECTS_MAX_AGE") setEnvString(&c.MetadataTTL, "PROXY_METADATA_TTL") setEnvString(&c.MetadataMaxSize, "PROXY_METADATA_MAX_SIZE") + setEnvString(&c.MetadataStreamMaxSize, "PROXY_METADATA_STREAM_MAX_SIZE") setEnvString(&c.ArtifactMaxSize, "PROXY_ARTIFACT_MAX_SIZE") setEnvString(&c.MetadataRewriteCacheSize, "PROXY_METADATA_REWRITE_CACHE_SIZE") setEnvString(&c.HTTPTimeout, "PROXY_HTTP_TIMEOUT") - setEnvBool(&c.Gradle.BuildCache.ReadOnly, "PROXY_GRADLE_BUILD_CACHE_READ_ONLY") + setEnvString(&c.WriteTimeout, "PROXY_WRITE_TIMEOUT") + setEnvString(&c.ArtifactTimeout, "PROXY_ARTIFACT_TIMEOUT") + c.setGradleReadOnlyFromEnv() setEnvString(&c.Gradle.BuildCache.MaxUploadSize, "PROXY_GRADLE_BUILD_CACHE_MAX_UPLOAD_SIZE") setEnvString(&c.Gradle.BuildCache.MaxAge, "PROXY_GRADLE_BUILD_CACHE_MAX_AGE") setEnvString(&c.Gradle.BuildCache.MaxSize, "PROXY_GRADLE_BUILD_CACHE_MAX_SIZE") setEnvString(&c.Gradle.BuildCache.SweepInterval, "PROXY_GRADLE_BUILD_CACHE_SWEEP_INTERVAL") setEnvString(&c.Health.StorageProbeInterval, "PROXY_HEALTH_STORAGE_PROBE_INTERVAL") + setEnvString(&c.Git.CacheDir, "PROXY_GIT_CACHE_DIR") + setEnvString(&c.Git.MaxSize, "PROXY_GIT_MAX_SIZE") + setEnvString(&c.Git.MaxRepoSize, "PROXY_GIT_MAX_REPO_SIZE") + setEnvString(&c.Git.RefreshWait, "PROXY_GIT_REFRESH_WAIT") + setEnvString(&c.Git.StaleMaxAge, "PROXY_GIT_STALE_MAX_AGE") } // validateAbsoluteURL returns an error if value is not a parseable URL with @@ -1294,8 +1680,8 @@ func (c *Config) Validate() error { // Validate direct serve TTL if specified if c.Storage.DirectServeTTL != "" { - if _, err := time.ParseDuration(c.Storage.DirectServeTTL); err != nil { - return fmt.Errorf("invalid storage.direct_serve_ttl %q: %w", c.Storage.DirectServeTTL, err) + if _, err := parseNonNegativeDuration("storage.direct_serve_ttl", c.Storage.DirectServeTTL); err != nil { + return err } } @@ -1312,8 +1698,8 @@ func (c *Config) Validate() error { // Validate metadata TTL if specified if c.MetadataTTL != "" && c.MetadataTTL != "0" { - if _, err := time.ParseDuration(c.MetadataTTL); err != nil { - return fmt.Errorf("invalid metadata_ttl %q: %w", c.MetadataTTL, err) + if _, err := parseNonNegativeDuration("metadata_ttl", c.MetadataTTL); err != nil { + return err } } @@ -1321,7 +1707,7 @@ func (c *Config) Validate() error { return err } - if err := validateHTTPTimeout(c.HTTPTimeout); err != nil { + if err := c.validateRequestTimeouts(); err != nil { return err } @@ -1343,6 +1729,10 @@ func (c *Config) validateCacheArtifacts() error { return fmt.Errorf("storage.cache_artifacts: false cannot be combined with storage.direct_serve: no artifacts are stored to redirect to") case c.MirrorAPI: return fmt.Errorf("storage.cache_artifacts: false cannot be combined with mirror_api: mirrored artifacts would never be served") + case len(c.Mirror.Schedules) > 0: + return fmt.Errorf("storage.cache_artifacts: false cannot be combined with mirror.schedules: mirrored artifacts would never be served") + case c.Mirror.Refresh != nil: + return fmt.Errorf("storage.cache_artifacts: false cannot be combined with mirror.refresh: mirrored artifacts would never be served") case c.Hosted.Enabled: return fmt.Errorf("storage.cache_artifacts: false cannot be combined with hosted.enabled: pushed packages would never be served") } @@ -1350,6 +1740,10 @@ func (c *Config) validateCacheArtifacts() error { } func (c *Config) validateComponents() error { + if err := c.Cooldown.ValidateProfiles(); err != nil { + return err + } + if err := validateMetadataRewriteCacheSize(c.MetadataRewriteCacheSize); err != nil { return err } @@ -1377,6 +1771,22 @@ func (c *Config) validateComponents() error { if err := c.Hosted.Validate(); err != nil { return err } + if _, reserved := c.Upstream.Generic[HostedGenericRepository]; reserved && c.Hosted.Enabled { + return fmt.Errorf("invalid upstream.generic name %q: reserved for pushed files at /generic/%s/ when hosted.enabled is set", + HostedGenericRepository, HostedGenericRepository) + } + + if err := c.Projects.Validate(); err != nil { + return err + } + + if err := c.Mirror.Validate(); err != nil { + return err + } + + if err := c.Git.Validate(); err != nil { + return err + } return c.Gradle.BuildCache.Validate() } @@ -1439,9 +1849,12 @@ func (g *GradleBuildCacheConfig) Validate() error { const ( defaultMetadataTTL = 5 * time.Minute //nolint:mnd // sensible default defaultDirectServeTTL = 15 * time.Minute //nolint:mnd // sensible default + defaultWriteTimeout = 5 * time.Minute + defaultArtifactTimeout = 5 * time.Minute defaultHTTPTimeout = 30 * time.Second //nolint:mnd // sensible default defaultHitFlushInterval = time.Second defaultMetadataMaxSize = 100 << 20 + defaultMetadataStreamMaxSize = 1 << 30 defaultMetadataRewriteCacheSize = 256 << 20 defaultGradleBuildCacheMaxUploadSize = 100 << 20 defaultGradleBuildCacheSweepInterval = 10 * time.Minute @@ -1467,36 +1880,53 @@ func (c *Config) ParseMaxSize() int64 { return size } -func validateHTTPTimeout(s string) error { +func (c *Config) validateRequestTimeouts() error { + for _, timeout := range []struct{ field, value string }{ + {"http_timeout", c.HTTPTimeout}, + {"write_timeout", c.WriteTimeout}, + {"artifact_timeout", c.ArtifactTimeout}, + } { + if err := validateRequestTimeout(timeout.field, timeout.value); err != nil { + return err + } + } + + return nil +} + +func validateRequestTimeout(field, s string) error { if s == "" || s == "0" { return nil } d, err := time.ParseDuration(s) if err != nil { - return fmt.Errorf("invalid http_timeout %q: %w", s, err) + return fmt.Errorf("invalid %s %q: %w", field, s, err) } if d < 0 { - return fmt.Errorf("invalid http_timeout %q: must be non-negative", s) + return fmt.Errorf("invalid %s %q: must be non-negative", field, s) } return nil } -func validateMetadataMaxSize(s string) error { +func validateMetadataMaxSize(name, s string) error { if s == "" { return nil } size, err := ParseSize(s) if err != nil { - return fmt.Errorf("invalid metadata_max_size: %w", err) + return fmt.Errorf("invalid %s: %w", name, err) } if size <= 0 { - return fmt.Errorf("invalid metadata_max_size %q: must be positive", s) + return fmt.Errorf("invalid %s %q: must be positive", name, s) } return nil } func (c *Config) validateDownloadSizeLimits() error { - if err := validateMetadataMaxSize(c.MetadataMaxSize); err != nil { + if err := validateMetadataMaxSize("metadata_max_size", c.MetadataMaxSize); err != nil { + return err + } + if err := validateMetadataMaxSize("metadata_stream_max_size", c.MetadataStreamMaxSize); err != nil { return err } return validateArtifactMaxSize(c.ArtifactMaxSize) @@ -1559,6 +1989,19 @@ func (c *Config) ParseMetadataMaxSize() int64 { return size } +// ParseMetadataStreamMaxSize returns the size limit for metadata streamed +// into storage in bytes. Returns 1GB if unset or invalid. +func (c *Config) ParseMetadataStreamMaxSize() int64 { + if c.MetadataStreamMaxSize == "" { + return defaultMetadataStreamMaxSize + } + size, err := ParseSize(c.MetadataStreamMaxSize) + if err != nil || size <= 0 { + return defaultMetadataStreamMaxSize + } + return size +} + // ParseArtifactMaxSize returns the artifact size limit in bytes, or 0 for // no limit. func (c *Config) ParseArtifactMaxSize() int64 { @@ -1575,15 +2018,28 @@ func (c *Config) ParseArtifactMaxSize() int64 { // ParseHTTPTimeout returns the upstream HTTP client timeout. // Returns 30s if unset, 0 (no timeout) if explicitly set to "0". func (c *Config) ParseHTTPTimeout() time.Duration { - if c.HTTPTimeout == "" { - return defaultHTTPTimeout + return parseRequestTimeout(c.HTTPTimeout, defaultHTTPTimeout) +} + +// ParseWriteTimeout returns the response write timeout, defaulting to 5m. +// An explicit zero disables the timeout. +func (c *Config) ParseWriteTimeout() time.Duration { + return parseRequestTimeout(c.WriteTimeout, defaultWriteTimeout) +} + +// ParseArtifactTimeout returns the upstream artifact download timeout for +// serving requests, defaulting to 5m. An explicit zero disables the timeout. +func (c *Config) ParseArtifactTimeout() time.Duration { + return parseRequestTimeout(c.ArtifactTimeout, defaultArtifactTimeout) +} + +func parseRequestTimeout(value string, fallback time.Duration) time.Duration { + if value == "" { + return fallback } - if c.HTTPTimeout == "0" { - return 0 - } - d, err := time.ParseDuration(c.HTTPTimeout) + d, err := time.ParseDuration(value) if err != nil || d < 0 { - return defaultHTTPTimeout + return fallback } return d } @@ -1647,6 +2103,20 @@ func (c *Config) ParseGradleBuildCacheMaxUploadSize() int64 { return size } +// ParseAPKSnapshots returns how long earlier Alpine APK indexes are kept +// after upstream replaced them. Returns 0 when snapshots are disabled or the +// value is invalid. +func (c *Config) ParseAPKSnapshots() time.Duration { + if c.Upstream.APKSnapshots == "" { + return 0 + } + d, err := parseDayDuration(c.Upstream.APKSnapshots) + if err != nil || d < 0 { + return 0 + } + return d +} + // ParseGradleBuildCacheMaxAge returns age-based eviction threshold. // Returns 0 when disabled or invalid. func (c *Config) ParseGradleBuildCacheMaxAge() time.Duration { @@ -1729,7 +2199,16 @@ func ParseSize(s string) (int64, error) { if err != nil { return 0, fmt.Errorf("invalid number %q", numStr) } - return int64(num * float64(s2.mult)), nil + // The comparisons also reject NaN. + size := num * float64(s2.mult) + if !(size >= 0 && size < math.MaxInt64) { + return 0, fmt.Errorf("invalid size %q: must be between 0 and %d bytes", s, int64(math.MaxInt64)) + } + // max_size 0 means unlimited, so don't let a tiny size become 0. + if num != 0 && int64(size) == 0 { + return 0, fmt.Errorf("invalid size %q: less than one byte", s) + } + return int64(size), nil } } @@ -1738,6 +2217,9 @@ func ParseSize(s string) (int64, error) { if err != nil { return 0, fmt.Errorf("invalid size %q", s) } + if num < 0 { + return 0, fmt.Errorf("invalid size %q: must not be negative", s) + } return num, nil } @@ -1778,7 +2260,3 @@ func (a *AuthConfig) Header() (name, value string) { func expandEnv(s string) string { return os.Expand(s, os.Getenv) } - -func envBool(v string) bool { - return v == "true" || v == "1" -} diff --git a/internal/config/config_test.go b/internal/config/config_test.go index e3b0a2c..ff8fc50 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -3,6 +3,7 @@ package config import ( "os" "path/filepath" + "slices" "strings" "testing" "time" @@ -21,6 +22,7 @@ func upstreamConfigValues(upstream UpstreamConfig) map[string]string { "cargo_download": upstream.CargoDownload, "gem": upstream.Gem, "go": upstream.Go, + "go_vulndb": upstream.GoVulnDB, "hex": upstream.Hex, "hex_api": upstream.HexAPI, "pub": upstream.Pub, @@ -33,6 +35,7 @@ func upstreamConfigValues(upstream UpstreamConfig) map[string]string { "composer": upstream.Composer, "composer_repository": upstream.ComposerRepository, "conan": upstream.Conan, + "chef": upstream.Chef, "conda": upstream.Conda, "cran": upstream.CRAN, "julia": upstream.Julia, @@ -52,6 +55,7 @@ func defaultUpstreamValues() map[string]string { "cargo_download": "https://static.crates.io/crates", "gem": "https://rubygems.org", "go": "https://proxy.golang.org", + "go_vulndb": "https://vuln.go.dev", "hex": "https://repo.hex.pm", "hex_api": "https://hex.pm", "pub": "https://pub.dev", @@ -64,6 +68,7 @@ func defaultUpstreamValues() map[string]string { "composer": "https://packagist.org", "composer_repository": "https://repo.packagist.org", "conan": "https://center.conan.io", + "chef": "https://supermarket.chef.io", "conda": "https://conda.anaconda.org", "cran": "https://cloud.r-project.org", "julia": "https://pkg.julialang.org", @@ -83,6 +88,7 @@ func upstreamEnvironmentVariables() map[string]string { "cargo_download": "PROXY_UPSTREAM_CARGO_DOWNLOAD", "gem": "PROXY_UPSTREAM_GEM", "go": "PROXY_UPSTREAM_GO", + "go_vulndb": "PROXY_UPSTREAM_GO_VULNDB", "hex": "PROXY_UPSTREAM_HEX", "hex_api": "PROXY_UPSTREAM_HEX_API", "pub": "PROXY_UPSTREAM_PUB", @@ -95,6 +101,7 @@ func upstreamEnvironmentVariables() map[string]string { "composer": "PROXY_UPSTREAM_COMPOSER", "composer_repository": "PROXY_UPSTREAM_COMPOSER_REPOSITORY", "conan": "PROXY_UPSTREAM_CONAN", + "chef": "PROXY_UPSTREAM_CHEF", "conda": "PROXY_UPSTREAM_CONDA", "cran": "PROXY_UPSTREAM_CRAN", "julia": "PROXY_UPSTREAM_JULIA", @@ -138,6 +145,9 @@ func TestDefault(t *testing.T) { if cfg.Gradle.BuildCache.MaxAge != "168h" { t.Errorf("Gradle.BuildCache.MaxAge = %q, want %q", cfg.Gradle.BuildCache.MaxAge, "168h") } + if !cfg.Gradle.BuildCache.ReadOnly { + t.Error("Gradle.BuildCache.ReadOnly = false, want true by default") + } if len(cfg.Upstream.AllowPrivateHosts) != 0 { t.Errorf("Upstream.AllowPrivateHosts = %v, want empty", cfg.Upstream.AllowPrivateHosts) } @@ -287,6 +297,8 @@ func TestParseSize(t *testing.T) { {"1TB", 1024 * 1024 * 1024 * 1024, false}, {"invalid", 0, true}, {"10XB", 0, true}, + {"0GB", 0, false}, + {"0.0MB", 0, false}, } for _, tt := range tests { @@ -373,6 +385,7 @@ upstream: cargo_download: "https://upstream.example.com/cargo_download" gem: "https://upstream.example.com/gem" go: "https://upstream.example.com/go" + go_vulndb: "https://upstream.example.com/go_vulndb" hex: "https://upstream.example.com/hex" hex_api: "https://upstream.example.com/hex_api" pub: "https://upstream.example.com/pub" @@ -385,6 +398,7 @@ upstream: composer: "https://upstream.example.com/composer" composer_repository: "https://upstream.example.com/composer_repository" conan: "https://upstream.example.com/conan" + chef: "https://upstream.example.com/chef" conda: "https://upstream.example.com/conda" cran: "https://upstream.example.com/cran" julia: "https://upstream.example.com/julia" @@ -417,6 +431,65 @@ upstream: } } +func TestLoadGradleBuildCacheReadOnly(t *testing.T) { + tests := []struct { + name string + content string + want bool + }{ + {"block without read_only keeps default", "gradle:\n build_cache:\n max_age: \"12h\"\n", true}, + {"explicit false allows uploads", "gradle:\n build_cache:\n read_only: false\n", false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + path := filepath.Join(t.TempDir(), "config.yaml") + if err := os.WriteFile(path, []byte(tt.content), 0644); err != nil { + t.Fatalf("writing config file: %v", err) + } + cfg, err := Load(path) + if err != nil { + t.Fatalf("Load() error = %v", err) + } + if cfg.Gradle.BuildCache.ReadOnly != tt.want { + t.Errorf("Gradle.BuildCache.ReadOnly = %v, want %v", cfg.Gradle.BuildCache.ReadOnly, tt.want) + } + }) + } +} + +func TestLoadGradleBuildCacheReadOnlyFromEnv(t *testing.T) { + tests := []struct { + value string + fileRO bool + want bool + warnings int + }{ + {"false", true, false, 0}, + {"0", true, false, 0}, + {" FALSE ", true, false, 0}, + {"True", false, true, 0}, + {"1", false, true, 0}, + {"yes", false, true, 0}, + {"off", true, false, 0}, + {"maybe", false, true, 1}, + {"", false, false, 0}, + } + for _, tt := range tests { + t.Run(tt.value, func(t *testing.T) { + t.Setenv("PROXY_GRADLE_BUILD_CACHE_READ_ONLY", tt.value) + cfg := Default() + cfg.Gradle.BuildCache.ReadOnly = tt.fileRO + cfg.LoadFromEnv() + if cfg.Gradle.BuildCache.ReadOnly != tt.want { + t.Errorf("Gradle.BuildCache.ReadOnly = %v, want %v", cfg.Gradle.BuildCache.ReadOnly, tt.want) + } + if got := len(cfg.EnvWarnings()); got != tt.warnings { + t.Errorf("len(EnvWarnings()) = %d, want %d: %v", got, tt.warnings, cfg.EnvWarnings()) + } + }) + } +} + func TestLoadJSON(t *testing.T) { dir := t.TempDir() path := filepath.Join(dir, "config.json") @@ -466,7 +539,7 @@ func TestLoadFromEnv(t *testing.T) { t.Setenv("PROXY_UI_FAILURE_DETAILS", "true") t.Setenv("PROXY_UPSTREAM_ALLOW_PRIVATE_HOSTS", "registry.internal, 10.0.0.12") t.Setenv("PROXY_UPSTREAM_ALLOW_LOOPBACK", "true") - t.Setenv("PROXY_GRADLE_BUILD_CACHE_READ_ONLY", "true") + t.Setenv("PROXY_GRADLE_BUILD_CACHE_READ_ONLY", "false") t.Setenv("PROXY_GRADLE_BUILD_CACHE_MAX_UPLOAD_SIZE", "32MB") t.Setenv("PROXY_GRADLE_BUILD_CACHE_MAX_AGE", "12h") t.Setenv("PROXY_GRADLE_BUILD_CACHE_MAX_SIZE", "10GB") @@ -517,8 +590,8 @@ func TestLoadFromEnv(t *testing.T) { t.Errorf("Upstream.AllowPrivateHosts after empty env = %q, want unchanged", got) } - if !cfg.Gradle.BuildCache.ReadOnly { - t.Error("Gradle.BuildCache.ReadOnly = false, want true") + if cfg.Gradle.BuildCache.ReadOnly { + t.Error("Gradle.BuildCache.ReadOnly = true, want false from the environment") } if cfg.Gradle.BuildCache.MaxUploadSize != "32MB" { t.Errorf("Gradle.BuildCache.MaxUploadSize = %q, want %q", cfg.Gradle.BuildCache.MaxUploadSize, "32MB") @@ -716,6 +789,29 @@ func TestParseMetadataMaxSize(t *testing.T) { } } +func TestParseMetadataStreamMaxSize(t *testing.T) { + cfg := Default() + if got := cfg.ParseMetadataStreamMaxSize(); got != defaultMetadataStreamMaxSize { + t.Errorf("unset: %d, want %d", got, defaultMetadataStreamMaxSize) + } + cfg.MetadataStreamMaxSize = "2GB" + if got := cfg.ParseMetadataStreamMaxSize(); got != 2<<30 { + t.Errorf("2GB: %d", got) + } + t.Setenv("PROXY_METADATA_STREAM_MAX_SIZE", "300MB") + cfg = Default() + cfg.LoadFromEnv() + if got := cfg.ParseMetadataStreamMaxSize(); got != 300<<20 { + t.Errorf("from env: %d", got) + } + for _, bad := range []string{"0", "lots"} { + cfg.MetadataStreamMaxSize = bad + if err := cfg.Validate(); err == nil { + t.Errorf("metadata_stream_max_size %q validated", bad) + } + } +} + func TestValidateMetadataMaxSize(t *testing.T) { cfg := Default() cfg.MetadataMaxSize = "not-a-size" @@ -1072,6 +1168,17 @@ func TestLoadMetadataTTLFromEnv(t *testing.T) { } } +func TestLoadChangeFeedsFromEnv(t *testing.T) { + cfg := Default() + t.Setenv("PROXY_UPSTREAM_NPM_CHANGE_FEED", "true") + t.Setenv("PROXY_UPSTREAM_COMPOSER_CHANGE_FEED", "true") + cfg.LoadFromEnv() + + if !cfg.Upstream.NPMChangeFeed || !cfg.Upstream.ComposerChangeFeed { + t.Errorf("change feeds = npm %t, composer %t, want both on", cfg.Upstream.NPMChangeFeed, cfg.Upstream.ComposerChangeFeed) + } +} + func TestParseGradleBuildCacheConfig(t *testing.T) { cfg := Default() @@ -1257,6 +1364,13 @@ func TestUpstreamAuthForURLMatchesURLComponents(t *testing.T) { {name: "lookalike host rejected", url: "https://registry.example.com.evil.test/package"}, {name: "different scheme rejected", url: "http://registry.example.com/package"}, {name: "different port rejected", url: "https://registry.example.com:8443/package"}, + {name: "dot dot segment rejected", url: "https://registry.example.com/private/../package"}, + {name: "encoded dot dot segment rejected", url: "https://registry.example.com/private/%2e%2e/package"}, + {name: "double encoded dot dot segment rejected", url: "https://registry.example.com/private/%252e%252e/package"}, + {name: "dot segment rejected", url: "https://registry.example.com/private/./package"}, + {name: "dot dot segment with parameter rejected", url: "https://registry.example.com/private/..;/package"}, + {name: "encoded dot dot segment with parameter rejected", url: "https://registry.example.com/private/%2e%2e;x/package"}, + {name: "dot dot segment with encoded parameter rejected", url: "https://registry.example.com/private/..%3b/package"}, } for _, tt := range tests { @@ -1653,6 +1767,30 @@ func TestValidateGoSumDBs(t *testing.T) { cfg.Upstream.GoSumDBsOffline = true }, }, + { + name: "npm change feed requires metadata caching", + modify: func(cfg *Config) { + cfg.CacheMetadata = false + cfg.Upstream.NPMChangeFeed = true + }, + wantErr: true, + }, + { + name: "Composer change feed requires metadata caching", + modify: func(cfg *Config) { + cfg.CacheMetadata = false + cfg.Upstream.ComposerChangeFeed = true + }, + wantErr: true, + }, + { + name: "change feeds with metadata caching", + modify: func(cfg *Config) { + cfg.CacheMetadata = true + cfg.Upstream.NPMChangeFeed = true + cfg.Upstream.ComposerChangeFeed = true + }, + }, } for _, tt := range tests { @@ -1773,3 +1911,363 @@ func TestLoadArtifactMaxSizeFromEnv(t *testing.T) { t.Errorf("ArtifactMaxSize = %q, want %q", cfg.ArtifactMaxSize, "2GB") } } + +func TestMavenRepositoryNames(t *testing.T) { + for _, tt := range []struct { + name string + wantErr bool + }{ + {"grails", false}, + {"grails-restricted", false}, + {"company-releases", false}, + {"org", true}, + {"com", true}, + {"tools", true}, + {"software", true}, + {"jakarta", true}, + {"javax", true}, + {"junit", true}, + {"androidx", true}, + {"gradle", true}, + {"nebula", true}, + {"my repo", true}, + {"rel#1", true}, + {"rel?x", true}, + {"-releases", true}, + {"repo_2.x", false}, + {"ORG", false}, + {"Tools", false}, + {"io", true}, + {"IO", true}, + {"de", true}, + {"x", true}, + {"net", true}, + {"a/b", true}, + } { + cfg := Default() + cfg.Upstream.MavenRepositories = map[string]string{tt.name: "https://repo.example/maven"} + err := cfg.Validate() + if (err != nil) != tt.wantErr { + t.Errorf("maven_repositories name %q: error = %v, want error %v", tt.name, err, tt.wantErr) + } + } + + cfg := Default() + cfg.Upstream.MavenRepositories = map[string]string{"grails": "not a url"} + if err := cfg.Validate(); err == nil { + t.Error("maven_repositories with an invalid URL: want an error") + } +} + +func TestGenericUpstreamNamedHosted(t *testing.T) { + cfg := Default() + cfg.Upstream.Generic = map[string]string{"hosted": "https://example.com"} + if err := cfg.Validate(); err != nil { + t.Errorf("upstream.generic named hosted with hosting off: %v, want it accepted", err) + } + + cfg = Default() + cfg.Upstream.Generic = map[string]string{"hosted": "https://example.com"} + cfg.Hosted.Enabled = true + cfg.Hosted.Token = "secret" + if err := cfg.Validate(); err == nil || !strings.Contains(err.Error(), "reserved") { + t.Errorf("upstream.generic named hosted with hosting on: %v, want it refused", err) + } +} + +func TestValidateFreeBSDUpstreams(t *testing.T) { + tests := []struct { + name string + freebsd map[string]string + wantErr bool + }{ + {"valid", map[string]string{"freebsd": "https://pkg.freebsd.org", "poudriere": "https://packages.example.com"}, false}, + {"name contains path separator", map[string]string{"freebsd/ports": "https://pkg.freebsd.org"}, true}, + {"URL is not absolute", map[string]string{"freebsd": "pkg.freebsd.org"}, true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + cfg := Default() + cfg.Upstream.FreeBSD = tt.freebsd + if err := cfg.Validate(); (err != nil) != tt.wantErr { + t.Errorf("Validate() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } +} + +func TestValidateGenericPaths(t *testing.T) { + githubAPI := map[string]string{"github-api": "https://api.github.com"} + token := map[string]AuthConfig{"https://api.github.com": {Type: "bearer", Token: "t"}} + tests := []struct { + name string + upstream UpstreamConfig + wantErr bool + }{ + {name: "public", upstream: UpstreamConfig{Generic: githubAPI}}, + {name: "credentials without paths", upstream: UpstreamConfig{Generic: githubAPI, Auth: token}, wantErr: true}, + { + name: "credentials for a path under the upstream", + upstream: UpstreamConfig{ + Generic: githubAPI, + Auth: map[string]AuthConfig{"https://api.github.com/repos/acme": {Type: "bearer", Token: "t"}}, + }, + wantErr: true, + }, + { + name: "credentials with paths", + upstream: UpstreamConfig{ + Generic: githubAPI, + GenericPaths: map[string][]string{"github-api": {"repos/*/*/releases/**"}}, + Auth: token, + }, + }, + { + name: "credentials for another host", + upstream: UpstreamConfig{ + Generic: githubAPI, + Auth: map[string]AuthConfig{"https://npm.example": {Type: "bearer", Token: "t"}}, + }, + }, + { + name: "paths for an unknown upstream", + upstream: UpstreamConfig{ + Generic: githubAPI, + GenericPaths: map[string][]string{"github": {"*/*/releases/**"}}, + }, + wantErr: true, + }, + { + name: "bad pattern", + upstream: UpstreamConfig{ + Generic: githubAPI, + GenericPaths: map[string][]string{"github-api": {"["}}, + }, + wantErr: true, + }, + { + name: "empty pattern", + upstream: UpstreamConfig{ + Generic: githubAPI, + GenericPaths: map[string][]string{"github-api": {""}}, + }, + wantErr: true, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if err := tt.upstream.Validate(); (err != nil) != tt.wantErr { + t.Errorf("Validate() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } +} + +func TestGenericPathAllowed(t *testing.T) { + patterns := []string{"repos/*/*/releases/**", "rate_limit"} + tests := []struct { + path string + want bool + }{ + {"repos/jqlang/jq/releases/tags/jq-1.7.1", true}, + {"repos/jqlang/jq/releases/latest", true}, + {"rate_limit", true}, + {"repos/jqlang/jq/releases", false}, + {"repos/acme/private/contents/secret.txt", false}, + {"user/repos", false}, + {"repos/jqlang/jq/releases/%2e%2e", false}, + {"repos/jqlang/jq?/releases/x", false}, + {"repos/jqlang/jq/releases/x#y", false}, + {`repos/jqlang/jq/releases/x\y`, false}, + } + for _, tt := range tests { + if got := GenericPathAllowed(patterns, tt.path); got != tt.want { + t.Errorf("GenericPathAllowed(%q) = %v, want %v", tt.path, got, tt.want) + } + } + if !GenericPathAllowed(nil, "user/repos") { + t.Error("GenericPathAllowed without patterns refused a path") + } +} + +func TestLoadGenericPaths(t *testing.T) { + path := filepath.Join(t.TempDir(), "config.yaml") + data := []byte(` +upstream: + generic: + github-api: https://api.github.com + generic_paths: + github-api: + - "repos/*/*/releases/**" + auth: + "https://api.github.com": + type: bearer + token: t +`) + if err := os.WriteFile(path, data, 0o600); err != nil { + t.Fatal(err) + } + cfg, err := Load(path) + if err != nil { + t.Fatalf("Load: %v", err) + } + if err := cfg.Validate(); err != nil { + t.Fatalf("Validate: %v", err) + } + if got := cfg.Upstream.GenericPaths["github-api"]; len(got) != 1 || got[0] != "repos/*/*/releases/**" { + t.Errorf("generic_paths = %v", cfg.Upstream.GenericPaths) + } +} + +func TestAPKSnapshots(t *testing.T) { + cfg := Default() + if got := cfg.ParseAPKSnapshots(); got != 0 { + t.Errorf("default ParseAPKSnapshots = %v, want 0", got) + } + + for value, want := range map[string]time.Duration{ + "90d": 90 * 24 * time.Hour, + "12h": 12 * time.Hour, + "0": 0, + } { + cfg.Upstream.APKSnapshots = value + if err := cfg.Validate(); err != nil { + t.Errorf("Validate(%q): %v", value, err) + } + if got := cfg.ParseAPKSnapshots(); got != want { + t.Errorf("ParseAPKSnapshots(%q) = %v, want %v", value, got, want) + } + } + + for _, value := range []string{"forever", "-1d"} { + cfg.Upstream.APKSnapshots = value + if err := cfg.Validate(); err == nil { + t.Errorf("Validate(%q) succeeded, want an error", value) + } + } + + cfg = Default() + t.Setenv("PROXY_UPSTREAM_APK_SNAPSHOTS", "30d") + cfg.LoadFromEnv() + if cfg.Upstream.APKSnapshots != "30d" { + t.Errorf("APKSnapshots from env = %q, want 30d", cfg.Upstream.APKSnapshots) + } +} + +func TestCooldownShortest(t *testing.T) { + for _, tc := range []struct { + name string + cfg *CooldownConfig + want time.Duration + }{ + {"nil", nil, 0}, + {"none", &CooldownConfig{Default: "0"}, 0}, + {"default", &CooldownConfig{Default: "3d"}, 72 * time.Hour}, + {"ecosystem", &CooldownConfig{Default: "3d", Ecosystems: map[string]string{"npm": "2d", "deb": "0"}}, 48 * time.Hour}, + {"package", &CooldownConfig{Default: "3d", Packages: map[string]string{"pkg:npm/lodash": "6h"}}, 6 * time.Hour}, + {"pattern", &CooldownConfig{Default: "0", PackagePatterns: map[string]string{"pkg:npm/@acme/*": "90m"}}, 90 * time.Minute}, + {"invalid ignored", &CooldownConfig{Default: "3d", Ecosystems: map[string]string{"npm": "soon"}}, 72 * time.Hour}, + } { + if got := tc.cfg.Shortest(); got != tc.want { + t.Errorf("%s: Shortest() = %v, want %v", tc.name, got, tc.want) + } + } +} + +func TestLoadBoolsFromEnvParseStrictly(t *testing.T) { + t.Run("no turns off a setting from the config file", func(t *testing.T) { + t.Setenv("PROXY_TRUST_FORWARDED_FOR", "no") + cfg := Default() + cfg.TrustForwardedFor = true + cfg.LoadFromEnv() + if cfg.TrustForwardedFor { + t.Error("TrustForwardedFor = true, want false") + } + }) + + tests := []struct { + value string + start bool + want bool + warnings int + }{ + {"true", false, true, 0}, + {"True", false, true, 0}, + {" TRUE ", false, true, 0}, + {"1", false, true, 0}, + {"false", true, false, 0}, + {"FALSE", true, false, 0}, + {"0", true, false, 0}, + {"yes", false, true, 0}, + {" On ", false, true, 0}, + {"no", true, false, 0}, + {"OFF", true, false, 0}, + {"maybe", false, false, 1}, + {"ture", true, true, 1}, + } + for _, tt := range tests { + t.Run(tt.value, func(t *testing.T) { + t.Setenv("PROXY_SCANNING_ENABLED", tt.value) + cfg := Default() + cfg.Scanning.Enabled = tt.start + cfg.LoadFromEnv() + if cfg.Scanning.Enabled != tt.want { + t.Errorf("Scanning.Enabled = %v, want %v", cfg.Scanning.Enabled, tt.want) + } + if got := len(cfg.EnvWarnings()); got != tt.warnings { + t.Errorf("len(EnvWarnings()) = %d, want %d: %v", got, tt.warnings, cfg.EnvWarnings()) + } + }) + } +} + +func TestScannerEcosystems(t *testing.T) { + cfg := ScanningConfig{ + Enabled: true, + SigningKey: "s3cret", + Scanners: []ScannerConfig{{ + Name: "clamav", URL: "http://scanner.invalid/scan", + Ecosystems: []string{"go", "Docker", "rubygems", "npm", "arch", "git"}, + }}, + } + if err := cfg.Validate(); err != nil { + t.Fatalf("Validate() error: %v", err) + } + want := []string{"golang", "oci", "gem", "npm", "arch", "git"} + if got := cfg.Scanners[0].Ecosystems; !slices.Equal(got, want) { + t.Errorf("Ecosystems = %v, want %v", got, want) + } + + cfg.Scanners[0].Ecosystems = []string{"npm", "pypy"} + err := cfg.Validate() + if err == nil || !strings.Contains(err.Error(), "pypy") { + t.Errorf("Validate() error = %v, want unknown ecosystem pypy", err) + } +} + +func TestParseSizeRejectsOutOfRange(t *testing.T) { + for _, s := range []string{"-5GB", "-1", "-0.5K", "NaNGB", "InfGB", "+InfB", "1e30GB", "9999999999TB", "0.5B", "0.000000000001GB"} { + if got, err := ParseSize(s); err == nil { + t.Errorf("ParseSize(%q) = %d, want error", s, got) + } + } + cfg := Default() + cfg.Storage.MaxSize = "-5GB" + if err := cfg.Validate(); err == nil { + t.Error("Validate() accepted storage.max_size -5GB") + } +} + +func TestValidateRejectsNegativeTTLs(t *testing.T) { + cfg := Default() + cfg.MetadataTTL = "-5m" + if err := cfg.Validate(); err == nil { + t.Error("Validate() accepted metadata_ttl -5m") + } + + cfg = Default() + cfg.Storage.DirectServeTTL = "-5m" + if err := cfg.Validate(); err == nil { + t.Error("Validate() accepted storage.direct_serve_ttl -5m") + } +} diff --git a/internal/config/cooldown_profiles.go b/internal/config/cooldown_profiles.go new file mode 100644 index 0000000..225dd20 --- /dev/null +++ b/internal/config/cooldown_profiles.go @@ -0,0 +1,64 @@ +package config + +import ( + "fmt" + "maps" + "regexp" + "slices" + + "github.com/git-pkgs/cooldown" +) + +var cooldownProfileName = regexp.MustCompile(`^[a-z0-9][a-z0-9_-]*$`) + +// Policy builds the policy for this URL's cooldown settings. +func (c *CooldownConfig) Policy() (*cooldown.Policy, error) { + return cooldown.NewPolicy(&cooldown.Config{ + Default: c.Default, Ecosystems: c.Ecosystems, Packages: c.NormalizedPackages(), + }, c.PackagePatterns) +} + +// ValidateProfiles checks names and policies before they become routes. +func (c *CooldownConfig) ValidateProfiles() error { + for _, name := range slices.Sorted(maps.Keys(c.Profiles)) { + profile := c.Profiles[name] + if !cooldownProfileName.MatchString(name) { + return fmt.Errorf("invalid cooldown profile name %q: use lowercase letters, digits, hyphens or underscores", name) + } + if len(profile.Profiles) > 0 { + return fmt.Errorf("cooldown.profiles.%s cannot contain profiles", name) + } + if err := profile.validateProfileDurations(); err != nil { + return fmt.Errorf("cooldown.profiles.%s: %w", name, err) + } + if _, err := profile.Policy(); err != nil { + return fmt.Errorf("cooldown.profiles.%s: %w", name, err) + } + } + return nil +} + +func (c *CooldownConfig) validateProfileDurations() error { + values := map[string]string{"default": c.Default} + for group, overrides := range map[string]map[string]string{ + "ecosystems": c.Ecosystems, "packages": c.Packages, "package_patterns": c.PackagePatterns, + } { + for key, value := range overrides { + values[group+"."+key] = value + } + } + for _, key := range slices.Sorted(maps.Keys(values)) { + value := values[key] + if key == "default" && value == "" { + continue + } + duration, err := cooldown.ParseDuration(value) + if err != nil { + return fmt.Errorf("invalid %s: %w", key, err) + } + if duration < 0 { + return fmt.Errorf("invalid %s: duration must be non-negative", key) + } + } + return nil +} diff --git a/internal/config/cooldown_profiles_test.go b/internal/config/cooldown_profiles_test.go new file mode 100644 index 0000000..6f10362 --- /dev/null +++ b/internal/config/cooldown_profiles_test.go @@ -0,0 +1,81 @@ +package config + +import ( + "os" + "path/filepath" + "strings" + "testing" + "time" +) + +func TestLoadCooldownProfiles(t *testing.T) { + filename := filepath.Join(t.TempDir(), "config.yaml") + data := `cooldown: + default: 7d + ecosystems: + npm: "0" + profiles: + 3d: + default: 3d + packages: + "pkg:pypi/Django": "0" + strict: + default: 14d + package_patterns: + "pkg:npm/@example/*": 1d +` + if err := os.WriteFile(filename, []byte(data), 0o600); err != nil { + t.Fatal(err) + } + cfg, err := Load(filename) + if err != nil { + t.Fatal(err) + } + if err := cfg.Validate(); err != nil { + t.Fatal(err) + } + profile := cfg.Cooldown.Profiles["3d"] + policy, err := profile.Policy() + if err != nil { + t.Fatal(err) + } + if got := policy.For("npm", "pkg:npm/demo"); got != 72*time.Hour { + t.Fatalf("profile inherited global ecosystem override: %v", got) + } + if got := policy.For("pypi", "pkg:pypi/django"); got != 0 { + t.Fatalf("canonical package override = %v", got) + } + strict := cfg.Cooldown.Profiles["strict"] + policy, err = strict.Policy() + if err != nil { + t.Fatal(err) + } + if got := policy.For("npm", "pkg:npm/%40example/tool"); got != 24*time.Hour { + t.Fatalf("profile pattern = %v", got) + } +} + +func TestLoadRejectsInvalidCooldownProfiles(t *testing.T) { + for _, tc := range []struct{ name, profile, want string }{ + {"path", `"a/b": {default: 3d}`, "profile name"}, + {"uppercase", `Strict: {default: 3d}`, "profile name"}, + {"empty", `"": {default: 3d}`, "profile name"}, + {"duration", `strict: {default: nope}`, "cooldown.profiles.strict"}, + {"pattern", `strict: {package_patterns: {"pkg:npm/[": 3d}}`, "cooldown.profiles.strict"}, + {"nested", `strict: {profiles: {nested: {default: 3d}}}`, "cannot contain profiles"}, + } { + t.Run(tc.name, func(t *testing.T) { + filename := filepath.Join(t.TempDir(), "config.yaml") + if err := os.WriteFile(filename, []byte("cooldown:\n profiles:\n "+tc.profile+"\n"), 0o600); err != nil { + t.Fatal(err) + } + cfg, err := Load(filename) + if err == nil { + err = cfg.Validate() + } + if err == nil || !strings.Contains(err.Error(), tc.want) { + t.Fatalf("Load error = %v, want %q", err, tc.want) + } + }) + } +} diff --git a/internal/config/git.go b/internal/config/git.go new file mode 100644 index 0000000..860adb7 --- /dev/null +++ b/internal/config/git.go @@ -0,0 +1,224 @@ +package config + +import ( + "encoding/json" + "fmt" + "path" + "strings" + "time" + + "gopkg.in/yaml.v3" +) + +const ( + defaultGitCacheDir = "./cache/git" + defaultGitMaxRepoSize = "5GB" + defaultGitRefreshWait = "5s" + defaultGitStaleMaxAge = "24h" +) + +// GitUpstream is an upstream.git entry: a Git server's base URL and, +// optionally, the repositories under it that may be served. In YAML or JSON +// it is either the URL alone or an object with url and repos. +type GitUpstream struct { + URL string `json:"url" yaml:"url"` + + // Repos lists path.Match patterns for repository paths under URL, such + // as "mediawiki/*". A pattern ending in "/**" also matches every + // repository nested below its prefix: "mediawiki/**" matches + // mediawiki/skins/Vector. Empty allows every repository. Required when + // upstream.auth has credentials for the URL, since everyone who can + // reach the proxy can read what it serves. + Repos []string `json:"repos" yaml:"repos"` +} + +// UnmarshalYAML accepts a bare URL as well as the object form. +func (g *GitUpstream) UnmarshalYAML(node *yaml.Node) error { + if node.Kind == yaml.ScalarNode { + return node.Decode(&g.URL) + } + type plain GitUpstream + return node.Decode((*plain)(g)) +} + +// UnmarshalJSON accepts a bare URL as well as the object form. +func (g *GitUpstream) UnmarshalJSON(data []byte) error { + if err := json.Unmarshal(data, &g.URL); err == nil { + return nil + } + type plain GitUpstream + return json.Unmarshal(data, (*plain)(g)) +} + +// AllowsRepo reports whether repo, a path under URL, may be served. +func (g GitUpstream) AllowsRepo(repo string) bool { + if len(g.Repos) == 0 { + return true + } + for _, pattern := range g.Repos { + if matchRepoPattern(pattern, repo) { + return true + } + } + return false +} + +func matchRepoPattern(pattern, repo string) bool { + prefix, nested := strings.CutSuffix(pattern, "/**") + if !nested { + ok, _ := path.Match(pattern, repo) + return ok + } + segments := strings.Count(prefix, "/") + 1 + parts := strings.SplitN(repo, "/", segments+1) + if len(parts) <= segments { + return false + } + ok, _ := path.Match(prefix, strings.Join(parts[:segments], "/")) + return ok +} + +// GitConfig configures the Git repository cache behind /git/{name}/. +type GitConfig struct { + // CacheDir holds the cached bare repositories. It must be local disk + // used by this process only, which locks it. Default: ./cache/git. + CacheDir string `json:"cache_dir" yaml:"cache_dir"` + + // MaxSize bounds the cache, counting fetches in progress; the least + // recently used repositories not in use are evicted to stay within it. + // Empty or "0" disables the limit. + MaxSize string `json:"max_size" yaml:"max_size"` + + // MaxRepoSize is the most one repository may take; a clone or fetch that + // would pass it fails. "0" disables the limit. Default: 5GB. MaxSize + // caps it when set. + MaxRepoSize string `json:"max_repo_size" yaml:"max_repo_size"` + + // RefreshWait is how long a request waits for the upstream's branches + // and tags to be checked before it is served the cached copy. A fetch of + // new commits the check finds is waited for in full. Default: 5s. + RefreshWait string `json:"refresh_wait" yaml:"refresh_wait"` + + // StaleMaxAge is how long after the last successful upstream check a + // cached copy may still be served when the upstream fails or is slow. + // Default: 24h. + StaleMaxAge string `json:"stale_max_age" yaml:"stale_max_age"` + + maxSize int64 + maxRepoSize int64 + refreshWait time.Duration + staleMaxAge time.Duration +} + +// MaxSizeBytes returns the parsed MaxSize, 0 for no limit. Validate must run first. +func (g *GitConfig) MaxSizeBytes() int64 { return g.maxSize } + +// MaxRepoSizeBytes returns the parsed MaxRepoSize, 0 for no limit. Validate must run first. +func (g *GitConfig) MaxRepoSizeBytes() int64 { return g.maxRepoSize } + +// RefreshWaitDuration returns the parsed RefreshWait. Validate must run first. +func (g *GitConfig) RefreshWaitDuration() time.Duration { return g.refreshWait } + +// StaleMaxAgeDuration returns the parsed StaleMaxAge. Validate must run first. +func (g *GitConfig) StaleMaxAgeDuration() time.Duration { return g.staleMaxAge } + +// Validate checks the Git cache settings, applying defaults where unset. +func (g *GitConfig) Validate() error { + if g.CacheDir == "" { + g.CacheDir = defaultGitCacheDir + } + if g.MaxRepoSize == "" { + g.MaxRepoSize = defaultGitMaxRepoSize + } + if g.RefreshWait == "" { + g.RefreshWait = defaultGitRefreshWait + } + if g.StaleMaxAge == "" { + g.StaleMaxAge = defaultGitStaleMaxAge + } + + var err error + if g.maxSize, err = parseNonNegativeSize("git.max_size", g.MaxSize); err != nil { + return err + } + if g.maxRepoSize, err = parseNonNegativeSize("git.max_repo_size", g.MaxRepoSize); err != nil { + return err + } + if g.refreshWait, err = parseNonNegativeDuration("git.refresh_wait", g.RefreshWait); err != nil { + return err + } + if g.staleMaxAge, err = parseNonNegativeDuration("git.stale_max_age", g.StaleMaxAge); err != nil { + return err + } + return nil +} + +func parseNonNegativeSize(field, value string) (int64, error) { + size, err := ParseSize(value) + if err != nil { + return 0, fmt.Errorf("invalid %s: %w", field, err) + } + if size < 0 { + return 0, fmt.Errorf("invalid %s %q: must not be negative", field, value) + } + return size, nil +} + +func parseNonNegativeDuration(field, value string) (time.Duration, error) { + d, err := time.ParseDuration(value) + if err != nil { + return 0, fmt.Errorf("invalid %s %q: %w", field, value, err) + } + if d < 0 { + return 0, fmt.Errorf("invalid %s %q: must not be negative", field, value) + } + return d, nil +} + +// validateGitUpstreams checks upstream.git names, URLs and repository +// patterns. An upstream that upstream.auth has credentials for must list its +// repositories, so configuring a token does not open every repository it can +// read to everyone who can reach the proxy. +func (u *UpstreamConfig) validateGitUpstreams() error { + for name, upstream := range u.Git { + field := "upstream.git." + name + if name == "" || name == "." || name == ".." || name[0] == '.' || strings.ContainsAny(name, `/\\`) { + return fmt.Errorf("invalid upstream.git name %q", name) + } + if err := validateAbsoluteURL(field, upstream.URL); err != nil { + return err + } + if scheme, _, _ := strings.Cut(upstream.URL, "://"); !strings.EqualFold(scheme, "https") && !strings.EqualFold(scheme, "http") { + return fmt.Errorf("invalid %s %q: only http and https are supported", field, upstream.URL) + } + for _, pattern := range upstream.Repos { + if _, err := path.Match(strings.TrimSuffix(pattern, "/**"), ""); pattern == "" || err != nil { + return fmt.Errorf("invalid %s.repos pattern %q", field, pattern) + } + } + if len(upstream.Repos) == 0 && u.HasAuthWithin(upstream.URL) { + return fmt.Errorf("%s needs repos: upstream.auth has credentials for %s, "+ + "and everyone who can reach the proxy could read every repository they allow", field, upstream.URL) + } + } + return nil +} + +// HasAuthWithin reports whether an upstream.auth scope covers baseURL or a +// path under it. +func (u *UpstreamConfig) HasAuthWithin(baseURL string) bool { + base, err := parseAuthURL(baseURL) + if err != nil { + return false + } + for scope := range u.Auth { + configured, err := parseAuthURL(scope) + if err != nil { + continue + } + if authURLMatches(configured, base) || authURLMatches(base, configured) { + return true + } + } + return false +} diff --git a/internal/config/git_test.go b/internal/config/git_test.go new file mode 100644 index 0000000..6c9b47b --- /dev/null +++ b/internal/config/git_test.go @@ -0,0 +1,172 @@ +package config + +import ( + "encoding/json" + "os" + "path/filepath" + "slices" + "testing" + "time" + + "gopkg.in/yaml.v3" +) + +func TestGitUpstreamAcceptsURLOrObject(t *testing.T) { + want := map[string]GitUpstream{ + "github": {URL: "https://github.com"}, + "wikimedia": {URL: "https://gitlab.wikimedia.org", Repos: []string{"mediawiki/*"}}, + } + + var fromYAML struct { + Git map[string]GitUpstream `yaml:"git"` + } + err := yaml.Unmarshal([]byte(` +git: + github: "https://github.com" + wikimedia: + url: "https://gitlab.wikimedia.org" + repos: ["mediawiki/*"] +`), &fromYAML) + if err != nil { + t.Fatalf("YAML: %v", err) + } + + var fromJSON struct { + Git map[string]GitUpstream `json:"git"` + } + err = json.Unmarshal([]byte(`{"git": { + "github": "https://github.com", + "wikimedia": {"url": "https://gitlab.wikimedia.org", "repos": ["mediawiki/*"]} + }}`), &fromJSON) + if err != nil { + t.Fatalf("JSON: %v", err) + } + + for format, got := range map[string]map[string]GitUpstream{"YAML": fromYAML.Git, "JSON": fromJSON.Git} { + for name, w := range want { + if g := got[name]; g.URL != w.URL || !slices.Equal(g.Repos, w.Repos) { + t.Errorf("%s %s = %+v, want %+v", format, name, g, w) + } + } + } +} + +func TestGitUpstreamAllowsRepo(t *testing.T) { + open := GitUpstream{URL: "https://github.com"} + if !open.AllowsRepo("any/repo") { + t.Error("an upstream without repos refused a repository") + } + listed := GitUpstream{URL: "https://gitlab.example", Repos: []string{"mediawiki/*", "tools/one", "group/**"}} + for repo, want := range map[string]bool{ + "mediawiki/core": true, + "tools/one": true, + "tools/two": false, + "mediawiki/extensions/Echo": false, + "group/sub/project": true, + "group/project": true, + "group": false, + "groups/project": false, + } { + if got := listed.AllowsRepo(repo); got != want { + t.Errorf("AllowsRepo(%q) = %v, want %v", repo, got, want) + } + } +} + +func TestValidateGitUpstreams(t *testing.T) { + tests := []struct { + name string + upstream UpstreamConfig + wantErr bool + }{ + {name: "public", upstream: UpstreamConfig{Git: map[string]GitUpstream{"github": {URL: "https://github.com"}}}}, + {name: "relative URL", upstream: UpstreamConfig{Git: map[string]GitUpstream{"github": {URL: "github.com"}}}, wantErr: true}, + {name: "name with slash", upstream: UpstreamConfig{Git: map[string]GitUpstream{"a/b": {URL: "https://github.com"}}}, wantErr: true}, + {name: "name with leading dot", upstream: UpstreamConfig{Git: map[string]GitUpstream{".tmp": {URL: "https://github.com"}}}, wantErr: true}, + {name: "bad pattern", upstream: UpstreamConfig{Git: map[string]GitUpstream{"github": {URL: "https://github.com", Repos: []string{"["}}}}, wantErr: true}, + {name: "nested pattern", upstream: UpstreamConfig{Git: map[string]GitUpstream{"gerrit": {URL: "https://gerrit.example/r", Repos: []string{"mediawiki/**"}}}}}, + {name: "ssh URL", upstream: UpstreamConfig{Git: map[string]GitUpstream{"github": {URL: "ssh://git@github.com"}}}, wantErr: true}, + { + name: "credentials without repos", + upstream: UpstreamConfig{ + Git: map[string]GitUpstream{"private": {URL: "https://git.example"}}, + Auth: map[string]AuthConfig{"https://git.example": {Type: "bearer", Token: "t"}}, + }, + wantErr: true, + }, + { + name: "credentials for a path under the upstream", + upstream: UpstreamConfig{ + Git: map[string]GitUpstream{"private": {URL: "https://git.example"}}, + Auth: map[string]AuthConfig{"https://git.example/team": {Type: "bearer", Token: "t"}}, + }, + wantErr: true, + }, + { + name: "credentials with repos", + upstream: UpstreamConfig{ + Git: map[string]GitUpstream{"private": {URL: "https://git.example", Repos: []string{"team/*"}}}, + Auth: map[string]AuthConfig{"https://git.example": {Type: "bearer", Token: "t"}}, + }, + }, + { + name: "credentials for another host", + upstream: UpstreamConfig{ + Git: map[string]GitUpstream{"github": {URL: "https://github.com"}}, + Auth: map[string]AuthConfig{"https://npm.example": {Type: "bearer", Token: "t"}}, + }, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if err := tt.upstream.Validate(); (err != nil) != tt.wantErr { + t.Errorf("Validate() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } +} + +func TestGitConfigDefaults(t *testing.T) { + var g GitConfig + if err := g.Validate(); err != nil { + t.Fatalf("Validate: %v", err) + } + if g.CacheDir != defaultGitCacheDir || g.MaxSizeBytes() != 0 || g.MaxRepoSizeBytes() != 5<<30 || + g.RefreshWaitDuration() != 5*time.Second || g.StaleMaxAgeDuration() != 24*time.Hour { + t.Errorf("defaults = %+v", g) + } + + for _, bad := range []GitConfig{{MaxSize: "lots"}, {RefreshWait: "soon"}, {StaleMaxAge: "-1h"}} { + if err := bad.Validate(); err == nil { + t.Errorf("Validate(%+v) accepted it", bad) + } + } +} + +func TestLoadGitConfig(t *testing.T) { + path := filepath.Join(t.TempDir(), "config.yaml") + data := []byte(` +upstream: + git: + github: https://github.com +git: + cache_dir: /data/git + max_size: 50GB +`) + if err := os.WriteFile(path, data, 0o600); err != nil { + t.Fatal(err) + } + cfg, err := Load(path) + if err != nil { + t.Fatalf("Load: %v", err) + } + t.Setenv("PROXY_GIT_REFRESH_WAIT", "2s") + cfg.LoadFromEnv() + if err := cfg.Validate(); err != nil { + t.Fatalf("Validate: %v", err) + } + if cfg.Upstream.Git["github"].URL != "https://github.com" || cfg.Git.CacheDir != "/data/git" || + cfg.Git.MaxSizeBytes() != 50<<30 || cfg.Git.RefreshWaitDuration() != 2*time.Second { + t.Errorf("loaded %+v and %+v", cfg.Upstream.Git, cfg.Git) + } +} diff --git a/internal/config/maven_group_roots.txt b/internal/config/maven_group_roots.txt new file mode 100644 index 0000000..b199222 --- /dev/null +++ b/internal/config/maven_group_roots.txt @@ -0,0 +1,1228 @@ +# First path segments of group IDs on Maven Central and the Gradle Plugin +# Portal, which the default repository falls back to, plus roots from +# Google's Maven repository. A maven_repositories name from this list would +# hide those groups in the default repository. Regenerate with: +# for u in https://repo1.maven.org/maven2/ https://plugins.gradle.org/m2/; do +# curl -s $u | grep -o 'href="[^"]*/"' | sed 's/href="//;s/\/"//' | grep -v '^\.\.$' +# done | sort -u # then add android and androidx +0x +abbot +ac +academy +acegisecurity +activation +activecluster +activeio +activemq +activemq-jaxb +activesoap +activespace +ad +adarwin +ae +aelfred +aero +africa +ag +agency +agorapulse +ai +aislib +ajk +al +all +alm +altrmi +am +amdonov +amnl +android +androidx +andromda +annogen +ant +ant-contrib +ant-doxygen +ant4eclipse +antlr +anttex +anverus +anvil +aopalliance +apache-jaxme +apl +app +aptconvert +ar +argelbargel +args4j +art +as +ashkay +ashkelon +asia +asm +aspectj +aspectwerkz +at +au +audio +avalon +avalon-activation +avalon-apps +avalon-composition +avalon-cornerstone +avalon-extension +avalon-framework +avalon-http +avalon-logging +avalon-logkit +avalon-meta +avalon-phoenix +avalon-repository +avalon-util +aws +ax +axion +axis +axis2 +az +azote +ba +backport-util-concurrent +backport175 +bairesqa +band +barsuift +baseline +batik +bayern +bcel +bd +be +beehive +beer +berkano +berkeleydb +berlin +best +bet +bg +bi +bike +binky +bio +biz +black +blissed +blog +blue +boo +bot +bouncycastle +box +boxstuff +br +brownshome +bsf +bsh +bue +build +builders +bump +burlap +buzz +by +bz +c10n +c3p0 +ca +cab +cactus +cafe +calces +cam +camp +capital +cards +care +cargo +cas +casa +cash +castor +cat +cc +ccd-sdk +cd +center +cern +cewolf +cf +cglib +cgoit +ch +charlotte +chat +cheap +checkstyle +church +ci +city +cj +cl +classworlds +click +clickstream +clinic +clirr +cloud +clover +club +cm +cmsdeploy +cn +co +coach +cobertura +coconut +cocoon +code +code316 +codehaus +CodeLineCounter +codes +coffee +colaba +colt +com +commons-attributes +commons-beanutils +commons-betwixt +commons-chain +commons-cli +commons-codec +commons-collections +commons-compress +commons-configuration +commons-daemon +commons-dbcp +commons-dbutils +commons-digester +commons-discovery +commons-el +commons-email +commons-fileupload +commons-grafolia +commons-grant +commons-graph +commons-http +commons-httpclient +commons-i18n +commons-io +commons-jdbc2pool +commons-jelly +commons-jexl +commons-jux +commons-jxpath +commons-lang +commons-latka +commons-launcher +commons-logging +commons-math +commons-messenger +commons-modeler +commons-naming +commons-net +commons-pool +commons-primitives +commons-resources +commons-scxml +commons-services +commons-sql +commons-test +commons-threadpool +commons-transaction +commons-util +commons-validator +commons-vfs +commons-xo +community +company +computer +concurrent +consulting +continuum +controlhaus +cool +coop +cornerstone-connection +cornerstone-datasources +cornerstone-scheduler +cornerstone-sockets +cornerstone-store +cornerstone-threads +cos +cover +craft +crimson +cryptix +cssparser +cup +cv +cwoongc +cx +cz +d-haven-event +d-haven-eventbus +d-haven-mpool +d3code +daemoniclabs +dalma +dalms +damagecontrol +dataforge +datasift +date +daveight +davethe8 +day +dbunit +de +decaf +decorutils +default +dentaku +dependency +dependency-maven-plugin +design +dev +digit +digital +dinistiq +directory +directory-asn1 +directory-authx +directory-clients +directory-naming +directory-network +directory-protocols +directory-shared +displaytag +ditchnet +dk +dm +dna +dnsjava +do +docbook +doccheck +docker +dom4j +domify +doxia +drone +drools +drools-examples +ds2 +dsh-vocabulary +dtdparser +dumbster +dwr +dynaop +earth +easyconf +easymock +ec +echo +echo3 +echo3extras +eclipse +eco +ecs +edenlib +edtftp +edu +education +ee +egor-n +ehcache +ejb +el-impl +elect86 +email +emberio +emetriq +emma +energy +engineer +engineering +enterprise +enterprises +ervacon +es +esdk +esper +eu +eus +events +excalibur +excalibur-altrmi +excalibur-cli +excalibur-collections +excalibur-component +excalibur-component-examples +excalibur-component-tests +excalibur-concurrent +excalibur-configuration +excalibur-containerkit +excalibur-datasource +excalibur-event +excalibur-extension +excalibur-fortress +excalibur-i18n +excalibur-instrument +excalibur-instrument-manager +excalibur-instrument-manager-interfaces +excalibur-io +excalibur-lifecycle +excalibur-logger +excalibur-monitor +excalibur-mpool +excalibur-naming +excalibur-pool +excalibur-sourceresolve +excalibur-store +excalibur-thread +excalibur-util +excalibur-xmlutil +exchange +exist +exml +exo +exolabcore +expert +express +exteca +external +ezy +family +fan +fans +farm +fashion +fastutil +fesi +fi +film +finance +financial +findbugs +firebase +firedancer +fish +fit +flavor +flox +flux +fm +fo +foo +fop +forehead +formproc +foundation +foxtrot +fr +framework +freebxml +freemarker +frl +fulcrum +fun +fwrap +fyi +ga +gabriel +gae +games +garden +gay +gbean +gdn +ge +generama +genjar +genjava +gent +geronimo +geronimo-spec +getui +gg +github +glass +glassfish +gliby +global +gmbh +gnu +gnu-regexp +gov +gq +gr +gradle +gradle-autoconf +gradle-clojure +gradle-jenkins-job-dsl-plugin +graphics +graphlayout +green +greendao +gregdev +grizzly +grizzly-cachetest +groovy +groovy-xmlrpc +groovycalamari +groovyx +group +gryphon +gs +gsbase +guru +haibison +hamburg +health +help +hessian +hibernate +hihex +hivemind +hk +hm +hmcts +hnct +Hoop +host +house +howl +hr +hsqldb +htmlunit +HTTPClient +httpcomponents-httpcore +httpunit +hu +hudson +huqi +i +ical4j +icu +icu4j +id +idb +ie +iirekm +ikakara +il +im +immo +in +inc +industries +info +informa +ink +innig +int +io +iq +ir +is +isorelax +it +itext +ivory +izpack +jaas +jaci +jackcess +jackson +jacl +jaf +jaimbot +jakarta +jakarta-regexp +jalopy +james +janino +jardiff +jarjar +jarsync +jasper-jsr199 +jasperreports +java_cup +java2html +java3d +javacc +javaconfig +javadb +javadoc +javaee +javagroups +javainetlocator +javamail +javamuc +javancss +javanettasks +javassist +javatar +javax +javazoom +javolution +jawin +jaxb +jaxen +jaxme +jaxr-ra +jblanket +jboss +jca +jcache +jcharts +jcifs +jcollardbovy +jcom +jcommon +jcoverage +jcs +jcs-javagroups +jcvsii +jdbc +jdbm +jdepend +jdiff +jdo +jdom +jdring +jdsl +je +jen +jencks +jep +jepi +jersey +jetty +jexcelapi +jface +jfree +jfreechart +jgen +jgoodies +jgraph +jgrapht +jgroups +jhunlang +jimmy +jini +jintention +jisp +jivesoftware +jlibdiff +jline +jmagick +jmaki +jmdns +jmfayard +jmimemagic +jmml +jmock +jms +jmscts +jmsn +joda-time +john-test +jotm +jp +jparsec +jpl +jpox +jpox-dbcp +jpox-enhancer +jpox-java5 +jrexx +jrms +jrobin +jruby +jsch +jsf-extensions +jspapi +jsptags +jstl +jstyle +jta +jtds +jtidy +juddi +judy +jug +jung +junit +junit-addons +junit-doclet +junitperf +juno +JuspayAssets +jwebunit +jxta +jython +k8s +kante +kawa +ke +keith +kg +kh +kim +king +kirin +kiwi +kkdt +kliche +koeln +kohsuke +kotlin2ts +kr +krd +kred +kruse +kt-logging +ktorm-tools +kxml +kxml2 +ky +kz +la +land +lat +lazy +lc +ldapd-common +ldapsdk +lenala +lgbt +li +libgdx-oboe +life +lingo +link +live +lk +llc +locc +log4j +log4unit +loggersoft +logkit +lol +loom +love +lpg +lt +ltd +lu +lucene +luisrjaeger +lv +ly +ma +magicGball +maps +market +markets +marmalade +math +maven +maven-integration-test-helper +maven-javanet-plugin +maven-new +maven-plugins +maven-proxy +maven-taglib +maven-torque-plugin +maven-validator +maven-xdoclet2-plugin +maxq +mckoi +md +me +media +merlin +merlin-developer +merlin-tutorial +messenger +metaclass +mevenide +micro +microcontainer +middlegen +mil +milyn +mk +ml +mm +mm-mysql +mn +mnm +mobi +mockcreator +mockit +mockmaker +mockobjects +mockrunner +modello +moe +monetdb +money +monster +mp +mpern +mrj +ms +mstor +msv +mt +mu +mule +muse +mx +mx4j +my +myfaces +mysql +mz +name +nanning +nanocontainer +nebula +nekohtml +neo +net +netbeans +network +neva +new +nexus +nf +ng +ninja +nl +no +norbert +nova +np +nrlssc +nsuml +nu +null +nz +oauth +odmg +oe +ognl +ojb +ojdbc +old +one +oness +onl +online +open +open-esb +opencypher +openejb +openim +openjms +opennms +opensymphony +openxp +oracle +org +org.elasticsearch +org.elasticsearch.client +org.elasticsearch.distribution.integ-test-zip +org.elasticsearch.distribution.zip +org.elasticsearch.gradle +org.elasticsearch.plugin +org.elasticsearch.test +oro +oscube +ovh +p2psockets +p6spy +page +partners +party +pathwaycommons +patterntesting +payload +pcj +pdfbox +pe +penguin +pet +petridish +ph +phd +photos +piccolo +picocontainer +picounit +pink +piotrmadry +pircbot +pitt +pk +pl +plexus +plj +plugin +plus +pluto-container +pm +pmd +pnuts +poi +poolman +portlet-api +postgresql +prevayler +pro +proctor +productions +profiler +progress +projektor +protop +proxool +proxytoys +pt +pub +pubscribe +pull-parser +pw +py +qa +qdox +qfork +quartz +quest +quilt +radeox +re +readline +red +redhill +redis +redmine +regexp +relaxngDatatype +ren +report +reportrunner +rest +rgoldberg +rhino +ricosys +rip +rkennel +ro +robo-guice +roboguice +rocks +rodeo +roller +rome +rpost +rs +rss4j +rsslibj +ru +rubygems +run +sa +sablecc +sagex +sale +sap +sax +saxon +saxpath +sbnarra +sbs +sc +scabbard +schibsted +schoenja +school +schwarz +science +scot +scout +scraping-engine +se +sebersole +security +securityfilter +seek +serg +servicemix +servicemix-ws +services +servletapi +servlets +setpoint +sfx4j +sg +sh +shellix +shocks +shop +show +si +si6 +sillyexceptions +simple +simple-jms +simple-jndi +site +sk +skaringa +ski +skinlf +slide +smartrics +sn +so +soap +social +software +soimp +solar +solarisrealm +solutions +source +space +speexx +spice +spring +springframework +springmodules +sqlline +srl +sshtools +sslext +st +stapler +statcvs +stax +stax-utils +store +stratum +stream +struts +struts-menu +strutstestcase +studio +stxx +su +subpersistence +subshell +substance +suiterunner +surefire +swanysimon +swarmcache +swehacker +swiss +swt +synapticloop +systems +sysunit +tablelayout +tagalog +tagishauth +taglibrarydoc +taglibs +tagsoup +tambora +tane +tangram +tanukisoft +tanvd +tapestry +tclib +team +tec +tech +technology +tekgenesis +tel +temportalist +textarea +tf +th +thad +thaiopensource +thefireplace +tiffrenderer +tjdo +tk +tl +tmporb +to +today +tokyo +tomcat +tomcat-util +tonic +tools +top +toplink +torque +torque-gen +touchstone +town +toys +tqrg +tr +trade +traer +trail-taglib +tranql +travel +trove +trust +tui +turbine +tv +tw +tylerthrailkill +tyrex +tz +ua +uaihebert +ubique +ud +ug +uispec4j +uk +umple +uno +uno-jar +urbanophile +urlrewrite +us +utry +uy +uz +vast +vc +vdoclet +velocity +velocity-anakia +velocity-dvsl +velocity-tools +ventures +vet +vicJuspay +video +view_inspector +village +vin +vinccool96 +vip +vision +vn +vogle +vontikov +vu +wadi +waena +wang +web +webmacro +website +webtest +weixinkeji +werken-xpath +werkflow +werkz +westhawk +wf +wg +which +wicket +wiki +win +wind57 +woodstox +work +works +world +wrapper +ws +ws-commons +ws-commons-java5 +ws-commons-util +ws-scout +wsdl4j +wsrf +wss4j +wstx +wtf +wurfl +wutka +xajile +xalan +xbean +xdoclet +xdoclet-plugins +xerces +xercesjarv +xfire +xfire-root +xin +xjavadoc +xml-apis +xml-resolver +xml-security +xmlbeans +xmldb +xmlenc +xmlmind +xmlpull +xmlrpc +xmlrpc-helma +xmlunit +xmlwise +xmlwriter +xom +xpp3 +xsddoc +xsdlib +xstream +xtc +xtiff-jai +xxl +xyz +yakworks +yan +yanjun +ymsg +yom +za +zip +zm +zone +zw diff --git a/internal/config/mirror.go b/internal/config/mirror.go new file mode 100644 index 0000000..3b56fd8 --- /dev/null +++ b/internal/config/mirror.go @@ -0,0 +1,220 @@ +package config + +import ( + "fmt" + "strings" + "time" + + "github.com/git-pkgs/purl" +) + +const minMirrorScheduleInterval = time.Minute + +// MirrorConfig configures mirroring that the server runs on its own. +type MirrorConfig struct { + // Schedules re-mirror container image tags at a fixed interval, so a + // moved tag is picked up even when nobody pulls it. + Schedules []MirrorSchedule `json:"schedules" yaml:"schedules"` + + // Refresh, when set, keeps the most used packages up to date in the + // background. + Refresh *MirrorRefresh `json:"refresh" yaml:"refresh"` +} + +const ( + defaultMirrorRefreshTop = 50 + defaultMirrorRefreshSince = 14 * 24 * time.Hour +) + +// MirrorRefresh mirrors new releases of the packages clients use most, so +// they are cached before the first client asks for them. +type MirrorRefresh struct { + // Interval is how often the refresh runs, at least one minute (e.g. + // "24h"). + Interval string `json:"interval" yaml:"interval"` + + // Top is how many packages per ecosystem are refreshed, the ones with + // the most downloads among those used within Since. Default: 50. + Top int `json:"top" yaml:"top"` + + // Since is how recently a package must have been downloaded to be + // refreshed (e.g. "14d"). Default: 14d. + Since string `json:"since" yaml:"since"` + + // MaxVersions caps how many new versions one run mirrors. 0 means no + // cap. + MaxVersions int `json:"max_versions" yaml:"max_versions"` + + // MaxBytes caps how much one run downloads (e.g. "2GB"). Empty means no + // cap. + MaxBytes string `json:"max_bytes" yaml:"max_bytes"` + + interval time.Duration + since time.Duration + maxBytes int64 +} + +// IntervalDuration returns the parsed Interval. Validate must run first. +func (r *MirrorRefresh) IntervalDuration() time.Duration { return r.interval } + +// TopPackages returns Top, or its default. +func (r *MirrorRefresh) TopPackages() int { + if r.Top == 0 { + return defaultMirrorRefreshTop + } + return r.Top +} + +// SinceDuration returns the parsed Since, or its default. Validate must run +// first. +func (r *MirrorRefresh) SinceDuration() time.Duration { return r.since } + +// MaxVersionsPerRun returns MaxVersions; 0 means no cap. +func (r *MirrorRefresh) MaxVersionsPerRun() int { return r.MaxVersions } + +// MaxBytesPerRun returns the parsed MaxBytes; 0 means no cap. Validate must +// run first. +func (r *MirrorRefresh) MaxBytesPerRun() int64 { return r.maxBytes } + +func (r *MirrorRefresh) validate() error { + d, err := time.ParseDuration(r.Interval) + if err != nil { + return fmt.Errorf("invalid mirror.refresh.interval %q: %w", r.Interval, err) + } + if d < minMirrorScheduleInterval { + return fmt.Errorf("invalid mirror.refresh.interval %q: must be at least %s", r.Interval, minMirrorScheduleInterval) + } + r.interval = d + if r.Top < 0 { + return fmt.Errorf("invalid mirror.refresh.top %d: must not be negative", r.Top) + } + r.since = defaultMirrorRefreshSince + if r.Since != "" { + since, err := parseDayDuration(r.Since) + if err != nil { + return fmt.Errorf("invalid mirror.refresh.since %q: %w", r.Since, err) + } + if since <= 0 { + return fmt.Errorf("invalid mirror.refresh.since %q: must be positive", r.Since) + } + r.since = since + } + if r.MaxVersions < 0 { + return fmt.Errorf("invalid mirror.refresh.max_versions %d: must not be negative", r.MaxVersions) + } + r.maxBytes = 0 + if r.MaxBytes != "" { + n, err := ParseSize(r.MaxBytes) + if err != nil { + return fmt.Errorf("invalid mirror.refresh.max_bytes %q: %w", r.MaxBytes, err) + } + if n < 0 { + return fmt.Errorf("invalid mirror.refresh.max_bytes %q: must not be negative", r.MaxBytes) + } + r.maxBytes = n + } + return nil +} + +// MirrorSchedule is a set of image PURLs mirrored every Interval. +type MirrorSchedule struct { + // Images are pkg:docker or pkg:oci PURLs with a tag. + Images []string `json:"images" yaml:"images"` + + // Interval is how often the images are mirrored, at least one minute + // (e.g. "6h"). + Interval string `json:"interval" yaml:"interval"` + + // Platforms limit which platforms of an image index are mirrored, as + // os/architecture[/variant]. Empty mirrors every platform. + Platforms []string `json:"platforms" yaml:"platforms"` + + interval time.Duration +} + +// IntervalDuration returns the parsed Interval. Validate must run first. +func (s *MirrorSchedule) IntervalDuration() time.Duration { + return s.interval +} + +// Warnings returns settings that are valid but do less than they may be +// expected to. The server logs them at startup. +func (c *Config) Warnings() []string { + var warnings []string + if c.Mirror.Refresh != nil && !c.CacheMetadata { + warnings = append(warnings, "mirror.refresh without cache_metadata does not refresh Debian, Alpine or RPM packages: their indexes are found through the metadata cache") + } + return warnings +} + +// Validate checks every schedule. +func (m *MirrorConfig) Validate() error { + for i := range m.Schedules { + if err := m.Schedules[i].validate(fmt.Sprintf("mirror.schedules[%d]", i)); err != nil { + return err + } + } + if m.Refresh != nil { + return m.Refresh.validate() + } + return nil +} + +func (s *MirrorSchedule) validate(field string) error { + d, err := time.ParseDuration(s.Interval) + if err != nil { + return fmt.Errorf("invalid %s.interval %q: %w", field, s.Interval, err) + } + if d < minMirrorScheduleInterval { + return fmt.Errorf("invalid %s.interval %q: must be at least %s", field, s.Interval, minMirrorScheduleInterval) + } + s.interval = d + + if len(s.Images) == 0 { + return fmt.Errorf("%s.images must not be empty", field) + } + for _, image := range s.Images { + if err := validateScheduledImage(image); err != nil { + return fmt.Errorf("invalid %s.images entry %q: %w", field, image, err) + } + } + for _, platform := range s.Platforms { + if err := validatePlatform(platform); err != nil { + return fmt.Errorf("invalid %s.platforms entry %q: %w", field, platform, err) + } + } + return nil +} + +func validateScheduledImage(image string) error { + p, err := purl.Parse(image) + if err != nil { + return err + } + if p.Type != "docker" && p.Type != "oci" { + return fmt.Errorf("only pkg:docker and pkg:oci images can be scheduled") + } + if p.Version == "" { + return fmt.Errorf("a tag is required") + } + repositoryURL := p.Qualifiers.Map()["repository_url"] + if p.Type == "oci" && repositoryURL == "" { + return fmt.Errorf("pkg:oci needs a repository_url qualifier") + } + // Only pkg:oci mirrors the tag qualifier next to the digest. + pinned := strings.HasPrefix(p.Version, "sha256:") + if pinned && (p.Type == "docker" || p.Qualifiers.Map()["tag"] == "") { + return fmt.Errorf("a digest never moves, so there is nothing to refresh; use a tag") + } + return nil +} + +// validatePlatform matches handler.ParsePlatform, which config cannot import. +func validatePlatform(value string) error { + os, rest, _ := strings.Cut(value, "/") + architecture, variant, _ := strings.Cut(rest, "/") + if os == "" || architecture == "" || strings.Contains(variant, "/") || strings.Contains(value, ",") { + return fmt.Errorf("want os/architecture[/variant]") + } + return nil +} diff --git a/internal/config/mirror_test.go b/internal/config/mirror_test.go new file mode 100644 index 0000000..d5dff5f --- /dev/null +++ b/internal/config/mirror_test.go @@ -0,0 +1,188 @@ +package config + +import ( + "os" + "path/filepath" + "strings" + "testing" + "time" +) + +func TestMirrorConfigValidate(t *testing.T) { + const digest = "sha256:0000000000000000000000000000000000000000000000000000000000000000" + tests := []struct { + name string + schedule MirrorSchedule + wantErr bool + }{ + {name: "docker tags", schedule: MirrorSchedule{Images: []string{"pkg:docker/library/alpine@3.20", "pkg:docker/nginx@stable"}, Interval: "6h"}}, + {name: "oci with tag", schedule: MirrorSchedule{Images: []string{"pkg:oci/app@v1?repository_url=ghcr.io/acme/app"}, Interval: "1m"}}, + {name: "oci digest with tag", schedule: MirrorSchedule{Images: []string{"pkg:oci/app@" + digest + "?repository_url=ghcr.io/acme/app&tag=v1"}, Interval: "1h"}}, + {name: "platforms", schedule: MirrorSchedule{Images: []string{"pkg:docker/alpine@3"}, Interval: "1h", Platforms: []string{"linux/amd64", "linux/arm64/v8"}}}, + {name: "missing interval", schedule: MirrorSchedule{Images: []string{"pkg:docker/alpine@3"}}, wantErr: true}, + {name: "bad interval", schedule: MirrorSchedule{Images: []string{"pkg:docker/alpine@3"}, Interval: "often"}, wantErr: true}, + {name: "interval under a minute", schedule: MirrorSchedule{Images: []string{"pkg:docker/alpine@3"}, Interval: "30s"}, wantErr: true}, + {name: "no images", schedule: MirrorSchedule{Interval: "1h"}, wantErr: true}, + {name: "unparsable purl", schedule: MirrorSchedule{Images: []string{"alpine:3"}, Interval: "1h"}, wantErr: true}, + {name: "not an image", schedule: MirrorSchedule{Images: []string{"pkg:npm/lodash@4.17.21"}, Interval: "1h"}, wantErr: true}, + {name: "no tag", schedule: MirrorSchedule{Images: []string{"pkg:docker/alpine"}, Interval: "1h"}, wantErr: true}, + {name: "docker digest", schedule: MirrorSchedule{Images: []string{"pkg:docker/alpine@" + digest}, Interval: "1h"}, wantErr: true}, + {name: "docker digest with tag qualifier", schedule: MirrorSchedule{Images: []string{"pkg:docker/alpine@" + digest + "?tag=3"}, Interval: "1h"}, wantErr: true}, + {name: "oci digest only", schedule: MirrorSchedule{Images: []string{"pkg:oci/app@" + digest + "?repository_url=ghcr.io/acme/app"}, Interval: "1h"}, wantErr: true}, + {name: "oci without repository_url", schedule: MirrorSchedule{Images: []string{"pkg:oci/app@v1"}, Interval: "1h"}, wantErr: true}, + {name: "platform without architecture", schedule: MirrorSchedule{Images: []string{"pkg:docker/alpine@3"}, Interval: "1h", Platforms: []string{"linux"}}, wantErr: true}, + {name: "platform list in one entry", schedule: MirrorSchedule{Images: []string{"pkg:docker/alpine@3"}, Interval: "1h", Platforms: []string{"linux/amd64,linux/arm64"}}, wantErr: true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + m := MirrorConfig{Schedules: []MirrorSchedule{tt.schedule}} + err := m.Validate() + if (err != nil) != tt.wantErr { + t.Errorf("Validate() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } +} + +func TestMirrorScheduleIntervalDuration(t *testing.T) { + m := MirrorConfig{Schedules: []MirrorSchedule{{Images: []string{"pkg:docker/alpine@3"}, Interval: "6h"}}} + if err := m.Validate(); err != nil { + t.Fatalf("Validate: %v", err) + } + if got := m.Schedules[0].IntervalDuration(); got != 6*time.Hour { + t.Errorf("IntervalDuration() = %v, want 6h", got) + } +} + +func TestValidateRejectsMirrorSchedulesWithoutCachedArtifacts(t *testing.T) { + cfg := Default() + cfg.Mirror.Schedules = []MirrorSchedule{{Images: []string{"pkg:docker/alpine@3"}, Interval: "1h"}} + cfg.Storage.CacheArtifacts = false + if err := cfg.Validate(); err == nil { + t.Error("Validate() accepted mirror.schedules with storage.cache_artifacts: false") + } +} + +func TestLoadYAMLMirrorSchedules(t *testing.T) { + path := filepath.Join(t.TempDir(), "config.yaml") + data := ` +mirror: + schedules: + - images: [pkg:docker/library/alpine@3.20] + interval: 6h + platforms: [linux/amd64] + - images: [pkg:docker/nginx@stable] + interval: 30s +` + if err := os.WriteFile(path, []byte(data), 0o600); err != nil { + t.Fatal(err) + } + cfg, err := Load(path) + if err != nil { + t.Fatalf("Load: %v", err) + } + if len(cfg.Mirror.Schedules) != 2 || cfg.Mirror.Schedules[0].Platforms[0] != "linux/amd64" { + t.Fatalf("schedules = %+v", cfg.Mirror.Schedules) + } + if err := cfg.Validate(); err == nil { + t.Error("Validate() accepted a 30s interval in the second schedule") + } +} + +func TestMirrorRefreshValidate(t *testing.T) { + tests := []struct { + name string + refresh *MirrorRefresh + wantErr bool + }{ + {name: "defaults", refresh: &MirrorRefresh{Interval: "24h"}}, + {name: "all fields", refresh: &MirrorRefresh{Interval: "12h", Top: 20, Since: "14d", MaxVersions: 100, MaxBytes: "2GB"}}, + {name: "missing interval", refresh: &MirrorRefresh{}, wantErr: true}, + {name: "interval under a minute", refresh: &MirrorRefresh{Interval: "10s"}, wantErr: true}, + {name: "negative top", refresh: &MirrorRefresh{Interval: "1h", Top: -1}, wantErr: true}, + {name: "bad since", refresh: &MirrorRefresh{Interval: "1h", Since: "recently"}, wantErr: true}, + {name: "negative since", refresh: &MirrorRefresh{Interval: "1h", Since: "-1d"}, wantErr: true}, + {name: "negative max_versions", refresh: &MirrorRefresh{Interval: "1h", MaxVersions: -1}, wantErr: true}, + {name: "bad max_bytes", refresh: &MirrorRefresh{Interval: "1h", MaxBytes: "lots"}, wantErr: true}, + {name: "negative max_bytes", refresh: &MirrorRefresh{Interval: "1h", MaxBytes: "-1GB"}, wantErr: true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + m := MirrorConfig{Refresh: tt.refresh} + err := m.Validate() + if (err != nil) != tt.wantErr { + t.Errorf("Validate() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } +} + +func TestMirrorRefreshDefaults(t *testing.T) { + m := MirrorConfig{Refresh: &MirrorRefresh{Interval: "24h"}} + if err := m.Validate(); err != nil { + t.Fatalf("Validate: %v", err) + } + r := m.Refresh + if r.IntervalDuration() != 24*time.Hour || r.TopPackages() != 50 || r.SinceDuration() != 14*24*time.Hour || + r.MaxVersionsPerRun() != 0 || r.MaxBytesPerRun() != 0 { + t.Errorf("got interval %v top %d since %v max_versions %d max_bytes %d, want 24h 50 336h 0 0", + r.IntervalDuration(), r.TopPackages(), r.SinceDuration(), r.MaxVersionsPerRun(), r.MaxBytesPerRun()) + } +} + +func TestValidateRejectsMirrorRefreshWithoutCachedArtifacts(t *testing.T) { + cfg := Default() + cfg.Mirror.Refresh = &MirrorRefresh{Interval: "24h"} + cfg.Storage.CacheArtifacts = false + if err := cfg.Validate(); err == nil { + t.Error("Validate() accepted mirror.refresh with storage.cache_artifacts: false") + } +} + +func TestLoadYAMLMirrorRefresh(t *testing.T) { + path := filepath.Join(t.TempDir(), "config.yaml") + data := ` +mirror: + refresh: + interval: 12h + top: 10 + since: 7d + max_versions: 200 + max_bytes: 1GB +` + if err := os.WriteFile(path, []byte(data), 0o600); err != nil { + t.Fatal(err) + } + cfg, err := Load(path) + if err != nil { + t.Fatalf("Load: %v", err) + } + r := cfg.Mirror.Refresh + if r == nil { + t.Fatal("mirror.refresh not loaded") + } + if err := cfg.Validate(); err != nil { + t.Fatalf("Validate: %v", err) + } + if r.IntervalDuration() != 12*time.Hour || r.TopPackages() != 10 || r.SinceDuration() != 7*24*time.Hour || + r.MaxVersionsPerRun() != 200 || r.MaxBytesPerRun() != 1<<30 { + t.Errorf("got interval %v top %d since %v max_versions %d max_bytes %d", + r.IntervalDuration(), r.TopPackages(), r.SinceDuration(), r.MaxVersionsPerRun(), r.MaxBytesPerRun()) + } +} + +func TestWarningsMirrorRefreshWithoutCacheMetadata(t *testing.T) { + cfg := Default() + cfg.Mirror.Refresh = &MirrorRefresh{Interval: "24h"} + cfg.CacheMetadata = false + if err := cfg.Validate(); err != nil { + t.Fatalf("Validate() = %v, want mirror.refresh accepted for the other ecosystems", err) + } + if got := cfg.Warnings(); len(got) != 1 || !strings.Contains(got[0], "cache_metadata") { + t.Errorf("Warnings() = %q, want one about cache_metadata", got) + } + cfg.CacheMetadata = true + if got := cfg.Warnings(); len(got) != 0 { + t.Errorf("Warnings() with cache_metadata = %q, want none", got) + } +} diff --git a/internal/config/projects.go b/internal/config/projects.go new file mode 100644 index 0000000..f416007 --- /dev/null +++ b/internal/config/projects.go @@ -0,0 +1,53 @@ +package config + +import ( + "fmt" + "time" +) + +// ProjectsConfig configures the project inventory: repositories upload an +// SBOM to /api/projects, and the proxy shows which of them use which package +// versions. +type ProjectsConfig struct { + // Enabled registers the /api/projects endpoints and the UI pages. Off by + // default. + Enabled bool `json:"enabled" yaml:"enabled"` + + // Token is the bearer token required to upload and delete projects. + // Required when Enabled. Supports ${VAR_NAME} expansion like AuthConfig + // fields. + Token string `json:"token" yaml:"token"` + + // MaxAge removes projects that have not uploaded an SBOM for this long + // (e.g., "90d"). Empty or "0" keeps them until they are deleted. + MaxAge string `json:"max_age" yaml:"max_age"` + + maxAge time.Duration +} + +// TokenExpanded returns Token with ${VAR_NAME} references expanded. +func (p *ProjectsConfig) TokenExpanded() string { + return expandEnv(p.Token) +} + +// MaxAgeDuration returns the parsed MaxAge, 0 to keep projects. Validate +// must run first. +func (p *ProjectsConfig) MaxAgeDuration() time.Duration { + return p.maxAge +} + +// Validate checks the project inventory settings. +func (p *ProjectsConfig) Validate() error { + p.maxAge = 0 + if p.MaxAge != "" { + d, err := parseRetentionDuration("projects.max_age", p.MaxAge) + if err != nil { + return err + } + p.maxAge = d + } + if p.Enabled && p.TokenExpanded() == "" { + return fmt.Errorf("projects.token is required when projects.enabled is true") + } + return nil +} diff --git a/internal/config/projects_test.go b/internal/config/projects_test.go new file mode 100644 index 0000000..ce3c27c --- /dev/null +++ b/internal/config/projects_test.go @@ -0,0 +1,69 @@ +package config + +import ( + "testing" + "time" +) + +func TestProjectsConfigValidate(t *testing.T) { + t.Setenv("PROJECTS_TEST_TOKEN", "from-env") + + tests := []struct { + name string + projects ProjectsConfig + wantErr bool + maxAge time.Duration + }{ + {name: "disabled without token", projects: ProjectsConfig{}}, + {name: "enabled without token", projects: ProjectsConfig{Enabled: true}, wantErr: true}, + {name: "enabled with token", projects: ProjectsConfig{Enabled: true, Token: "s3cret"}}, + {name: "token from env reference", projects: ProjectsConfig{Enabled: true, Token: "${PROJECTS_TEST_TOKEN}"}}, + {name: "token env reference unset", projects: ProjectsConfig{Enabled: true, Token: "${PROJECTS_TEST_UNSET}"}, wantErr: true}, + {name: "max age in days", projects: ProjectsConfig{Enabled: true, Token: "s3cret", MaxAge: "90d"}, maxAge: 90 * 24 * time.Hour}, + {name: "max age in hours", projects: ProjectsConfig{Enabled: true, Token: "s3cret", MaxAge: "36h"}, maxAge: 36 * time.Hour}, + {name: "max age zero keeps projects", projects: ProjectsConfig{Enabled: true, Token: "s3cret", MaxAge: "0"}}, + {name: "invalid max age", projects: ProjectsConfig{Enabled: true, Token: "s3cret", MaxAge: "soon"}, wantErr: true}, + {name: "negative max age", projects: ProjectsConfig{Enabled: true, Token: "s3cret", MaxAge: "-1d"}, wantErr: true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + err := tt.projects.Validate() + if (err != nil) != tt.wantErr { + t.Fatalf("Validate() error = %v, wantErr %v", err, tt.wantErr) + } + if got := tt.projects.MaxAgeDuration(); err == nil && got != tt.maxAge { + t.Errorf("MaxAgeDuration() = %v, want %v", got, tt.maxAge) + } + }) + } +} + +func TestLoadFromEnvProjects(t *testing.T) { + cfg := Default() + t.Setenv("PROXY_PROJECTS_ENABLED", "true") + t.Setenv("PROXY_PROJECTS_TOKEN", "env-token") + t.Setenv("PROXY_PROJECTS_MAX_AGE", "30d") + + cfg.LoadFromEnv() + + if !cfg.Projects.Enabled { + t.Error("Projects.Enabled not loaded from PROXY_PROJECTS_ENABLED") + } + if cfg.Projects.TokenExpanded() != "env-token" { + t.Errorf("Projects.Token = %q, want env-token", cfg.Projects.Token) + } + if err := cfg.Validate(); err != nil { + t.Fatalf("Validate: %v", err) + } + if got := cfg.Projects.MaxAgeDuration(); got != 30*24*time.Hour { + t.Errorf("MaxAgeDuration() = %v, want 30 days", got) + } +} + +func TestValidateRejectsProjectsWithoutToken(t *testing.T) { + cfg := Default() + cfg.Projects = ProjectsConfig{Enabled: true} + if err := cfg.Validate(); err == nil { + t.Error("Validate() accepted projects.enabled without a token") + } +} diff --git a/internal/config/request_timeouts_test.go b/internal/config/request_timeouts_test.go new file mode 100644 index 0000000..01848c6 --- /dev/null +++ b/internal/config/request_timeouts_test.go @@ -0,0 +1,76 @@ +package config + +import ( + "os" + "path/filepath" + "strings" + "testing" + "time" +) + +func TestRequestTimeouts(t *testing.T) { + for _, value := range []string{"", "0", "0s", "18m", "invalid", "-1s", "999999999999999999h"} { + t.Run(value, func(t *testing.T) { + cfg := Default() + cfg.WriteTimeout, cfg.ArtifactTimeout = value, value + valid := value == "" || value == "0" || value == "0s" || value == "18m" + want := 5 * time.Minute + if value == "0" || value == "0s" { + want = 0 + } + if value == "18m" { + want = 18 * time.Minute + } + if got := cfg.ParseWriteTimeout(); got != want { + t.Errorf("write timeout = %v, want %v", got, want) + } + if got := cfg.ParseArtifactTimeout(); got != want { + t.Errorf("artifact timeout = %v, want %v", got, want) + } + err := cfg.Validate() + if (err == nil) != valid { + t.Fatalf("Validate() = %v, valid = %v", err, valid) + } + if !valid { + if !strings.Contains(err.Error(), "write_timeout") { + t.Fatalf("error does not identify write_timeout: %v", err) + } + cfg.WriteTimeout = "" + if err := cfg.Validate(); err == nil || !strings.Contains(err.Error(), "artifact_timeout") { + t.Fatalf("artifact validation = %v", err) + } + } + }) + } +} + +func TestLoadRequestTimeouts(t *testing.T) { + for _, format := range []struct{ extension, data string }{ + {"yaml", "write_timeout: 18m\nartifact_timeout: 10m\nhttp_timeout: 90s\n"}, + {"json", `{"write_timeout":"18m","artifact_timeout":"10m","http_timeout":"90s"}`}, + } { + t.Run(format.extension, func(t *testing.T) { + path := filepath.Join(t.TempDir(), "config."+format.extension) + if err := os.WriteFile(path, []byte(format.data), 0600); err != nil { + t.Fatal(err) + } + cfg, err := Load(path) + if err != nil { + t.Fatal(err) + } + if cfg.ParseWriteTimeout() != 18*time.Minute || cfg.ParseArtifactTimeout() != 10*time.Minute || cfg.ParseHTTPTimeout() != 90*time.Second { + t.Fatalf("file timeouts = %v, %v, %v", cfg.WriteTimeout, cfg.ArtifactTimeout, cfg.HTTPTimeout) + } + t.Setenv("PROXY_WRITE_TIMEOUT", "20m") + t.Setenv("PROXY_ARTIFACT_TIMEOUT", "0") + t.Setenv("PROXY_HTTP_TIMEOUT", "15s") + cfg.LoadFromEnv() + if cfg.ParseWriteTimeout() != 20*time.Minute || cfg.ParseArtifactTimeout() != 0 || cfg.ParseHTTPTimeout() != 15*time.Second { + t.Fatalf("environment timeouts = %v, %v, %v", cfg.WriteTimeout, cfg.ArtifactTimeout, cfg.HTTPTimeout) + } + if err := cfg.Validate(); err != nil { + t.Fatal(err) + } + }) + } +} diff --git a/internal/config/retention.go b/internal/config/retention.go index 3467166..9493d28 100644 --- a/internal/config/retention.go +++ b/internal/config/retention.go @@ -48,6 +48,7 @@ func (c *Config) RetentionRules(reg *retention.Registry) (retention.Rules, error rules := retention.Rules{ Ecosystems: map[string]time.Duration{}, Packages: map[string]time.Duration{}, + Sources: map[string]map[string]time.Duration{}, } var err error @@ -84,7 +85,7 @@ func (c *Config) RetentionRules(reg *retention.Registry) (retention.Rules, error for _, key := range sortedKeys(r.Packages) { field := fmt.Sprintf("storage.retention.packages[%q]", key) - canonical, err := retentionPackageKey(reg, key) + canonical, sourceOf, err := retentionPackageKey(reg, key) if err != nil { return retention.Rules{}, fmt.Errorf("invalid %s: %w", field, err) } @@ -92,6 +93,13 @@ func (c *Config) RetentionRules(reg *retention.Registry) (retention.Rules, error if err != nil { return retention.Rules{}, err } + if sourceOf != "" { + if rules.Sources[sourceOf] == nil { + rules.Sources[sourceOf] = map[string]time.Duration{} + } + rules.Sources[sourceOf][key] = d + continue + } if prev, ok := rules.Packages[canonical]; ok && prev != d { return retention.Rules{}, fmt.Errorf("invalid %s: conflicts with another key for package %s", field, canonical) } @@ -102,38 +110,41 @@ func (c *Config) RetentionRules(reg *retention.Registry) (retention.Rules, error } // retentionPackageKey returns the stored package PURL a configured package -// key stands for. -func retentionPackageKey(reg *retention.Registry, key string) (string, error) { +// key stands for, or, for a key that has to be resolved through the upstream +// first, the ecosystem key it belongs to. +func retentionPackageKey(reg *retention.Registry, key string) (canonical, sourceOf string, _ error) { // A julia PURL needs a uuid qualifier to parse at all, and the julia // handler stores none, so no key could ever match one of its packages. if strings.HasPrefix(strings.ToLower(key), "pkg:julia/") { - return "", fmt.Errorf("package rules are not supported for julia") + return "", "", fmt.Errorf("package rules are not supported for julia") } p, err := purl.Parse(key) if err != nil { - return "", fmt.Errorf("not a valid package PURL: %w", err) + return "", "", fmt.Errorf("not a valid package PURL: %w", err) } if p.Version != "" { - return "", fmt.Errorf("package PURL must not carry a version") + return "", "", fmt.Errorf("package PURL must not carry a version") } // A rule names a whole package; qualifiers and subpaths would be // dropped on the way to the stored PURL, so refuse them rather than // let "?type=pom" quietly cover every file of the package. if len(p.Qualifiers) > 0 || p.Subpath != "" { - return "", fmt.Errorf("package PURL must not carry qualifiers or a subpath") + return "", "", fmt.Errorf("package PURL must not carry qualifiers or a subpath") } - canonical, ok := reg.Canonical(p) - if ok { - return canonical, nil + if canonical, ok := reg.Canonical(p); ok { + return canonical, "", nil + } + if ecosystem, ok := reg.Source(p); ok { + return "", ecosystem, nil } ecosystem, registered := reg.KeyForDBEcosystem(purl.PURLTypeToEcosystem(p.Type)) if !registered { - return "", fmt.Errorf("retention is not supported for %s packages in this version", p.Type) + return "", "", fmt.Errorf("retention is not supported for %s packages in this version", p.Type) } if spec, _ := reg.Lookup(ecosystem); spec.CanonicalPackage == nil { - return "", fmt.Errorf("package rules are not supported for %s; use storage.retention.ecosystems.%s", ecosystem, ecosystem) + return "", "", fmt.Errorf("package rules are not supported for %s; use storage.retention.ecosystems.%s", ecosystem, ecosystem) } - return "", fmt.Errorf("does not match how %s packages are stored; see the package rule forms in docs/configuration.md", ecosystem) + return "", "", fmt.Errorf("does not match how %s packages are stored; see the package rule forms in docs/configuration.md", ecosystem) } func sortedKeys(m map[string]string) []string { diff --git a/internal/config/retention_test.go b/internal/config/retention_test.go index e416301..eb614e8 100644 --- a/internal/config/retention_test.go +++ b/internal/config/retention_test.go @@ -12,6 +12,7 @@ const retentionDay = 24 * time.Hour func retentionTestRegistry() *retention.Registry { reg := retention.NewRegistry() + reg.Register(retention.Spec{Key: "generic", CanonicalPackage: retention.DefaultCanonical("generic")}) reg.Register(retention.Spec{Key: "npm", CanonicalPackage: retention.DefaultCanonical("npm")}) reg.Register(retention.Spec{Key: "julia"}) reg.Register(retention.Spec{Key: "helm"}) @@ -34,8 +35,9 @@ func TestRetentionRulesResolves(t *testing.T) { Default: "30d", Ecosystems: map[string]string{"npm": "14d"}, Packages: map[string]string{ - "pkg:npm/lodash": "0", - "pkg:npm/@babel/core": "90d", + "pkg:npm/lodash": "0", + "pkg:npm/@babel/core": "90d", + "pkg:generic/jqlang%2Fjq": "7d", }, SweepInterval: "5m", } @@ -56,6 +58,12 @@ func TestRetentionRulesResolves(t *testing.T) { if got := rules.For("npm", "pkg:npm/%40babel/core"); got != 90*retentionDay { t.Errorf("babel rule = %v, want 90d under its canonical key", got) } + if got := rules.For("generic", "pkg:generic/jqlang%2Fjq"); got != 7*retentionDay { + t.Errorf("generic package rule = %v, want 7d", got) + } + if got := rules.For("generic", "pkg:generic/other%2Frepo"); got != 0 { + t.Errorf("unconfigured generic package rule = %v, want 0 despite the global default", got) + } if got := cfg.ParseRetentionSweepInterval(); got != 5*time.Minute { t.Errorf("ParseRetentionSweepInterval() = %v, want 5m", got) } @@ -76,7 +84,6 @@ func TestRetentionRulesErrors(t *testing.T) { {"sweep interval below a minute", func(r *RetentionConfig) { r.SweepInterval = "30s" }, "must be at least 1m0s"}, {"bad sweep interval", func(r *RetentionConfig) { r.SweepInterval = "often" }, "sweep_interval"}, {"unknown ecosystem", func(r *RetentionConfig) { r.Ecosystems = map[string]string{"nmp": "1d"} }, "unknown ecosystem"}, - {"generic is not an ecosystem key", func(r *RetentionConfig) { r.Ecosystems = map[string]string{"generic": "1d"} }, "unknown ecosystem"}, {"ecosystem not registered", func(r *RetentionConfig) { r.Ecosystems = map[string]string{"oci": "14d"} }, `storage.retention.ecosystems.oci: retention is not supported for "oci"`}, {"bad ecosystem duration", func(r *RetentionConfig) { r.Ecosystems = map[string]string{"npm": "soon"} }, "storage.retention.ecosystems.npm"}, diff --git a/internal/cooldownpolicy/policy.go b/internal/cooldownpolicy/policy.go deleted file mode 100644 index 096c4a4..0000000 --- a/internal/cooldownpolicy/policy.go +++ /dev/null @@ -1,114 +0,0 @@ -// Package cooldownpolicy applies package-pattern overrides to cooldown checks. -package cooldownpolicy - -import ( - "fmt" - "path" - "sort" - "strings" - "time" - - "github.com/git-pkgs/cooldown" -) - -// Policy applies exact PURL overrides before package-pattern overrides. -type Policy struct { - base *cooldown.Config - patterns []pattern - enabled bool -} - -type pattern struct { - glob string - duration time.Duration - config *cooldown.Config -} - -// New creates a Policy using the supplied exact and pattern overrides. -func New(base *cooldown.Config, packagePatterns map[string]string) (*Policy, error) { - if base == nil { - base = &cooldown.Config{} - } - - keys := make([]string, 0, len(packagePatterns)) - for glob := range packagePatterns { - keys = append(keys, glob) - } - sort.Strings(keys) - patterns := make([]pattern, 0, len(packagePatterns)) - seen := make(map[string]pattern) - enabled := base.Enabled() - for _, glob := range keys { - value := packagePatterns[glob] - if strings.ContainsAny(glob, "[\\") { - return nil, fmt.Errorf("invalid cooldown package pattern %q: character classes and escapes are not supported", glob) - } - canonicalGlob := strings.ReplaceAll(glob, "@", "%40") - if _, err := path.Match(canonicalGlob, ""); err != nil { - return nil, fmt.Errorf("invalid cooldown package pattern %q: %w", glob, err) - } - duration, err := cooldown.ParseDuration(value) - if err != nil { - return nil, fmt.Errorf("invalid cooldown duration for package pattern %q: %w", glob, err) - } - if previous, exists := seen[canonicalGlob]; exists { - if previous.duration != duration { - return nil, fmt.Errorf("conflicting cooldown package patterns %q and %q", previous.glob, glob) - } - continue - } - seen[canonicalGlob] = pattern{glob: glob, duration: duration} - config := &cooldown.Config{Default: value} - enabled = config.Enabled() || enabled - patterns = append(patterns, pattern{glob: canonicalGlob, duration: duration, config: config}) - } - sort.Slice(patterns, func(i, j int) bool { - left, right := literalLength(patterns[i].glob), literalLength(patterns[j].glob) - if left != right { - return left > right - } - return patterns[i].glob < patterns[j].glob - }) - - return &Policy{base: base, patterns: patterns, enabled: enabled}, nil -} - -func literalLength(glob string) int { - return len(glob) - strings.Count(glob, "*") - strings.Count(glob, "?") -} - -// For returns the duration, with exact overrides taking precedence over patterns. -func (p *Policy) For(ecosystem, packagePURL string) time.Duration { - return p.configFor(packagePURL).For(ecosystem, packagePURL) -} - -func (p *Policy) configFor(packagePURL string) *cooldown.Config { - if _, exact := p.base.Packages[packagePURL]; exact { - return p.base - } - - for _, candidate := range p.patterns { - matched, _ := path.Match(candidate.glob, packagePURL) - if !matched { - continue - } - return candidate.config - } - - return p.base -} - -// IsAllowed reports whether the package version has completed its cooldown. -func (p *Policy) IsAllowed(ecosystem, packagePURL string, publishedAt time.Time) bool { - return p.Evaluate(ecosystem, packagePURL, publishedAt, time.Now()).Allowed -} - -// Evaluate returns the cooldown decision at the supplied evaluation time. -func (p *Policy) Evaluate(ecosystem, packagePURL string, publishedAt, evaluatedAt time.Time) cooldown.Decision { - return p.configFor(packagePURL).Evaluate(ecosystem, packagePURL, publishedAt, evaluatedAt) -} - -// Enabled reports whether any configured cooldown can filter a package version. -func (p *Policy) Enabled() bool { - return p.enabled -} diff --git a/internal/cooldownpolicy/policy_test.go b/internal/cooldownpolicy/policy_test.go deleted file mode 100644 index 9e956c1..0000000 --- a/internal/cooldownpolicy/policy_test.go +++ /dev/null @@ -1,223 +0,0 @@ -package cooldownpolicy - -import ( - "strings" - "testing" - "time" - - "github.com/git-pkgs/cooldown" -) - -func TestPatternOverride(t *testing.T) { - policy, err := New(&cooldown.Config{ - Default: "7d", - Ecosystems: map[string]string{"npm": "7d"}, - }, map[string]string{ - "pkg:npm/@example/*": "0", - }) - if err != nil { - t.Fatalf("New returned error: %v", err) - } - - if !policy.IsAllowed("npm", "pkg:npm/%40example/widget", time.Now()) { - t.Fatal("matching package pattern should disable cooldown") - } - if policy.IsAllowed("npm", "pkg:npm/public-package", time.Now()) { - t.Fatal("non-matching package should use ecosystem cooldown") - } -} - -func TestExactOverrideTakesPrecedenceOverPattern(t *testing.T) { - purl := "pkg:npm/%40example/widget" - policy, err := New(&cooldown.Config{ - Default: "7d", - Packages: map[string]string{purl: "2d"}, - }, map[string]string{ - "pkg:npm/@example/*": "0", - }) - if err != nil { - t.Fatalf("New returned error: %v", err) - } - - if policy.IsAllowed("npm", purl, time.Now()) { - t.Fatal("exact package override should take precedence over pattern") - } -} - -func TestMoreSpecificPatternTakesPrecedence(t *testing.T) { - policy, err := New(&cooldown.Config{Default: "7d"}, map[string]string{ - "pkg:npm/@example/*": "0", - "pkg:npm/@example/critical": "2d", - }) - if err != nil { - t.Fatalf("New returned error: %v", err) - } - - if policy.IsAllowed("npm", "pkg:npm/%40example/critical", time.Now()) { - t.Fatal("more specific pattern should take precedence") - } -} - -func TestNewRejectsInvalidPattern(t *testing.T) { - for _, glob := range []string{"pkg:npm/[", "pkg:npm/[@a]*", "pkg:npm/[abcdef]*", `pkg:npm/\*`, `pkg:npm/\@example/*`} { - t.Run(glob, func(t *testing.T) { - if _, err := New(nil, map[string]string{glob: "0"}); err == nil || !strings.Contains(err.Error(), "character classes and escapes are not supported") { - t.Fatalf("unsupported pattern %q: error = %v", glob, err) - } - }) - } -} - -func TestQuestionMarkPattern(t *testing.T) { - policy, err := New(&cooldown.Config{Default: "7d"}, map[string]string{"pkg:npm/@example/widget-?": "0"}) - if err != nil { - t.Fatal(err) - } - for _, tc := range []struct { - purl string - want time.Duration - }{ - {"pkg:npm/%40example/widget-a", 0}, - {"pkg:npm/%40example/widget-ab", 7 * 24 * time.Hour}, - {"pkg:npm/%40example/widget-/", 7 * 24 * time.Hour}, - } { - if got := policy.For("npm", tc.purl); got != tc.want { - t.Errorf("For(%q) = %s, want %s", tc.purl, got, tc.want) - } - } -} - -func TestNormalizedPatternCollisions(t *testing.T) { - for _, duration := range []string{"0", "24h"} { - t.Run(duration, func(t *testing.T) { - for range 20 { - policy, err := New(nil, map[string]string{ - "pkg:npm/@example/*": "1d", - "pkg:npm/%40example/*": duration, - }) - if duration == "0" { - if err == nil || !strings.Contains(err.Error(), `conflicting cooldown package patterns "pkg:npm/%40example/*" and "pkg:npm/@example/*"`) { - t.Fatalf("conflict error = %v", err) - } - continue - } - if err != nil { - t.Fatal(err) - } - if got := policy.For("npm", "pkg:npm/%40example/widget"); got != 24*time.Hour { - t.Fatalf("duration = %s", got) - } - } - }) - } -} - -func TestForPrecedence(t *testing.T) { - policy, err := New(&cooldown.Config{ - Default: "1h", - Ecosystems: map[string]string{"npm": "2h"}, - Packages: map[string]string{"pkg:npm/%40example/exact": "0"}, - }, map[string]string{ - "pkg:npm/@example/*": "3h", - "pkg:npm/@example/specific*": "4h", - "pkg:npm/@example/ab*": "5h", - "pkg:npm/@example/a*c": "6h", - }) - if err != nil { - t.Fatal(err) - } - for _, tc := range []struct { - ecosystem, purl string - want time.Duration - }{ - {"npm", "pkg:npm/%40example/exact", 0}, - {"npm", "pkg:npm/%40example/widget", 3 * time.Hour}, - {"npm", "pkg:npm/%40example/specific-widget", 4 * time.Hour}, - {"npm", "pkg:npm/%40example/abc", 6 * time.Hour}, - {"npm", "pkg:npm/other", 2 * time.Hour}, - {"npm", "pkg:npm/%40example/nested/package", 2 * time.Hour}, - {"cargo", "pkg:cargo/serde", time.Hour}, - } { - t.Run(tc.purl, func(t *testing.T) { - if got := policy.For(tc.ecosystem, tc.purl); got != tc.want { - t.Errorf("For = %s, want %s", got, tc.want) - } - }) - } -} - -func TestPatternOnlyPolicy(t *testing.T) { - policy, err := New(nil, map[string]string{"pkg:nuget/example.*": "24h"}) - if err != nil { - t.Fatal(err) - } - if !policy.Enabled() { - t.Fatal("pattern-only policy should be enabled") - } - for _, tc := range []struct { - published time.Time - allowed bool - }{ - {time.Now().Add(-time.Hour), false}, - {time.Now().Add(-48 * time.Hour), true}, - {time.Time{}, true}, - } { - if got := policy.IsAllowed("nuget", "pkg:nuget/example.widget", tc.published); got != tc.allowed { - t.Errorf("published=%s: allowed=%t, want %t", tc.published, got, tc.allowed) - } - } - if !policy.IsAllowed("nuget", "pkg:nuget/other", time.Now()) { - t.Error("unmatched package should have no cooldown") - } -} - -func TestDisabledPolicy(t *testing.T) { - for _, patterns := range []map[string]string{nil, {"pkg:npm/@example/*": "0"}} { - policy, err := New(nil, patterns) - if err != nil { - t.Fatal(err) - } - if policy.Enabled() { - t.Error("zero cooldown should be disabled") - } - } -} - -func TestNewRejectsInvalidDuration(t *testing.T) { - if _, err := New(nil, map[string]string{"pkg:npm/*": "invalid"}); err == nil { - t.Fatal("invalid duration accepted") - } -} - -func TestEvaluate(t *testing.T) { - policy, err := New(&cooldown.Config{ - Default: "48h", - Ecosystems: map[string]string{"npm": "72h"}, - Packages: map[string]string{"pkg:npm/%40example/exact": "0"}, - }, map[string]string{"pkg:npm/@example/*": "7d"}) - if err != nil { - t.Fatal(err) - } - published := time.Date(2026, time.October, 1, 0, 0, 0, 0, time.UTC) - eligible := published.Add(7 * 24 * time.Hour) - for _, tc := range []struct { - name, ecosystem, purl string - published, at time.Time - want cooldown.Decision - }{ - {"waiting", "npm", "pkg:npm/%40example/widget", published, eligible.Add(-time.Nanosecond), cooldown.Decision{Cooldown: 7 * 24 * time.Hour, AvailableAt: eligible, Reason: cooldown.ReasonWaiting}}, - {"boundary", "npm", "pkg:npm/%40example/widget", published, eligible, cooldown.Decision{Allowed: true, Cooldown: 7 * 24 * time.Hour, AvailableAt: eligible, Reason: cooldown.ReasonElapsed}}, - {"elapsed", "npm", "pkg:npm/%40example/widget", published, eligible.Add(time.Hour), cooldown.Decision{Allowed: true, Cooldown: 7 * 24 * time.Hour, AvailableAt: eligible, Reason: cooldown.ReasonElapsed}}, - {"unknown publication", "npm", "pkg:npm/%40example/widget", time.Time{}, eligible, cooldown.Decision{Allowed: true, Cooldown: 7 * 24 * time.Hour, Reason: cooldown.ReasonUnknownPublicationTime}}, - {"exact exemption", "npm", "pkg:npm/%40example/exact", published, published, cooldown.Decision{Allowed: true, AvailableAt: published, Reason: cooldown.ReasonDisabled}}, - {"exemption without publication", "npm", "pkg:npm/%40example/exact", time.Time{}, eligible, cooldown.Decision{Allowed: true, Reason: cooldown.ReasonUnknownPublicationTime}}, - {"ecosystem fallback", "npm", "pkg:npm/other", published, published, cooldown.Decision{Cooldown: 72 * time.Hour, AvailableAt: published.Add(72 * time.Hour), Reason: cooldown.ReasonWaiting}}, - {"global fallback", "cargo", "pkg:cargo/serde", published, published, cooldown.Decision{Cooldown: 48 * time.Hour, AvailableAt: published.Add(48 * time.Hour), Reason: cooldown.ReasonWaiting}}, - } { - t.Run(tc.name, func(t *testing.T) { - if got := policy.Evaluate(tc.ecosystem, tc.purl, tc.published, tc.at); got != tc.want { - t.Errorf("Evaluate = %+v, want %+v", got, tc.want) - } - }) - } -} diff --git a/internal/database/analytics_test.go b/internal/database/analytics_test.go index 269b9d2..5084acd 100644 --- a/internal/database/analytics_test.go +++ b/internal/database/analytics_test.go @@ -373,3 +373,92 @@ func TestMergeAliasedEcosystemsBreaksSizeTiesByName(t *testing.T) { t.Errorf("input order changed the surviving spelling: %q vs %q", first, second) } } + +// Cooldown stores publish times of versions nobody downloaded, without a +// package row. They count under the ecosystem of their package PURL, not as +// unattributed. +func TestGetEcosystemStatsAttributesPublishTimesByPURL(t *testing.T) { + runWithBothDatabases(t, func(t *testing.T, db *DB) { + seedArtifact(t, db, "npm", "lodash", "4.17.21", 1000, 2) + published := time.Now().Add(-time.Hour) + for _, v := range []struct{ version, pkg string }{ + {"pkg:npm/react@19.0.0", "pkg:npm/react"}, + {"pkg:golang/github.com/swaggo/swag@v1.16.3", "pkg:golang/github.com/swaggo/swag"}, + {"pkg:golang/github.com/swaggo/swag@v1.16.4", "pkg:golang/github.com/swaggo/swag"}, + {"pkg:composer/vendor/pkg@1.0.0", "pkg:composer/vendor/pkg"}, + {"not-a-purl@1", "not-a-purl"}, + } { + if err := db.SetVersionPublishedAt(v.version, v.pkg, published); err != nil { + t.Fatal(err) + } + } + + stats, err := db.GetEcosystemStats() + if err != nil { + t.Fatalf("GetEcosystemStats: %v", err) + } + versions := map[string]int64{} + for _, e := range stats { + versions[e.Ecosystem] = e.Versions + } + want := map[string]int64{"npm": 2, "golang": 2, "composer": 1, unattributedEcosystem: 1} + for ecosystem, n := range want { + if versions[ecosystem] != n { + t.Errorf("versions of %s = %d, want %d (all: %v)", ecosystem, versions[ecosystem], n, versions) + } + } + if len(versions) != len(want) { + t.Errorf("ecosystems = %v, want %v", versions, want) + } + }) +} + +// TestGetEcosystemStatsVersionsReconcile checks that the versions counted +// per ecosystem add up to the cache stats' total, with publish times stored +// under namespaced PURLs, an alias of a package row's ecosystem, and a PURL +// that can't be parsed. +func TestGetEcosystemStatsVersionsReconcile(t *testing.T) { + runWithBothDatabases(t, func(t *testing.T, db *DB) { + seedArtifact(t, db, "npm", "lodash", "4.17.21", 1000, 2) + seedArtifact(t, db, "go", "github.com/pkg/errors", "v0.9.1", 500, 1) + published := time.Now().Add(-time.Hour) + for _, v := range []struct{ version, pkg string }{ + {"pkg:npm/%40babel/core@7.25.2", "pkg:npm/%40babel/core"}, + {"pkg:maven/org.apache.commons/commons-lang3@3.14.0", "pkg:maven/org.apache.commons/commons-lang3"}, + {"pkg:pypi/requests@2.32.3", "pkg:pypi/requests"}, + {"pkg:golang/github.com/swaggo/swag@v1.16.4", "pkg:golang/github.com/swaggo/swag"}, + {"~odd@1", "~odd"}, + } { + if err := db.SetVersionPublishedAt(v.version, v.pkg, published); err != nil { + t.Fatal(err) + } + } + + stats, err := db.GetEcosystemStats() + if err != nil { + t.Fatalf("GetEcosystemStats: %v", err) + } + versions := map[string]int64{} + var sum int64 + for _, e := range stats { + versions[e.Ecosystem] += e.Versions + sum += e.Versions + } + want := map[string]int64{"npm": 2, "go": 2, "maven": 1, "pypi": 1, unattributedEcosystem: 1} + if len(versions) != len(want) { + t.Errorf("ecosystems = %v, want %v", versions, want) + } + for ecosystem, n := range want { + if versions[ecosystem] != n { + t.Errorf("versions of %s = %d, want %d (all: %v)", ecosystem, versions[ecosystem], n, versions) + } + } + cache, err := db.GetCacheStats() + if err != nil { + t.Fatal(err) + } + if sum != cache.TotalVersions { + t.Errorf("versions per ecosystem add up to %d, cache stats count %d", sum, cache.TotalVersions) + } + }) +} diff --git a/internal/database/cache_eviction.go b/internal/database/cache_eviction.go new file mode 100644 index 0000000..33bcdae --- /dev/null +++ b/internal/database/cache_eviction.go @@ -0,0 +1,247 @@ +package database + +import ( + "database/sql" + "slices" + "time" +) + +// Kinds of CacheEntry. +const ( + CacheEntryArtifact = "artifact" + CacheEntryMetadata = "metadata" +) + +// CacheEntry is a cached object size eviction can remove: an artifact fetched +// from upstream or a metadata document. For an artifact Key is its version +// PURL and Name its filename; for metadata Key is the ecosystem and Name the +// cache key. FetchedAt is only read for artifacts, UpdatedAt for metadata +// not backfilled yet. +type CacheEntry struct { + Kind string `db:"kind"` + Key string `db:"cache_key"` + Name string `db:"name"` + StoragePath sql.NullString `db:"storage_path"` + Size sql.NullInt64 `db:"size"` + LastAccessedAt sql.NullTime `db:"last_accessed_at"` + FetchedAt sql.NullTime `db:"fetched_at"` + UpdatedAt sql.NullTime `db:"updated_at"` +} + +// GetEvictableCacheSize returns the bytes max_size limits: cached upstream +// artifacts and cached metadata documents. +func (db *DB) GetEvictableCacheSize() (int64, error) { + var total int64 + err := db.Get(&total, ` + SELECT (SELECT COALESCE(SUM(size), 0) FROM artifacts WHERE storage_path IS NOT NULL AND source <> 'local') + + (SELECT COALESCE(SUM(size), 0) FROM metadata_cache)`) + return total, err +} + +// GetLeastRecentlyUsedCacheEntries returns up to limit artifacts and metadata +// documents, least recently used first. An artifact counts as used when it +// was fetched until it is first served, so a fresh download does not go +// before every metadata document. Each kind is read in order on its own and +// the two are merged here, which keeps the queries simple for both dialects. +func (db *DB) GetLeastRecentlyUsedCacheEntries(limit int) ([]CacheEntry, error) { + var artifacts, metadata []CacheEntry + if err := db.Select(&artifacts, db.Rebind(` + SELECT 'artifact' AS kind, version_purl AS cache_key, filename AS name, + storage_path, size, last_accessed_at, fetched_at + FROM artifacts + WHERE storage_path IS NOT NULL AND source <> 'local' + ORDER BY COALESCE(last_accessed_at, fetched_at) ASC NULLS FIRST + LIMIT ? + `), limit); err != nil { + return nil, err + } + if err := db.Select(&metadata, db.Rebind(` + SELECT 'metadata' AS kind, ecosystem AS cache_key, name, + storage_path, size, last_accessed_at, updated_at + FROM metadata_cache + ORDER BY COALESCE(last_accessed_at, updated_at) ASC NULLS FIRST + LIMIT ? + `), limit); err != nil { + return nil, err + } + // Rows not backfilled yet fall back to updated_at, which Postgres keeps + // in local time, so the order is fixed up once it is read as UTC. + for i := range metadata { + metadata[i].UpdatedAt = db.writtenAtUTC(metadata[i].UpdatedAt) + } + slices.SortStableFunc(metadata, func(a, b CacheEntry) int { + switch { + case a.usedAfter(b): + return 1 + case b.usedAfter(a): + return -1 + } + return 0 + }) + + entries := make([]CacheEntry, 0, min(limit, len(artifacts)+len(metadata))) + for len(entries) < limit && (len(artifacts) > 0 || len(metadata) > 0) { + if len(metadata) == 0 || (len(artifacts) > 0 && !artifacts[0].usedAfter(metadata[0])) { + entries, artifacts = append(entries, artifacts[0]), artifacts[1:] + } else { + entries, metadata = append(entries, metadata[0]), metadata[1:] + } + } + return entries, nil +} + +// lastUsed is when e was last served, or for an artifact not served since, +// when it was fetched. It is invalid when neither is known. +func (e CacheEntry) lastUsed() sql.NullTime { + if e.LastAccessedAt.Valid { + return e.LastAccessedAt + } + if e.FetchedAt.Valid { + return e.FetchedAt + } + return e.UpdatedAt +} + +// usedAfter reports whether e was used later than other. Entries with no +// time known count as the oldest, as NULLS FIRST orders them. +func (e CacheEntry) usedAfter(other CacheEntry) bool { + a, b := e.lastUsed(), other.lastUsed() + if !a.Valid { + return false + } + return !b.Valid || a.Time.After(b.Time) +} + +// EvictMetadataCache deletes a metadata cache row if it still points at +// storagePath and has not been used since lastAccessed, queueing the path in +// the same transaction so a crash before the blob is deleted cannot orphan it. +func (db *DB) EvictMetadataCache(ecosystem, name, storagePath string, lastAccessed sql.NullTime) (bool, error) { + query := ` + DELETE FROM metadata_cache + WHERE ecosystem = ? AND name = ? AND storage_path = ? AND last_accessed_at IS NULL` + args := []any{ecosystem, name, storagePath} + if lastAccessed.Valid { + query = ` + DELETE FROM metadata_cache + WHERE ecosystem = ? AND name = ? AND storage_path = ? + AND (last_accessed_at IS NULL OR last_accessed_at <= ?)` + args = append(args, lastAccessed.Time) + } + tx, err := db.Beginx() + if err != nil { + return false, err + } + defer func() { _ = tx.Rollback() }() + res, err := tx.Exec(db.Rebind(query), args...) + if err != nil { + return false, err + } + if n, err := res.RowsAffected(); err != nil || n == 0 { + return false, err + } + if _, err := tx.Exec(db.Rebind(queuePendingDeleteQuery), storagePath, time.Now().UTC()); err != nil { + return false, err + } + return true, tx.Commit() +} + +// DiscardMetadataCache deletes a metadata cache row whose stored document +// failed its integrity check, if it still points at storagePath with digest, +// and queues the path for deletion in the same transaction. A row a newer +// fetch has rewritten is left alone. +func (db *DB) DiscardMetadataCache(ecosystem, name, storagePath, digest string) error { + tx, err := db.Beginx() + if err != nil { + return err + } + defer func() { _ = tx.Rollback() }() + res, err := tx.Exec(db.Rebind(` + DELETE FROM metadata_cache + WHERE ecosystem = ? AND name = ? AND storage_path = ? AND content_digest = ?`), + ecosystem, name, storagePath, digest) + if err != nil { + return err + } + if n, err := res.RowsAffected(); err != nil || n == 0 { + return err + } + if _, err := tx.Exec(db.Rebind(queuePendingDeleteQuery), storagePath, time.Now().UTC()); err != nil { + return err + } + return tx.Commit() +} + +// RecordMetadataHit marks a cached metadata document as served now. Like +// RecordArtifactHit it is buffered when BatchHits is on. +func (db *DB) RecordMetadataHit(ecosystem, name string) error { + now := time.Now() + if db.hits != nil { + db.hits.addMetadata(metadataHitKey{ecosystem, name}, now) + return nil + } + _, err := db.Exec(db.Rebind(recordMetadataHitQuery), now.UTC(), now.UTC(), ecosystem, name) + return err +} + +// recordMetadataHitQuery takes the access time twice, then the ecosystem and +// key. The time only moves forward, as for artifacts. +const recordMetadataHitQuery = ` + UPDATE metadata_cache + SET last_accessed_at = CASE WHEN last_accessed_at IS NULL OR last_accessed_at < ? THEN ? ELSE last_accessed_at END + WHERE ecosystem = ? AND name = ?` + +// writtenAtUTC returns a metadata_cache updated_at or created_at as the +// instant it was written. Both were written in local time, and a Postgres +// TIMESTAMP keeps only the wall clock, which lib/pq reads back as UTC. +func (db *DB) writtenAtUTC(t sql.NullTime) sql.NullTime { + if t.Valid && db.dialect == DialectPostgres { + w := t.Time + t.Time = time.Date(w.Year(), w.Month(), w.Day(), w.Hour(), w.Minute(), w.Second(), w.Nanosecond(), time.Local) + } + if t.Valid { + t.Time = t.Time.UTC() + } + return t +} + +// BackfillMetadataLastAccessed sets last_accessed_at from the write time on +// up to limit rows that have none, in one transaction, and reports how many it +// set. Rows served in the meantime keep the time of that hit. +func (db *DB) BackfillMetadataLastAccessed(limit int) (int, error) { + var rows []struct { + ID int64 `db:"id"` + UpdatedAt sql.NullTime `db:"updated_at"` + CreatedAt sql.NullTime `db:"created_at"` + } + query := db.Rebind(`SELECT id, updated_at, created_at FROM metadata_cache WHERE last_accessed_at IS NULL LIMIT ?`) + if err := db.Select(&rows, query, limit); err != nil { + return 0, err + } + if len(rows) == 0 { + return 0, nil + } + tx, err := db.Beginx() + if err != nil { + return 0, err + } + defer func() { _ = tx.Rollback() }() + stmt, err := tx.Preparex(db.Rebind(`UPDATE metadata_cache SET last_accessed_at = ? WHERE id = ? AND last_accessed_at IS NULL`)) + if err != nil { + return 0, err + } + defer func() { _ = stmt.Close() }() + for _, r := range rows { + at := db.writtenAtUTC(r.UpdatedAt) + if !at.Valid { + at = db.writtenAtUTC(r.CreatedAt) + } + if !at.Valid { + // Nothing to go by; counting it as used now at least ends the loop. + at = sql.NullTime{Time: time.Now().UTC(), Valid: true} + } + if _, err := stmt.Exec(at.Time, r.ID); err != nil { + return 0, err + } + } + return len(rows), tx.Commit() +} diff --git a/internal/database/cache_eviction_test.go b/internal/database/cache_eviction_test.go new file mode 100644 index 0000000..4040316 --- /dev/null +++ b/internal/database/cache_eviction_test.go @@ -0,0 +1,325 @@ +package database + +import ( + "database/sql" + "strings" + "testing" + "time" +) + +func upsertTestMetadata(t *testing.T, db *DB, name string, size int64) { + t.Helper() + if err := db.UpsertMetadataCache(&MetadataCacheEntry{ + Ecosystem: testEcosystemNPM, + Name: name, + StoragePath: "_metadata/npm/" + name + "/metadata", + Size: sql.NullInt64{Int64: size, Valid: true}, + FetchedAt: sql.NullTime{Time: time.Now(), Valid: true}, + }); err != nil { + t.Fatalf("UpsertMetadataCache: %v", err) + } +} + +func setTestMetadataAccess(t *testing.T, db *DB, name string, at time.Time) { + t.Helper() + query := db.Rebind(`UPDATE metadata_cache SET last_accessed_at = ? WHERE ecosystem = ? AND name = ?`) + if _, err := db.Exec(query, at.UTC(), testEcosystemNPM, name); err != nil { + t.Fatalf("setting last access: %v", err) + } +} + +func TestUpsertMetadataCacheMarksAccess(t *testing.T) { + runWithBothDatabases(t, func(t *testing.T, db *DB) { + before := time.Now().Add(-time.Second) + upsertTestMetadata(t, db, "lodash", 10) + + got, err := db.GetMetadataCache(testEcosystemNPM, "lodash") + if err != nil || got == nil { + t.Fatalf("GetMetadataCache: %v, %v", got, err) + } + if !got.LastAccessedAt.Valid || got.LastAccessedAt.Time.Before(before) { + t.Errorf("last_accessed_at = %v, want the time of the write", got.LastAccessedAt) + } + }) +} + +func TestGetEvictableCacheSizeCountsMetadata(t *testing.T) { + runWithBothDatabases(t, func(t *testing.T, db *DB) { + upsertTestMetadata(t, db, "a", 300) + upsertTestMetadata(t, db, "b", 200) + + total, err := db.GetEvictableCacheSize() + if err != nil { + t.Fatalf("GetEvictableCacheSize: %v", err) + } + if total != 500 { + t.Errorf("evictable size = %d, want 500", total) + } + // The size shown in stats stays the artifacts' total. + artifacts, err := db.GetTotalCacheSize() + if err != nil || artifacts != 0 { + t.Errorf("GetTotalCacheSize = %d, %v, want 0", artifacts, err) + } + }) +} + +func TestGetLeastRecentlyUsedCacheEntriesOrdersMetadataAndArtifacts(t *testing.T) { + runWithBothDatabases(t, func(t *testing.T, db *DB) { + now := time.Now() + upsertTestMetadata(t, db, "old", 1) + setTestMetadataAccess(t, db, "old", now.Add(-3*time.Hour)) + upsertTestMetadata(t, db, "new", 1) + setTestMetadataAccess(t, db, "new", now) + if err := db.UpsertArtifact(&Artifact{ + VersionPURL: "pkg:npm/mid@1.0.0", + Filename: "mid-1.0.0.tgz", + UpstreamURL: "https://example.test/mid-1.0.0.tgz", + StoragePath: sql.NullString{String: "npm/mid/1.0.0/mid-1.0.0.tgz", Valid: true}, + Size: sql.NullInt64{Int64: 1, Valid: true}, + LastAccessedAt: sql.NullTime{Time: now.Add(-time.Hour), Valid: true}, + }); err != nil { + t.Fatalf("UpsertArtifact: %v", err) + } + + entries, err := db.GetLeastRecentlyUsedCacheEntries(10) + if err != nil { + t.Fatalf("GetLeastRecentlyUsedCacheEntries: %v", err) + } + var got []string + for _, e := range entries { + got = append(got, e.Kind+":"+e.Name) + } + want := []string{"metadata:old", "artifact:mid-1.0.0.tgz", "metadata:new"} + if len(got) != len(want) { + t.Fatalf("entries = %v, want %v", got, want) + } + for i := range want { + if got[i] != want[i] { + t.Fatalf("entries = %v, want %v", got, want) + } + } + }) +} + +func TestEvictMetadataCacheKeepsRowUsedSinceRead(t *testing.T) { + runWithBothDatabases(t, func(t *testing.T, db *DB) { + upsertTestMetadata(t, db, "lodash", 10) + setTestMetadataAccess(t, db, "lodash", time.Now().Add(-time.Hour)) + read, _ := db.GetMetadataCache(testEcosystemNPM, "lodash") + + if err := db.RecordMetadataHit(testEcosystemNPM, "lodash"); err != nil { + t.Fatalf("RecordMetadataHit: %v", err) + } + evicted, err := db.EvictMetadataCache(testEcosystemNPM, "lodash", read.StoragePath, read.LastAccessedAt) + if err != nil || evicted { + t.Fatalf("EvictMetadataCache = %v, %v, want the row kept", evicted, err) + } + + current, _ := db.GetMetadataCache(testEcosystemNPM, "lodash") + evicted, err = db.EvictMetadataCache(testEcosystemNPM, "lodash", current.StoragePath, current.LastAccessedAt) + if err != nil || !evicted { + t.Fatalf("EvictMetadataCache = %v, %v, want the row evicted", evicted, err) + } + if gone, _ := db.GetMetadataCache(testEcosystemNPM, "lodash"); gone != nil { + t.Error("row still present after eviction") + } + }) +} + +func TestRecordMetadataHitBatched(t *testing.T) { + runWithBothDatabases(t, func(t *testing.T, db *DB) { + upsertTestMetadata(t, db, "lodash", 10) + old := time.Now().Add(-time.Hour) + setTestMetadataAccess(t, db, "lodash", old) + db.BatchHits(time.Hour, nil) + + if err := db.RecordMetadataHit(testEcosystemNPM, "lodash"); err != nil { + t.Fatalf("RecordMetadataHit: %v", err) + } + if got, _ := db.GetMetadataCache(testEcosystemNPM, "lodash"); got.LastAccessedAt.Time.After(old.Add(time.Minute)) { + t.Error("batched hit was written before the flush") + } + if err := db.flushHits(); err != nil { + t.Fatalf("flushHits: %v", err) + } + if got, _ := db.GetMetadataCache(testEcosystemNPM, "lodash"); !got.LastAccessedAt.Time.After(old.Add(time.Minute)) { + t.Errorf("last_accessed_at = %v after flush, want the hit's time", got.LastAccessedAt) + } + }) +} + +func TestPendingDeleteSkipsPathMetadataPointsAt(t *testing.T) { + runWithBothDatabases(t, func(t *testing.T, db *DB) { + upsertTestMetadata(t, db, "lodash", 10) + path := "_metadata/npm/lodash/metadata" + if err := db.QueuePendingDelete(path); err != nil { + t.Fatalf("QueuePendingDelete: %v", err) + } + + due, err := db.GetDuePendingDeletes(time.Now().Add(time.Hour), 10) + if err != nil { + t.Fatalf("GetDuePendingDeletes: %v", err) + } + if len(due) != 0 { + t.Errorf("due = %v, want the path a metadata row uses skipped", due) + } + }) +} + +// TestGetLeastRecentlyUsedCacheEntriesCountsFetchAsUse checks that an +// artifact not served since its download ranks by when it was fetched, not +// ahead of every metadata document. +func TestGetLeastRecentlyUsedCacheEntriesCountsFetchAsUse(t *testing.T) { + runWithBothDatabases(t, func(t *testing.T, db *DB) { + now := time.Now() + upsertTestMetadata(t, db, "old", 1) + setTestMetadataAccess(t, db, "old", now.Add(-time.Hour)) + if err := db.UpsertArtifact(&Artifact{ + VersionPURL: "pkg:npm/fresh@1.0.0", + Filename: "fresh-1.0.0.tgz", + UpstreamURL: "https://example.test/fresh-1.0.0.tgz", + StoragePath: sql.NullString{String: "npm/fresh/1.0.0/fresh-1.0.0.tgz", Valid: true}, + Size: sql.NullInt64{Int64: 1, Valid: true}, + FetchedAt: sql.NullTime{Time: now, Valid: true}, + }); err != nil { + t.Fatalf("UpsertArtifact: %v", err) + } + + entries, err := db.GetLeastRecentlyUsedCacheEntries(1) + if err != nil || len(entries) != 1 { + t.Fatalf("GetLeastRecentlyUsedCacheEntries: %v, %v", entries, err) + } + if entries[0].Kind != CacheEntryMetadata { + t.Errorf("least recently used = %+v, want the metadata used an hour ago", entries[0]) + } + }) +} + +// TestLeastRecentlyUsedQueriesUseIndexes checks on SQLite that eviction reads +// both tables off an index rather than sorting them whole. +func TestLeastRecentlyUsedQueriesUseIndexes(t *testing.T) { + db := setupMetadataCacheDB(t) + for _, q := range []string{ + `SELECT version_purl FROM artifacts WHERE storage_path IS NOT NULL AND source <> 'local' + ORDER BY COALESCE(last_accessed_at, fetched_at) ASC NULLS FIRST LIMIT 50`, + `SELECT name FROM metadata_cache ORDER BY COALESCE(last_accessed_at, updated_at) ASC NULLS FIRST LIMIT 50`, + } { + rows, err := db.Query("EXPLAIN QUERY PLAN " + q) + if err != nil { + t.Fatalf("explain: %v", err) + } + var plan []string + for rows.Next() { + var id, parent, unused int + var detail string + if err := rows.Scan(&id, &parent, &unused, &detail); err != nil { + t.Fatalf("scan: %v", err) + } + plan = append(plan, detail) + } + _ = rows.Close() + for _, step := range plan { + if strings.Contains(step, "TEMP B-TREE") { + t.Errorf("query sorts instead of using an index: %v\n%s", plan, q) + } + } + } +} + +// insertLegacyMetadata adds a row as the proxy wrote it before +// last_accessed_at existed: write times in local time, no access time. +func insertLegacyMetadata(t *testing.T, db *DB, name string, written time.Time) { + t.Helper() + if _, err := db.Exec(db.Rebind(` + INSERT INTO metadata_cache (ecosystem, name, storage_path, size, created_at, updated_at) + VALUES (?, ?, ?, ?, ?, ?)`), testEcosystemNPM, name, "_metadata/npm/"+name+"/metadata", 1, written, written); err != nil { + t.Fatalf("inserting legacy row: %v", err) + } +} + +func TestMetadataLastAccessedMigrationLeavesBackfillToBackground(t *testing.T) { + runWithBothDatabases(t, func(t *testing.T, db *DB) { + for _, q := range []string{ + "DROP INDEX idx_metadata_last_used", + "DROP INDEX idx_metadata_storage_path", + "DROP INDEX idx_artifacts_last_used", + "ALTER TABLE metadata_cache DROP COLUMN last_accessed_at", + "DELETE FROM migrations WHERE name = '014_add_metadata_last_accessed'", + } { + if _, err := db.Exec(q); err != nil { + t.Fatalf("%s: %v", q, err) + } + } + written := time.Date(2026, 1, 2, 3, 4, 5, 0, time.Local) + insertLegacyMetadata(t, db, "legacy", written) + + if err := db.MigrateSchema(); err != nil { + t.Fatalf("MigrateSchema: %v", err) + } + if got, _ := db.GetMetadataCache(testEcosystemNPM, "legacy"); got == nil || got.LastAccessedAt.Valid { + t.Fatalf("row after migration = %+v, want it kept with no access time", got) + } + if n, err := db.BackfillMetadataLastAccessed(10); err != nil || n != 1 { + t.Fatalf("BackfillMetadataLastAccessed = %d, %v, want 1", n, err) + } + got, _ := db.GetMetadataCache(testEcosystemNPM, "legacy") + if got == nil || !got.LastAccessedAt.Valid || !got.LastAccessedAt.Time.Equal(written) { + t.Errorf("backfilled last_accessed_at = %+v, want %v", got, written.UTC()) + } + }) +} + +// TestBackfillMetadataLastAccessedResumes runs the backfill in batches, as a +// restart after an interruption would, and leaves rows served meanwhile alone. +func TestBackfillMetadataLastAccessedResumes(t *testing.T) { + runWithBothDatabases(t, func(t *testing.T, db *DB) { + written := time.Now().Add(-48 * time.Hour).Truncate(time.Second) + for _, name := range []string{"a", "b", "c"} { + insertLegacyMetadata(t, db, name, written) + } + if n, err := db.BackfillMetadataLastAccessed(2); err != nil || n != 2 { + t.Fatalf("first batch = %d, %v, want 2", n, err) + } + var left string + if err := db.Get(&left, `SELECT name FROM metadata_cache WHERE last_accessed_at IS NULL`); err != nil { + t.Fatalf("finding the row left: %v", err) + } + if err := db.RecordMetadataHit(testEcosystemNPM, left); err != nil { + t.Fatalf("RecordMetadataHit: %v", err) + } + if n, err := db.BackfillMetadataLastAccessed(2); err != nil || n != 0 { + t.Fatalf("second batch = %d, %v, want 0", n, err) + } + got, _ := db.GetMetadataCache(testEcosystemNPM, left) + if !got.LastAccessedAt.Time.After(written.Add(time.Hour)) { + t.Errorf("served row last_accessed_at = %v, want the hit kept", got.LastAccessedAt) + } + }) +} + +// TestLeastRecentlyUsedOrdersUnbackfilledMetadataByWriteTime checks that rows +// still waiting for the backfill are not all evicted first. +func TestLeastRecentlyUsedOrdersUnbackfilledMetadataByWriteTime(t *testing.T) { + runWithBothDatabases(t, func(t *testing.T, db *DB) { + now := time.Now() + insertLegacyMetadata(t, db, "recent", now) + if err := db.UpsertArtifact(&Artifact{ + VersionPURL: "pkg:npm/old@1.0.0", + Filename: "old-1.0.0.tgz", + UpstreamURL: "https://example.test/old-1.0.0.tgz", + StoragePath: sql.NullString{String: "npm/old/1.0.0/old-1.0.0.tgz", Valid: true}, + Size: sql.NullInt64{Int64: 1, Valid: true}, + LastAccessedAt: sql.NullTime{Time: now.Add(-time.Hour), Valid: true}, + }); err != nil { + t.Fatalf("UpsertArtifact: %v", err) + } + + entries, err := db.GetLeastRecentlyUsedCacheEntries(1) + if err != nil || len(entries) != 1 { + t.Fatalf("GetLeastRecentlyUsedCacheEntries: %v, %v", entries, err) + } + if entries[0].Kind != CacheEntryArtifact { + t.Errorf("least recently used = %+v, want the artifact used an hour ago", entries[0]) + } + }) +} diff --git a/internal/database/cached_names.go b/internal/database/cached_names.go new file mode 100644 index 0000000..0b9563b --- /dev/null +++ b/internal/database/cached_names.go @@ -0,0 +1,21 @@ +package database + +// CachedArtifactNames returns the names of the packages of ecosystem that +// have a cached artifact called filename, for protocols whose file names +// identify an artifact without its package name. +func (db *DB) CachedArtifactNames(ecosystem, filename string) ([]string, error) { + var names []string + query := db.Rebind(` + SELECT DISTINCT packages.name + FROM artifacts + JOIN versions ON versions.purl = artifacts.version_purl + JOIN packages ON packages.purl = versions.package_purl + WHERE packages.ecosystem = ? AND artifacts.filename = ? + AND artifacts.storage_path IS NOT NULL AND artifacts.fetched_at IS NOT NULL + ORDER BY packages.name + `) + if err := db.Select(&names, query, ecosystem, filename); err != nil { + return nil, err + } + return names, nil +} diff --git a/internal/database/database.go b/internal/database/database.go index f438f67..ac71ac1 100644 --- a/internal/database/database.go +++ b/internal/database/database.go @@ -1,9 +1,13 @@ package database import ( + "context" + "database/sql" "fmt" "os" "path/filepath" + "runtime" + "strings" "time" "github.com/jmoiron/sqlx" @@ -32,8 +36,33 @@ const ( DialectPostgres Dialect = "postgres" ) +// SQLite DSN parameters. Every connection a pool opens applies them, so a +// connection database/sql reopens gets them too. The reader pool sets +// query_only, which makes a write sent to it fail instead of being run. +const ( + sqliteWriterParams = "?_busy_timeout=5000&_journal_mode=WAL&_synchronous=NORMAL" + sqliteReaderParams = "?_busy_timeout=5000&_query_only=1" +) + +// Size bounds of the SQLite reader pool. At least two, so a slow stats or +// eviction scan does not block request lookups even on one CPU. +const ( + sqliteMinReaders = 2 + sqliteMaxReaders = 8 +) + +// DB is the proxy database. The embedded pool takes every write. For SQLite +// it holds a single connection, as SQLite allows one writer at a time, and +// reads go to a separate read-only pool so they don't queue behind writes or +// behind each other (WAL mode lets readers run alongside the writer). For +// Postgres and in-memory SQLite both are the same pool. +// +// Get, Select, Query and QueryRow (and their Context forms) use the reader. +// Exec, transactions and everything else use the writer, so a read inside a +// transaction goes through the transaction and sees its own writes. type DB struct { *sqlx.DB + reader *sqlx.DB dialect Dialect path string hits *hitBatch @@ -75,24 +104,51 @@ func Open(path string) (*DB, error) { } } - // Add busy_timeout to handle concurrent writes - sqlDB, err := sqlx.Open("sqlite", path+"?_busy_timeout=5000") + writer, err := sqlx.Open("sqlite", path+sqliteWriterParams) if err != nil { return nil, fmt.Errorf("opening database: %w", err) } + // One connection serializes writes, so they never wait on SQLite's + // busy timeout for each other. + writer.SetMaxOpenConns(1) - // Limit connections to 1 for SQLite to serialize writes - sqlDB.SetMaxOpenConns(1) - - db := &DB{DB: sqlDB, dialect: DialectSQLite, path: path} - if err := db.OptimizeForReads(); err != nil { - _ = sqlDB.Close() - return nil, fmt.Errorf("optimizing database: %w", err) + // Connecting applies journal_mode=WAL before any reader opens the file. + if err := writer.Ping(); err != nil { + _ = writer.Close() + return nil, fmt.Errorf("opening database: %w", err) } + db := &DB{DB: writer, reader: writer, dialect: DialectSQLite, path: path} + if isMemoryPath(path) { + // Each connection to an in-memory database gets its own empty + // database, so the reads have to share the writer's connection. + return db, nil + } + + reader, err := sqlx.Open("sqlite", path+sqliteReaderParams) + if err != nil { + _ = writer.Close() + return nil, fmt.Errorf("opening database reader: %w", err) + } + n := sqliteReaderConns() + reader.SetMaxOpenConns(n) + reader.SetMaxIdleConns(n) + db.reader = reader + return db, nil } +func sqliteReaderConns() int { + return min(max(runtime.GOMAXPROCS(0), sqliteMinReaders), sqliteMaxReaders) +} + +// isMemoryPath reports whether path names an in-memory database, as +// ":memory:" or a URI such as "file::memory:?cache=shared" or +// "file:x?mode=memory". +func isMemoryPath(path string) bool { + return path == "" || strings.Contains(path, ":memory:") || strings.Contains(path, "mode=memory") +} + func OpenOrCreate(path string) (*DB, error) { if Exists(path) { return Open(path) @@ -116,7 +172,7 @@ func OpenPostgres(url string) (*DB, error) { return nil, fmt.Errorf("connecting to postgres: %w", err) } - return &DB{DB: sqlDB, dialect: DialectPostgres}, nil + return &DB{DB: sqlDB, reader: sqlDB, dialect: DialectPostgres}, nil } func OpenPostgresOrCreate(url string) (*DB, error) { @@ -125,18 +181,24 @@ func OpenPostgresOrCreate(url string) (*DB, error) { return nil, err } - var exists bool - err = db.Get(&exists, "SELECT EXISTS (SELECT FROM information_schema.tables WHERE table_name = 'schema_info')") + // Instances started together on an empty database would otherwise + // create the schema at the same time and fail on each other's tables. + err = db.WithLock(context.Background(), schemaLock, func() error { + var exists bool + if err := db.Get(&exists, "SELECT EXISTS (SELECT FROM information_schema.tables WHERE table_name = 'schema_info')"); err != nil { + return fmt.Errorf("checking schema: %w", err) + } + if exists { + return nil + } + if err := db.CreateSchema(); err != nil { + return fmt.Errorf("creating schema: %w", err) + } + return nil + }) if err != nil { _ = db.Close() - return nil, fmt.Errorf("checking schema: %w", err) - } - - if !exists { - if err := db.CreateSchema(); err != nil { - _ = db.Close() - return nil, fmt.Errorf("creating schema: %w", err) - } + return nil, err } return db, nil @@ -172,3 +234,56 @@ func (db *DB) Path() string { func (db *DB) Rebind(query string) string { return db.DB.Rebind(query) } + +// Get runs a read on the reader pool. +func (db *DB) Get(dest any, query string, args ...any) error { + return db.reader.Get(dest, query, args...) +} + +// GetContext runs a read on the reader pool. +func (db *DB) GetContext(ctx context.Context, dest any, query string, args ...any) error { + return db.reader.GetContext(ctx, dest, query, args...) +} + +// Select runs a read on the reader pool. +func (db *DB) Select(dest any, query string, args ...any) error { + return db.reader.Select(dest, query, args...) +} + +// SelectContext runs a read on the reader pool. +func (db *DB) SelectContext(ctx context.Context, dest any, query string, args ...any) error { + return db.reader.SelectContext(ctx, dest, query, args...) +} + +// Query runs a read on the reader pool. +func (db *DB) Query(query string, args ...any) (*sql.Rows, error) { + return db.reader.Query(query, args...) +} + +// QueryContext runs a read on the reader pool. +func (db *DB) QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error) { + return db.reader.QueryContext(ctx, query, args...) +} + +// QueryRow runs a read on the reader pool. +func (db *DB) QueryRow(query string, args ...any) *sql.Row { + return db.reader.QueryRow(query, args...) +} + +// QueryRowContext runs a read on the reader pool. +func (db *DB) QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row { + return db.reader.QueryRowContext(ctx, query, args...) +} + +// closePools closes the reader pool, if separate, then the writer. The +// writer goes last so that, as the last connection, it checkpoints the WAL. +func (db *DB) closePools() error { + var readerErr error + if db.reader != nil && db.reader != db.DB { + readerErr = db.reader.Close() + } + if err := db.DB.Close(); err != nil { + return err + } + return readerErr +} diff --git a/internal/database/database_test.go b/internal/database/database_test.go index f09a86a..500ad0d 100644 --- a/internal/database/database_test.go +++ b/internal/database/database_test.go @@ -613,7 +613,7 @@ func createTestPostgresDB(t *testing.T) *DB { // Drop and recreate every table CreateSchema creates for clean test state; // leftover migration records make the next CreateSchema fail on the // migrations primary key. - tables := []string{"artifacts", "pending_deletes", "versions", "packages", "vulnerabilities", "metadata_cache", "metadata_dates", "migrations", "schema_info"} + tables := []string{"artifacts", "pending_deletes", "versions", "packages", "vulnerabilities", "metadata_cache", "metadata_dates", "job_runs", "fetch_leases", "upstream_holds", "metadata_snapshots", "projects", "project_components", "migrations", "schema_info"} for _, table := range tables { _, _ = db.Exec("DROP TABLE IF EXISTS " + table + " CASCADE") } @@ -1164,3 +1164,86 @@ func TestVersionPublishedAtPreserved(t *testing.T) { } }) } + +func TestGetFetchedVersionPURLs(t *testing.T) { + runWithBothDatabases(t, func(t *testing.T, db *DB) { + const pkg = "pkg:npm/leftpad" + for _, v := range []string{"1.0.0", "2.0.0", "3.0.0"} { + if err := db.UpsertVersion(&Version{PURL: pkg + "@" + v, PackagePURL: pkg}); err != nil { + t.Fatalf("UpsertVersion: %v", err) + } + } + if err := db.UpsertVersion(&Version{PURL: "pkg:npm/other@1.0.0", PackagePURL: "pkg:npm/other"}); err != nil { + t.Fatalf("UpsertVersion: %v", err) + } + artifacts := []Artifact{ + {VersionPURL: pkg + "@1.0.0", Filename: "leftpad-1.0.0.tgz", UpstreamURL: "https://example.com/1", + StoragePath: sql.NullString{String: "npm/leftpad-1.0.0.tgz", Valid: true}}, + // Evicted: the row stays without a storage path. + {VersionPURL: pkg + "@2.0.0", Filename: "leftpad-2.0.0.tgz", UpstreamURL: "https://example.com/2"}, + {VersionPURL: "pkg:npm/other@1.0.0", Filename: "other-1.0.0.tgz", UpstreamURL: "https://example.com/3"}, + } + for i := range artifacts { + if err := db.UpsertArtifact(&artifacts[i]); err != nil { + t.Fatalf("UpsertArtifact: %v", err) + } + } + + got, err := db.GetFetchedVersionPURLs(pkg) + if err != nil { + t.Fatalf("GetFetchedVersionPURLs: %v", err) + } + want := map[string]bool{pkg + "@1.0.0": true, pkg + "@2.0.0": true} + if len(got) != len(want) { + t.Fatalf("got %v, want %v", got, want) + } + for purl := range want { + if !got[purl] { + t.Errorf("missing %s in %v", purl, got) + } + } + }) +} + +// Publish times are written in UTC whatever zone the caller's time is in, so +// a TIMESTAMP column without a zone reads back the same instant. +func TestVersionPublishedAtIsUTC(t *testing.T) { + tokyo, err := time.LoadLocation("Asia/Tokyo") + if err != nil { + t.Skipf("time zone data unavailable: %v", err) + } + prev := time.Local + time.Local = tokyo + t.Cleanup(func() { time.Local = prev }) + + runWithBothDatabases(t, func(t *testing.T, db *DB) { + written := time.Date(2026, 10, 10, 21, 0, 1, 0, tokyo) + want := written.UTC() + check := func(purl string) { + t.Helper() + got, err := db.GetVersionByPURL(purl) + if err != nil || got == nil || !got.PublishedAt.Valid { + t.Fatalf("GetVersionByPURL(%s) = %+v, %v", purl, got, err) + } + // Postgres reads TIMESTAMP back as a fixed +0000 zone rather + // than time.UTC, so compare the offset. + if _, offset := got.PublishedAt.Time.Zone(); !got.PublishedAt.Time.Equal(want) || offset != 0 { + t.Errorf("%s PublishedAt read back as %v, want %v", purl, got.PublishedAt.Time, want) + } + } + + if err := db.SetVersionPublishedAt("pkg:cargo/demo@1.0.0", "pkg:cargo/demo", written); err != nil { + t.Fatal(err) + } + check("pkg:cargo/demo@1.0.0") + + if err := db.UpsertVersion(&Version{ + PURL: "pkg:cargo/demo@2.0.0", + PackagePURL: "pkg:cargo/demo", + PublishedAt: sql.NullTime{Time: written, Valid: true}, + }); err != nil { + t.Fatal(err) + } + check("pkg:cargo/demo@2.0.0") + }) +} diff --git a/internal/database/ecosystem_filter.go b/internal/database/ecosystem_filter.go new file mode 100644 index 0000000..17d66ba --- /dev/null +++ b/internal/database/ecosystem_filter.go @@ -0,0 +1,34 @@ +package database + +import ( + "slices" + "strings" + + "github.com/git-pkgs/purl" +) + +// ecosystemSpellings returns the names an ecosystem's packages can be stored +// under. The proxy's handlers write "gem" and "composer" where git-pkgs, and +// proxy mirror before it used the handler names, write "rubygems" and +// "packagist". +func ecosystemSpellings(ecosystem string) []string { + purlType := purl.EcosystemToPURLType(ecosystem) + spellings := []string{ecosystem} + for _, s := range []string{purlType, purl.PURLTypeToEcosystem(purlType)} { + if s != "" && !slices.Contains(spellings, s) { + spellings = append(spellings, s) + } + } + return spellings +} + +// ecosystemFilter returns a condition matching p.ecosystem against every +// spelling of ecosystem, and its arguments. +func ecosystemFilter(ecosystem string) (string, []any) { + spellings := ecosystemSpellings(ecosystem) + args := make([]any, len(spellings)) + for i, s := range spellings { + args[i] = s + } + return "p.ecosystem IN (" + strings.TrimSuffix(strings.Repeat("?, ", len(spellings)), ", ") + ")", args +} diff --git a/internal/database/fetch_leases.go b/internal/database/fetch_leases.go new file mode 100644 index 0000000..56390e3 --- /dev/null +++ b/internal/database/fetch_leases.go @@ -0,0 +1,94 @@ +package database + +import ( + "database/sql" + "errors" + "fmt" + "time" +) + +// Fetch leases let instances sharing a Postgres database fetch each cache +// miss from upstream once. The instance that fetches holds the lease for the +// miss's key and renews it until the result is stored; the others wait for +// the stored result. Expiry uses the database clock, so instances whose +// clocks disagree still agree on when a lease has run out. SQLite is +// single-instance, so these are only used on Postgres. + +// AcquireFetchLease takes the lease on key for owner unless another owner +// holds one that has neither expired nor failed, and reports whether it did. +func (db *DB) AcquireFetchLease(key, owner string, ttl time.Duration) (bool, error) { + res, err := db.Exec(` + INSERT INTO fetch_leases (key, owner, expires_at) + VALUES ($1, $2, now() + $3 * interval '1 millisecond') + ON CONFLICT (key) DO UPDATE SET owner = excluded.owner, expires_at = excluded.expires_at, failed = FALSE + WHERE fetch_leases.expires_at < now() OR fetch_leases.failed`, key, owner, ttl.Milliseconds()) + if err != nil { + return false, fmt.Errorf("acquiring fetch lease: %w", err) + } + n, err := res.RowsAffected() + if err != nil { + return false, fmt.Errorf("acquiring fetch lease: %w", err) + } + return n > 0, nil +} + +// RenewFetchLease extends owner's lease on key by ttl from now, and reports +// whether owner still held it. +func (db *DB) RenewFetchLease(key, owner string, ttl time.Duration) (bool, error) { + res, err := db.Exec(` + UPDATE fetch_leases SET expires_at = now() + $3 * interval '1 millisecond' + WHERE key = $1 AND owner = $2`, key, owner, ttl.Milliseconds()) + if err != nil { + return false, fmt.Errorf("renewing fetch lease: %w", err) + } + n, err := res.RowsAffected() + if err != nil { + return false, fmt.Errorf("renewing fetch lease: %w", err) + } + return n > 0, nil +} + +// FetchLeaseHolder returns the owner of the lease on key, and whether its +// fetch failed. ok is false when no lease is held or it has expired. +func (db *DB) FetchLeaseHolder(key string) (owner string, failed, ok bool, err error) { + err = db.QueryRow(` + SELECT owner, failed FROM fetch_leases + WHERE key = $1 AND expires_at >= now()`, key).Scan(&owner, &failed) + if errors.Is(err, sql.ErrNoRows) { + return "", false, false, nil + } + if err != nil { + return "", false, false, fmt.Errorf("reading fetch lease: %w", err) + } + return owner, failed, true, nil +} + +// FailFetchLease marks owner's lease on key as failed. Instances waiting on +// it stop waiting, and the next AcquireFetchLease takes it at once. +func (db *DB) FailFetchLease(key, owner string) error { + if _, err := db.Exec(`UPDATE fetch_leases SET failed = TRUE WHERE key = $1 AND owner = $2`, key, owner); err != nil { + return fmt.Errorf("failing fetch lease: %w", err) + } + return nil +} + +// ReleaseFetchLease drops owner's lease on key. +func (db *DB) ReleaseFetchLease(key, owner string) error { + if _, err := db.Exec(`DELETE FROM fetch_leases WHERE key = $1 AND owner = $2`, key, owner); err != nil { + return fmt.Errorf("releasing fetch lease: %w", err) + } + return nil +} + +// DeleteExpiredFetchLeases removes leases that expired more than grace ago, +// left by instances that stopped while fetching. +func (db *DB) DeleteExpiredFetchLeases(grace time.Duration) (int64, error) { + if db.dialect != DialectPostgres { + return 0, nil + } + res, err := db.Exec(`DELETE FROM fetch_leases WHERE expires_at < now() - $1 * interval '1 millisecond'`, grace.Milliseconds()) + if err != nil { + return 0, fmt.Errorf("deleting expired fetch leases: %w", err) + } + return res.RowsAffected() +} diff --git a/internal/database/hits.go b/internal/database/hits.go index 4b5de0b..3609b5f 100644 --- a/internal/database/hits.go +++ b/internal/database/hits.go @@ -2,6 +2,7 @@ package database import ( "cmp" + "errors" "log/slog" "slices" "sync" @@ -20,9 +21,14 @@ type hitEntry struct { last time.Time } +// metadataHitKey identifies a metadata cache row; a hit only moves its +// last-access time. +type metadataHitKey struct{ ecosystem, name string } + type hitBatch struct { mu sync.Mutex pending map[hitKey]hitEntry + metadata map[metadataHitKey]time.Time stop chan struct{} stopOnce sync.Once done chan struct{} @@ -39,6 +45,22 @@ func (b *hitBatch) add(k hitKey, e hitEntry) { b.pending[k] = cur } +func (b *hitBatch) addMetadata(k metadataHitKey, last time.Time) { + b.mu.Lock() + defer b.mu.Unlock() + if last.After(b.metadata[k]) { + b.metadata[k] = last + } +} + +func (b *hitBatch) takeMetadata() map[metadataHitKey]time.Time { + b.mu.Lock() + defer b.mu.Unlock() + metadata := b.metadata + b.metadata = map[metadataHitKey]time.Time{} + return metadata +} + func (b *hitBatch) take() map[hitKey]hitEntry { b.mu.Lock() defer b.mu.Unlock() @@ -57,7 +79,7 @@ func (db *DB) BatchHits(interval time.Duration, logger *slog.Logger) { if logger == nil { logger = slog.New(slog.DiscardHandler) } - b := &hitBatch{pending: map[hitKey]hitEntry{}, stop: make(chan struct{}), done: make(chan struct{})} + b := &hitBatch{pending: map[hitKey]hitEntry{}, metadata: map[metadataHitKey]time.Time{}, stop: make(chan struct{}), done: make(chan struct{})} db.hits = b go func() { defer close(b.done) @@ -83,9 +105,10 @@ func (db *DB) BatchHits(interval time.Duration, logger *slog.Logger) { // fails they are put back for the next flush, so a failed write delays // counts rather than losing them. func (db *DB) flushHits() error { + metadataErr := db.flushMetadataHits() pending := db.hits.take() if len(pending) == 0 { - return nil + return metadataErr } err := db.writeHits(pending) @@ -94,9 +117,54 @@ func (db *DB) flushHits() error { db.hits.add(k, e) } } + return errors.Join(err, metadataErr) +} + +// flushMetadataHits writes the pending metadata hits like flushHits. +func (db *DB) flushMetadataHits() error { + metadata := db.hits.takeMetadata() + if len(metadata) == 0 { + return nil + } + err := db.writeMetadataHits(metadata) + if err != nil { + for k, last := range metadata { + db.hits.addMetadata(k, last) + } + } return err } +func (db *DB) writeMetadataHits(metadata map[metadataHitKey]time.Time) error { + tx, err := db.Beginx() + if err != nil { + return err + } + defer func() { _ = tx.Rollback() }() + + stmt, err := tx.Preparex(db.Rebind(recordMetadataHitQuery)) + if err != nil { + return err + } + defer func() { _ = stmt.Close() }() + + // Sorted for the same reason as the artifact hits. + keys := make([]metadataHitKey, 0, len(metadata)) + for k := range metadata { + keys = append(keys, k) + } + slices.SortFunc(keys, func(a, b metadataHitKey) int { + return cmp.Or(cmp.Compare(a.ecosystem, b.ecosystem), cmp.Compare(a.name, b.name)) + }) + for _, k := range keys { + last := metadata[k].UTC() + if _, err := stmt.Exec(last, last, k.ecosystem, k.name); err != nil { + return err + } + } + return tx.Commit() +} + func (db *DB) writeHits(pending map[hitKey]hitEntry) error { tx, err := db.Beginx() if err != nil { @@ -143,5 +211,5 @@ func (db *DB) Close() error { b.stopOnce.Do(func() { close(b.stop) }) <-b.done } - return db.DB.Close() + return db.closePools() } diff --git a/internal/database/local_artifacts.go b/internal/database/local_artifacts.go index 8319776..162b471 100644 --- a/internal/database/local_artifacts.go +++ b/internal/database/local_artifacts.go @@ -31,27 +31,32 @@ func (db *DB) GetLocalArtifacts(packagePURL string) ([]LocalArtifact, error) { return artifacts, nil } -// DeleteLocalArtifacts removes the pushed artifacts of a version and queues -// their stored objects for deletion in the same transaction, so a failed -// queue keeps the records instead of orphaning the objects. Artifacts cached -// from an upstream are left alone. It returns how many records it removed. -func (db *DB) DeleteLocalArtifacts(versionPURL string) (int, error) { +// DeleteLocalArtifacts removes the pushed artifacts of a version, or only the +// one named filename when it is set, and queues their stored objects for +// deletion in the same transaction, so a failed queue keeps the records +// instead of orphaning the objects. Artifacts cached from an upstream are left +// alone. It returns how many records it removed. +func (db *DB) DeleteLocalArtifacts(versionPURL, filename string) (int, error) { tx, err := db.Beginx() if err != nil { return 0, err } defer func() { _ = tx.Rollback() }() + where := "version_purl = ? AND source = 'local'" + args := []any{versionPURL} + if filename != "" { + where += " AND filename = ?" + args = append(args, filename) + } + var paths []string - selectQuery := db.Rebind(` - SELECT storage_path FROM artifacts - WHERE version_purl = ? AND source = 'local' AND storage_path IS NOT NULL - `) - if err := tx.Select(&paths, selectQuery, versionPURL); err != nil { + selectQuery := db.Rebind(`SELECT storage_path FROM artifacts WHERE ` + where + ` AND storage_path IS NOT NULL`) + if err := tx.Select(&paths, selectQuery, args...); err != nil { return 0, fmt.Errorf("reading local artifacts: %w", err) } - res, err := tx.Exec(db.Rebind(`DELETE FROM artifacts WHERE version_purl = ? AND source = 'local'`), versionPURL) + res, err := tx.Exec(db.Rebind(`DELETE FROM artifacts WHERE `+where), args...) if err != nil { return 0, fmt.Errorf("deleting local artifacts: %w", err) } @@ -68,3 +73,54 @@ func (db *DB) DeleteLocalArtifacts(versionPURL string) (int, error) { } return int(deleted), tx.Commit() } + +// RecordLocalArtifact records a pushed artifact in one transaction: the +// package if it is missing, the version, and the artifact. An artifact cached +// from an upstream under the same name is replaced and its stored object +// queued for deletion; a pushed one is never replaced, and the whole record +// is refused with ErrLocalArtifactExists, so of two concurrent pushes of the +// same file exactly one wins. +// +// When oneFilePerVersion is false, an existing version record is left as it +// is. Otherwise its integrity is set to v.Integrity, and the push is refused +// if the version already holds a pushed artifact under any filename, since +// aliases of one name (Composer's are case-insensitive) share the version +// record and its integrity. The version upsert locks that record first, so +// concurrent pushes of aliases see each other. +func (db *DB) RecordLocalArtifact(pkg *Package, v *Version, oneFilePerVersion bool, a *Artifact) error { + local := *a + local.Source = SourceLocal + return db.recordArtifact(&local, func(tx execer) error { + now := time.Now() + if _, err := tx.Exec(db.Rebind(` + INSERT INTO packages (purl, ecosystem, name, created_at, updated_at) + VALUES (?, ?, ?, ?, ?) + ON CONFLICT(purl) DO NOTHING + `), pkg.PURL, pkg.Ecosystem, pkg.Name, now, now); err != nil { + return fmt.Errorf("inserting package: %w", err) + } + versionConflict := `DO NOTHING` + if oneFilePerVersion { + versionConflict = `DO UPDATE SET integrity = excluded.integrity, updated_at = excluded.updated_at` + } + if _, err := tx.Exec(db.Rebind(` + INSERT INTO versions (purl, package_purl, integrity, created_at, updated_at) + VALUES (?, ?, ?, ?, ?) + ON CONFLICT(purl) `+versionConflict, + ), v.PURL, v.PackagePURL, v.Integrity, now, now); err != nil { + return fmt.Errorf("recording version: %w", err) + } + if oneFilePerVersion { + var pushed int + if err := tx.Get(&pushed, db.Rebind(` + SELECT COUNT(*) FROM artifacts WHERE version_purl = ? AND source = ? + `), v.PURL, SourceLocal); err != nil { + return fmt.Errorf("checking pushed artifacts: %w", err) + } + if pushed > 0 { + return ErrLocalArtifactExists + } + } + return nil + }, ErrLocalArtifactExists) +} diff --git a/internal/database/local_artifacts_test.go b/internal/database/local_artifacts_test.go index 81d5ec8..a6d0ed5 100644 --- a/internal/database/local_artifacts_test.go +++ b/internal/database/local_artifacts_test.go @@ -2,7 +2,10 @@ package database import ( "database/sql" + "errors" + "fmt" "path/filepath" + "sync" "testing" "time" ) @@ -183,7 +186,7 @@ func TestDeleteLocalArtifacts(t *testing.T) { seedSourcedArtifact(t, db, "express", SourceUpstream, 100, time.Now()) const pushedPath = "npm/request/1.0.0/request-1.0.0.tgz" - deleted, err := db.DeleteLocalArtifacts("pkg:npm/request@1.0.0") + deleted, err := db.DeleteLocalArtifacts("pkg:npm/request@1.0.0", "") if err != nil || deleted != 1 { t.Fatalf("DeleteLocalArtifacts(request) = %d, %v, want 1, nil", deleted, err) } @@ -196,7 +199,7 @@ func TestDeleteLocalArtifacts(t *testing.T) { t.Errorf("queued deletes for %s = %d, %v, want 1", pushedPath, queued, err) } - deleted, err = db.DeleteLocalArtifacts("pkg:npm/express@1.0.0") + deleted, err = db.DeleteLocalArtifacts("pkg:npm/express@1.0.0", "") if err != nil || deleted != 0 { t.Errorf("DeleteLocalArtifacts(upstream) = %d, %v, want 0, nil", deleted, err) } @@ -295,3 +298,210 @@ func TestUpsertPackageKeepsSource(t *testing.T) { } }) } + +func localPush(versionPURL, filename, storagePath string) *Artifact { + return &Artifact{ + VersionPURL: versionPURL, + Filename: filename, + StoragePath: sql.NullString{String: storagePath, Valid: true}, + ContentHash: sql.NullString{String: storagePath, Valid: true}, + Size: sql.NullInt64{Int64: 1, Valid: true}, + FetchedAt: sql.NullTime{Time: time.Now(), Valid: true}, + } +} + +func TestRecordLocalArtifactNeverReplacesAPush(t *testing.T) { + runWithBothDatabases(t, func(t *testing.T, db *DB) { + pkg := &Package{PURL: "pkg:npm/request", Ecosystem: "npm", Name: "request"} + version := func(integrity string) *Version { + return &Version{PURL: "pkg:npm/request@1.0.0", PackagePURL: pkg.PURL, + Integrity: sql.NullString{String: integrity, Valid: true}} + } + + first := localPush("pkg:npm/request@1.0.0", "request-1.0.0.tgz", "npm/request/first") + if err := db.RecordLocalArtifact(pkg, version("sha512-first"), true, first); err != nil { + t.Fatalf("first RecordLocalArtifact: %v", err) + } + second := localPush("pkg:npm/request@1.0.0", "request-1.0.0.tgz", "npm/request/second") + if err := db.RecordLocalArtifact(pkg, version("sha512-second"), true, second); !errors.Is(err, ErrLocalArtifactExists) { + t.Fatalf("second RecordLocalArtifact error = %v, want ErrLocalArtifactExists", err) + } + + art, err := db.GetArtifact("pkg:npm/request@1.0.0", "request-1.0.0.tgz") + if err != nil || art == nil || art.StoragePath.String != "npm/request/first" || art.Source != SourceLocal { + t.Fatalf("artifact after refused push = %+v, %v, want the first push", art, err) + } + v, err := db.GetVersionByPURL("pkg:npm/request@1.0.0") + if err != nil || v == nil || v.Integrity.String != "sha512-first" { + t.Errorf("version integrity after refused push = %+v, %v, want the first push's", v, err) + } + var queued int + if err := db.Get(&queued, db.Rebind(`SELECT COUNT(*) FROM pending_deletes`)); err != nil || queued != 0 { + t.Errorf("queued deletes = %d, %v, want none", queued, err) + } + }) +} + +func TestRecordLocalArtifactReplacesUpstreamCopy(t *testing.T) { + runWithBothDatabases(t, func(t *testing.T, db *DB) { + seedSourcedArtifact(t, db, "request", SourceUpstream, 100, time.Now()) + pkg := &Package{PURL: "pkg:npm/request", Ecosystem: "npm", Name: "request"} + v := &Version{PURL: "pkg:npm/request@1.0.0", PackagePURL: pkg.PURL} + + pushed := localPush("pkg:npm/request@1.0.0", "request-1.0.0.tgz", "npm/request/pushed") + if err := db.RecordLocalArtifact(pkg, v, true, pushed); err != nil { + t.Fatalf("RecordLocalArtifact: %v", err) + } + art, err := db.GetArtifact("pkg:npm/request@1.0.0", "request-1.0.0.tgz") + if err != nil || art == nil || art.Source != SourceLocal || art.StoragePath.String != "npm/request/pushed" { + t.Fatalf("artifact = %+v, %v, want the push", art, err) + } + const upstreamPath = "npm/request/1.0.0/request-1.0.0.tgz" + var queued int + if err := db.Get(&queued, db.Rebind(`SELECT COUNT(*) FROM pending_deletes WHERE path = ?`), upstreamPath); err != nil || queued != 1 { + t.Errorf("queued deletes for the upstream copy = %d, %v, want 1", queued, err) + } + }) +} + +func TestRecordLocalArtifactCanKeepTheVersionRecord(t *testing.T) { + runWithBothDatabases(t, func(t *testing.T, db *DB) { + pkg := &Package{PURL: "pkg:generic/tools", Ecosystem: "generic", Name: "tools"} + if err := db.UpsertPackage(pkg); err != nil { + t.Fatalf("UpsertPackage: %v", err) + } + if err := db.UpsertVersion(&Version{PURL: "pkg:generic/tools@1.2.0", PackagePURL: pkg.PURL, + License: sql.NullString{String: "MIT", Valid: true}, + Integrity: sql.NullString{String: "sha256-upstream", Valid: true}}); err != nil { + t.Fatalf("UpsertVersion: %v", err) + } + + pushed := localPush("pkg:generic/tools@1.2.0", "tool.tar.gz", "generic/tools/pushed") + if err := db.RecordLocalArtifact(pkg, &Version{PURL: "pkg:generic/tools@1.2.0", PackagePURL: pkg.PURL}, false, pushed); err != nil { + t.Fatalf("RecordLocalArtifact: %v", err) + } + v, err := db.GetVersionByPURL("pkg:generic/tools@1.2.0") + if err != nil || v == nil || v.Integrity.String != "sha256-upstream" || v.License.String != "MIT" { + t.Errorf("version after push = %+v, %v, want it unchanged", v, err) + } + }) +} + +func TestRecordLocalArtifactConcurrentPushesHaveOneWinner(t *testing.T) { + runWithBothDatabases(t, func(t *testing.T, db *DB) { + pkg := &Package{PURL: "pkg:generic/tools", Ecosystem: "generic", Name: "tools"} + const pushes = 8 + start := make(chan struct{}) + errs := make([]error, pushes) + var wg sync.WaitGroup + for i := range pushes { + wg.Go(func() { + <-start + v := &Version{PURL: "pkg:generic/tools@1.2.0", PackagePURL: pkg.PURL} + a := localPush("pkg:generic/tools@1.2.0", "tool.tar.gz", fmt.Sprintf("generic/tools/push-%d", i)) + errs[i] = db.RecordLocalArtifact(pkg, v, false, a) + }) + } + close(start) + wg.Wait() + + winners := 0 + for i, err := range errs { + switch { + case err == nil: + winners++ + case !errors.Is(err, ErrLocalArtifactExists): + t.Errorf("push %d error = %v, want ErrLocalArtifactExists", i, err) + } + } + if winners != 1 { + t.Errorf("%d pushes succeeded, want exactly 1", winners) + } + }) +} + +// Aliases of one name, such as Composer names differing in case, share the +// version record and its integrity, so only one of them may be pushed. +func TestRecordLocalArtifactOneFilePerVersionRefusesAliases(t *testing.T) { + runWithBothDatabases(t, func(t *testing.T, db *DB) { + pkg := &Package{PURL: "pkg:composer/acme/private", Ecosystem: "composer", Name: "acme/private"} + const pushes = 8 + start := make(chan struct{}) + errs := make([]error, pushes) + var wg sync.WaitGroup + for i := range pushes { + wg.Go(func() { + <-start + v := &Version{PURL: "pkg:composer/acme/private@1.0.0", PackagePURL: pkg.PURL, + Integrity: sql.NullString{String: fmt.Sprintf("sha512-push-%d", i), Valid: true}} + a := localPush("pkg:composer/acme/private@1.0.0", fmt.Sprintf("alias-%d-1.0.0.zip", i), + fmt.Sprintf("composer/acme/private/push-%d", i)) + errs[i] = db.RecordLocalArtifact(pkg, v, true, a) + }) + } + close(start) + wg.Wait() + + winner := -1 + for i, err := range errs { + switch { + case err == nil: + if winner >= 0 { + t.Errorf("pushes %d and %d both succeeded, want exactly 1", winner, i) + } + winner = i + case !errors.Is(err, ErrLocalArtifactExists): + t.Errorf("push %d error = %v, want ErrLocalArtifactExists", i, err) + } + } + if winner < 0 { + t.Fatal("no push succeeded") + } + artifacts, err := db.GetArtifactsByVersionPURL("pkg:composer/acme/private@1.0.0") + if err != nil { + t.Fatal(err) + } + if len(artifacts) != 1 || artifacts[0].Filename != fmt.Sprintf("alias-%d-1.0.0.zip", winner) { + t.Errorf("artifacts = %+v, want only push %d", artifacts, winner) + } + v, err := db.GetVersionByPURL("pkg:composer/acme/private@1.0.0") + if err != nil || v == nil || v.Integrity.String != fmt.Sprintf("sha512-push-%d", winner) { + t.Errorf("version = %+v, %v, want the integrity of push %d", v, err, winner) + } + }) +} + +func TestRecordCachedArtifactNeverReplacesAPush(t *testing.T) { + runWithBothDatabases(t, func(t *testing.T, db *DB) { + pkg := &Package{PURL: "pkg:npm/request", Ecosystem: "npm", Name: "request"} + pushed := localPush("pkg:npm/request@1.0.0", "request-1.0.0.tgz", "npm/request/pushed") + if err := db.RecordLocalArtifact(pkg, &Version{PURL: "pkg:npm/request@1.0.0", PackagePURL: pkg.PURL, + Integrity: sql.NullString{String: "sha512-pushed", Valid: true}}, true, pushed); err != nil { + t.Fatalf("RecordLocalArtifact: %v", err) + } + + fetched := &Artifact{ + VersionPURL: "pkg:npm/request@1.0.0", + Filename: "request-1.0.0.tgz", + UpstreamURL: "https://registry.example/request-1.0.0.tgz", + StoragePath: sql.NullString{String: "npm/request/fetched", Valid: true}, + } + err := db.RecordCachedArtifact(pkg, &Version{PURL: "pkg:npm/request@1.0.0", PackagePURL: pkg.PURL, + Integrity: sql.NullString{String: "sha512-upstream", Valid: true}}, fetched) + if !errors.Is(err, ErrLocalArtifactExists) { + t.Fatalf("RecordCachedArtifact error = %v, want ErrLocalArtifactExists", err) + } + if err := db.UpsertArtifact(fetched); !errors.Is(err, ErrLocalArtifactExists) { + t.Errorf("UpsertArtifact error = %v, want ErrLocalArtifactExists", err) + } + + art, err := db.GetArtifact("pkg:npm/request@1.0.0", "request-1.0.0.tgz") + if err != nil || art == nil || art.Source != SourceLocal || art.StoragePath.String != "npm/request/pushed" { + t.Errorf("artifact = %+v, %v, want the push", art, err) + } + v, err := db.GetVersionByPURL("pkg:npm/request@1.0.0") + if err != nil || v == nil || v.Integrity.String != "sha512-pushed" { + t.Errorf("version = %+v, %v, want the push's integrity", v, err) + } + }) +} diff --git a/internal/database/lock.go b/internal/database/lock.go new file mode 100644 index 0000000..f4b1f70 --- /dev/null +++ b/internal/database/lock.go @@ -0,0 +1,107 @@ +package database + +import ( + "context" + "database/sql" + "database/sql/driver" + "fmt" + "hash/fnv" + "time" +) + +// Several instances can share one Postgres database. Advisory locks keep +// them from creating the schema, migrating it or running a background job at +// the same time. SQLite is single-instance, so there every lock is granted +// at once. + +// lockKey maps a lock name to the 64-bit key Postgres advisory locks take. +func lockKey(name string) int64 { + h := fnv.New64a() + _, _ = h.Write([]byte("git-pkgs/proxy:" + name)) + return int64(h.Sum64()) //nolint:gosec // a key, wrapping is fine +} + +// WithLock runs fn while holding the named lock, waiting for another +// instance that holds it. +func (db *DB) WithLock(ctx context.Context, name string, fn func() error) error { + if db.dialect != DialectPostgres { + return fn() + } + conn, err := db.Conn(ctx) + if err != nil { + return fmt.Errorf("taking connection for lock %s: %w", name, err) + } + defer func() { _ = conn.Close() }() + if _, err := conn.ExecContext(ctx, "SELECT pg_advisory_lock($1)", lockKey(name)); err != nil { + return fmt.Errorf("taking lock %s: %w", name, err) + } + defer unlock(conn, name) + return fn() +} + +// TryLock takes the named lock if no other instance holds it. When ok is +// true the caller must call release once done. The lock lives in a +// connection held for that time, and Postgres frees it if the process dies. +func (db *DB) TryLock(ctx context.Context, name string) (release func(), ok bool, err error) { + if db.dialect != DialectPostgres { + return func() {}, true, nil + } + conn, err := db.Conn(ctx) + if err != nil { + return nil, false, fmt.Errorf("taking connection for lock %s: %w", name, err) + } + if err := conn.QueryRowContext(ctx, "SELECT pg_try_advisory_lock($1)", lockKey(name)).Scan(&ok); err != nil { + _ = conn.Close() + return nil, false, fmt.Errorf("taking lock %s: %w", name, err) + } + if !ok { + _ = conn.Close() + return nil, false, nil + } + return func() { + unlock(conn, name) + _ = conn.Close() + }, true, nil +} + +// unlockTimeout bounds the unlock. If it fails, closing the connection still +// ends the session that holds the lock. +const unlockTimeout = 10 * time.Second + +func unlock(conn *sql.Conn, name string) { + ctx, cancel := context.WithTimeout(context.Background(), unlockTimeout) + defer cancel() + if _, err := conn.ExecContext(ctx, "SELECT pg_advisory_unlock($1)", lockKey(name)); err != nil { + // Drop the connection so the session, and with it the lock, ends. + _ = conn.Raw(func(any) error { return driver.ErrBadConn }) + } +} + +// ClaimJobRun records that the named job starts now unless it started less +// than minGap ago, and reports whether the caller should run it. Instances +// sharing the database each keep their own timer for a scheduled job, and +// this lets only the first of them run it per interval. +func (db *DB) ClaimJobRun(name string, minGap time.Duration) (bool, error) { + now := time.Now().UTC() + res, err := db.Exec(db.Rebind(` + INSERT INTO job_runs (name, started_at) VALUES (?, ?) + ON CONFLICT(name) DO UPDATE SET started_at = excluded.started_at + WHERE job_runs.started_at <= ?`), name, now, now.Add(-minGap)) + if err != nil { + return false, fmt.Errorf("claiming job run %s: %w", name, err) + } + n, err := res.RowsAffected() + if err != nil { + return false, fmt.Errorf("claiming job run %s: %w", name, err) + } + return n > 0, nil +} + +// ReleaseJobRun drops the named job's last claim, so the next attempt on any +// instance runs it. It is for a run that was interrupted before it finished. +func (db *DB) ReleaseJobRun(name string) error { + if _, err := db.Exec(db.Rebind(`DELETE FROM job_runs WHERE name = ?`), name); err != nil { + return fmt.Errorf("releasing job run %s: %w", name, err) + } + return nil +} diff --git a/internal/database/lock_test.go b/internal/database/lock_test.go new file mode 100644 index 0000000..de3e64c --- /dev/null +++ b/internal/database/lock_test.go @@ -0,0 +1,347 @@ +package database + +import ( + "context" + "net/url" + "os" + "strings" + "sync" + "sync/atomic" + "testing" + "time" +) + +func TestTryLockSQLiteAlwaysGranted(t *testing.T) { + db := createTestDB(t) + defer func() { _ = db.Close() }() + release, ok, err := db.TryLock(context.Background(), "job:test") + if err != nil || !ok { + t.Fatalf("TryLock = %v, %v; want granted", ok, err) + } + // SQLite is single-instance, so a second holder is granted too. + release2, ok, err := db.TryLock(context.Background(), "job:test") + if err != nil || !ok { + t.Fatalf("second TryLock = %v, %v; want granted", ok, err) + } + release2() + release() +} + +func TestClaimJobRun(t *testing.T) { + forEachDialect(t, func(t *testing.T, db *DB) { + claimed, err := db.ClaimJobRun("mirror-schedule:a", time.Hour) + if err != nil || !claimed { + t.Fatalf("first claim = %v, %v; want claimed", claimed, err) + } + claimed, err = db.ClaimJobRun("mirror-schedule:a", time.Hour) + if err != nil || claimed { + t.Fatalf("claim within the gap = %v, %v; want not claimed", claimed, err) + } + claimed, err = db.ClaimJobRun("mirror-schedule:b", time.Hour) + if err != nil || !claimed { + t.Fatalf("claim of another job = %v, %v; want claimed", claimed, err) + } + // A run started longer ago than the gap can be claimed again. + claimed, err = db.ClaimJobRun("mirror-schedule:a", 0) + if err != nil || !claimed { + t.Fatalf("claim after the gap = %v, %v; want claimed", claimed, err) + } + // A released run can be claimed again within the gap. + if err := db.ReleaseJobRun("mirror-schedule:a"); err != nil { + t.Fatal(err) + } + claimed, err = db.ClaimJobRun("mirror-schedule:a", time.Hour) + if err != nil || !claimed { + t.Fatalf("claim after release = %v, %v; want claimed", claimed, err) + } + claimed, err = db.ClaimJobRun("mirror-schedule:b", time.Hour) + if err != nil || claimed { + t.Fatalf("other job after release = %v, %v; want still claimed", claimed, err) + } + }) +} + +// forEachDialect runs fn against SQLite and, when PROXY_DATABASE_URL is set, +// against Postgres. +func forEachDialect(t *testing.T, fn func(t *testing.T, db *DB)) { + t.Run("sqlite", func(t *testing.T) { + db := createTestDB(t) + defer func() { _ = db.Close() }() + fn(t, db) + }) + t.Run("postgres", func(t *testing.T) { + db := createTestPostgresDB(t) + if db == nil { + t.Skip("PROXY_DATABASE_URL not set") + } + defer func() { _ = db.Close() }() + fn(t, db) + }) +} + +func openTestPostgres(t *testing.T) *DB { + t.Helper() + dbURL := os.Getenv("PROXY_DATABASE_URL") + if dbURL == "" { + t.Skip("PROXY_DATABASE_URL not set") + } + db, err := OpenPostgres(dbURL) + if err != nil { + t.Fatalf("OpenPostgres: %v", err) + } + t.Cleanup(func() { _ = db.Close() }) + return db +} + +func TestTryLockPostgresExcludesOtherInstance(t *testing.T) { + a := openTestPostgres(t) + b := openTestPostgres(t) + ctx := context.Background() + + release, ok, err := a.TryLock(ctx, "job:test-exclusive") + if err != nil || !ok { + t.Fatalf("TryLock on a = %v, %v; want granted", ok, err) + } + if _, ok, err := b.TryLock(ctx, "job:test-exclusive"); err != nil || ok { + t.Fatalf("TryLock on b while a holds it = %v, %v; want refused", ok, err) + } + // Another lock name is independent. + releaseOther, ok, err := b.TryLock(ctx, "job:test-other") + if err != nil || !ok { + t.Fatalf("TryLock on another name = %v, %v; want granted", ok, err) + } + releaseOther() + + release() + release, ok, err = b.TryLock(ctx, "job:test-exclusive") + if err != nil || !ok { + t.Fatalf("TryLock on b after a released = %v, %v; want granted", ok, err) + } + release() +} + +func TestTryLockPostgresFreedWhenSessionEnds(t *testing.T) { + a := openTestPostgres(t) + b := openTestPostgres(t) + ctx := context.Background() + + if _, ok, err := a.TryLock(ctx, "job:test-crash"); err != nil || !ok { + t.Fatalf("TryLock on a = %v, %v; want granted", ok, err) + } + // End a's session holding the lock, as a crash would. + if _, err := b.Exec(`SELECT pg_terminate_backend(pid) FROM pg_locks + WHERE locktype = 'advisory' AND pid <> pg_backend_pid()`); err != nil { + t.Fatalf("terminating a's session: %v", err) + } + waitUntil(t, func() bool { + release, ok, err := b.TryLock(ctx, "job:test-crash") + if ok { + release() + } + return err == nil && ok + }) +} + +func TestWithLockPostgresSerialises(t *testing.T) { + const instances = 4 + dbs := make([]*DB, instances) + for i := range dbs { + dbs[i] = openTestPostgres(t) + } + var inside, overlapped atomic.Int32 + var wg sync.WaitGroup + for _, db := range dbs { + wg.Go(func() { + err := db.WithLock(context.Background(), "test-serialise", func() error { + if inside.Add(1) > 1 { + overlapped.Store(1) + } + time.Sleep(20 * time.Millisecond) + inside.Add(-1) + return nil + }) + if err != nil { + t.Errorf("WithLock: %v", err) + } + }) + } + wg.Wait() + if overlapped.Load() != 0 { + t.Error("two instances held the lock at once") + } +} + +// TestOpenPostgresOrCreateConcurrent starts several instances at once on an +// empty database. Without the schema lock all but one failed on each +// other's tables. +func TestOpenPostgresOrCreateConcurrent(t *testing.T) { + admin := openTestPostgres(t) + name := "proxy_lock_test_" + strings.ReplaceAll(time.Now().UTC().Format("150405.000000"), ".", "_") + if _, err := admin.Exec("CREATE DATABASE " + name); err != nil { + t.Skipf("cannot create a scratch database: %v", err) + } + t.Cleanup(func() { _, _ = admin.Exec("DROP DATABASE IF EXISTS " + name + " WITH (FORCE)") }) + + u, err := url.Parse(os.Getenv("PROXY_DATABASE_URL")) + if err != nil { + t.Fatalf("parsing PROXY_DATABASE_URL: %v", err) + } + u.Path = "/" + name + scratch := u.String() + + const instances = 5 + errs := make([]error, instances) + var wg sync.WaitGroup + start := make(chan struct{}) + for i := range instances { + wg.Go(func() { + <-start + db, err := OpenPostgresOrCreate(scratch) + if err == nil { + err = db.MigrateSchema() + _ = db.Close() + } + errs[i] = err + }) + } + close(start) + wg.Wait() + for i, err := range errs { + if err != nil { + t.Errorf("instance %d: %v", i, err) + } + } + + db, err := OpenPostgres(scratch) + if err != nil { + t.Fatalf("OpenPostgres: %v", err) + } + defer func() { _ = db.Close() }() + var n int + if err := db.Get(&n, "SELECT COUNT(*) FROM schema_info"); err != nil || n != 1 { + t.Errorf("schema_info rows = %d, %v; want 1", n, err) + } + if err := db.Get(&n, "SELECT COUNT(*) FROM migrations"); err != nil || n != len(migrations) { + t.Errorf("migrations rows = %d, %v; want %d", n, err, len(migrations)) + } +} + +func waitUntil(t *testing.T, cond func() bool) { + t.Helper() + deadline := time.Now().Add(5 * time.Second) + for !cond() { + if time.Now().After(deadline) { + t.Fatal("timed out") + } + time.Sleep(10 * time.Millisecond) + } +} + +func TestMigrateAddsJobRuns(t *testing.T) { + forEachDialect(t, func(t *testing.T, db *DB) { + // A database from before the job_runs migration. + if _, err := db.Exec("DROP TABLE job_runs"); err != nil { + t.Fatalf("dropping job_runs: %v", err) + } + if _, err := db.Exec(db.Rebind("DELETE FROM migrations WHERE name = ?"), "015_add_job_runs"); err != nil { + t.Fatalf("forgetting the migration: %v", err) + } + if err := db.MigrateSchema(); err != nil { + t.Fatalf("MigrateSchema: %v", err) + } + if claimed, err := db.ClaimJobRun("mirror-schedule:a", time.Hour); err != nil || !claimed { + t.Fatalf("ClaimJobRun after migration = %v, %v; want claimed", claimed, err) + } + }) +} + +func TestFetchLeases(t *testing.T) { + db := createTestPostgresDB(t) + if db == nil { + t.Skip("PROXY_DATABASE_URL not set") + } + defer func() { _ = db.Close() }() + + acquire := func(owner string, ttl time.Duration) bool { + t.Helper() + ok, err := db.AcquireFetchLease("k", owner, ttl) + if err != nil { + t.Fatalf("AcquireFetchLease(%s): %v", owner, err) + } + return ok + } + if !acquire("a", time.Minute) { + t.Fatal("a could not take a free lease") + } + if acquire("b", time.Minute) { + t.Fatal("b took a lease a holds") + } + if held, err := db.RenewFetchLease("k", "b", time.Minute); err != nil || held { + t.Fatalf("b renewed a's lease: %v, %v", held, err) + } + if held, err := db.RenewFetchLease("k", "a", time.Minute); err != nil || !held { + t.Fatalf("a could not renew its lease: %v, %v", held, err) + } + // Only the owner can release it. + if err := db.ReleaseFetchLease("k", "b"); err != nil { + t.Fatal(err) + } + if acquire("b", time.Minute) { + t.Fatal("b's release dropped a's lease") + } + if err := db.ReleaseFetchLease("k", "a"); err != nil { + t.Fatal(err) + } + if !acquire("b", time.Millisecond) { + t.Fatal("b could not take the lease a released") + } + time.Sleep(20 * time.Millisecond) + if !acquire("c", time.Millisecond) { + t.Fatal("c could not take b's expired lease") + } + time.Sleep(20 * time.Millisecond) + if n, err := db.DeleteExpiredFetchLeases(0); err != nil || n != 1 { + t.Fatalf("DeleteExpiredFetchLeases = %d, %v; want 1", n, err) + } +} + +func TestFetchLeaseFailure(t *testing.T) { + db := createTestPostgresDB(t) + if db == nil { + t.Skip("PROXY_DATABASE_URL not set") + } + defer func() { _ = db.Close() }() + + if ok, err := db.AcquireFetchLease("k", "a", time.Minute); err != nil || !ok { + t.Fatalf("a could not take a free lease: %v, %v", ok, err) + } + if owner, failed, ok, err := db.FetchLeaseHolder("k"); err != nil || !ok || owner != "a" || failed { + t.Fatalf("FetchLeaseHolder = %q, failed %v, ok %v, %v; want a's live lease", owner, failed, ok, err) + } + // A failed lease stays readable for those waiting on it, and is free to + // take. + if err := db.FailFetchLease("k", "b"); err != nil { + t.Fatal(err) + } + if _, failed, _, _ := db.FetchLeaseHolder("k"); failed { + t.Fatal("b failed a's lease") + } + if err := db.FailFetchLease("k", "a"); err != nil { + t.Fatal(err) + } + if owner, failed, ok, err := db.FetchLeaseHolder("k"); err != nil || !ok || owner != "a" || !failed { + t.Fatalf("FetchLeaseHolder = %q, failed %v, ok %v, %v; want a's failed lease", owner, failed, ok, err) + } + if ok, err := db.AcquireFetchLease("k", "b", time.Minute); err != nil || !ok { + t.Fatalf("b could not take a's failed lease: %v, %v", ok, err) + } + if owner, failed, _, _ := db.FetchLeaseHolder("k"); owner != "b" || failed { + t.Fatalf("after takeover: owner %q, failed %v", owner, failed) + } + if err := db.ReleaseFetchLease("k", "b"); err != nil { + t.Fatal(err) + } + if _, _, ok, err := db.FetchLeaseHolder("k"); err != nil || ok { + t.Fatalf("FetchLeaseHolder after release: ok %v, %v", ok, err) + } +} diff --git a/internal/database/metadata_cache_test.go b/internal/database/metadata_cache_test.go index 26e0a63..ee16c25 100644 --- a/internal/database/metadata_cache_test.go +++ b/internal/database/metadata_cache_test.go @@ -2,7 +2,9 @@ package database import ( "database/sql" + "fmt" "path/filepath" + "slices" "testing" "time" ) @@ -401,3 +403,138 @@ func TestMetadataCacheTimesOffUTC(t *testing.T) { } }) } + +// TestRefreshMetadataCache checks that a refresh moves only fetched_at on, and +// only while the row still records the digest it was asked for. +func TestRefreshMetadataCache(t *testing.T) { + db := setupMetadataCacheDB(t) + fetched := time.Now().Add(-time.Hour).UTC().Truncate(time.Second) + entry := &MetadataCacheEntry{ + Ecosystem: testEcosystemNPM, + Name: "lodash", + StoragePath: "_metadata/npm/lodash/metadata", + ETag: sql.NullString{String: `"abc123"`, Valid: true}, + ContentDigest: sql.NullString{String: "sha256:aaaa", Valid: true}, + Size: sql.NullInt64{Int64: 1024, Valid: true}, + FetchedAt: sql.NullTime{Time: fetched, Valid: true}, + } + if err := db.UpsertMetadataCache(entry); err != nil { + t.Fatal(err) + } + + refreshed, err := db.RefreshMetadataCache(testEcosystemNPM, "lodash", "sha256:bbbb", time.Now()) + if err != nil || refreshed { + t.Fatalf("refresh with another digest = %v, %v, want false", refreshed, err) + } + if got, _ := db.GetMetadataCache(testEcosystemNPM, "lodash"); !got.FetchedAt.Time.Equal(fetched) { + t.Errorf("fetched_at = %v after a refresh with another digest, want %v", got.FetchedAt.Time, fetched) + } + + now := time.Now().Truncate(time.Second) + refreshed, err = db.RefreshMetadataCache(testEcosystemNPM, "lodash", "sha256:aaaa", now) + if err != nil || !refreshed { + t.Fatalf("refresh = %v, %v, want true", refreshed, err) + } + got, err := db.GetMetadataCache(testEcosystemNPM, "lodash") + if err != nil { + t.Fatal(err) + } + if !got.FetchedAt.Time.Equal(now) { + t.Errorf("fetched_at = %v, want %v", got.FetchedAt.Time, now) + } + if got.ETag.String != `"abc123"` || got.ContentDigest.String != "sha256:aaaa" || got.Size.Int64 != 1024 || got.StoragePath != entry.StoragePath { + t.Errorf("refresh changed the row: %+v", got) + } + + if refreshed, err := db.RefreshMetadataCache(testEcosystemNPM, "missing", "sha256:aaaa", now); err != nil || refreshed { + t.Errorf("refresh of a missing row = %v, %v, want false", refreshed, err) + } +} + +// TestExpireMetadataCache checks that expiring clears fetched_at only on the +// named rows of the ecosystem fetched before the cutoff, and keeps their +// documents and validators. +func TestExpireMetadataCache(t *testing.T) { + db := setupMetadataCacheDB(t) + cutoff := time.Now().UTC().Truncate(time.Second) + rows := []struct { + ecosystem, name string + fetched time.Time + }{ + {"composer", "acme/lib", cutoff.Add(-time.Minute)}, + {"composer", "acme/lib~dev", cutoff.Add(-time.Minute)}, + {"composer", "acme/new", cutoff.Add(time.Second)}, + {"composer", "acme/other", cutoff.Add(-time.Minute)}, + {"composer", "routes/abc/acme/lib", cutoff.Add(-time.Minute)}, + {testEcosystemNPM, "acme/lib", cutoff.Add(-time.Minute)}, + } + for _, r := range rows { + err := db.UpsertMetadataCache(&MetadataCacheEntry{ + Ecosystem: r.ecosystem, + Name: r.name, + StoragePath: "_metadata/" + r.ecosystem + "/" + r.name, + ETag: sql.NullString{String: `"abc"`, Valid: true}, + ContentDigest: sql.NullString{String: "sha256:aaaa", Valid: true}, + FetchedAt: sql.NullTime{Time: r.fetched, Valid: true}, + }) + if err != nil { + t.Fatal(err) + } + } + + expired, err := db.ExpireMetadataCache("composer", []string{"acme/lib", "acme/lib~dev", "acme/new", "acme/missing"}, cutoff) + if err != nil { + t.Fatal(err) + } + slices.Sort(expired) + if want := []string{"acme/lib", "acme/lib~dev"}; !slices.Equal(expired, want) { + t.Errorf("expired = %v, want %v", expired, want) + } + got, err := db.GetMetadataCache("composer", "acme/lib") + if err != nil { + t.Fatal(err) + } + if got.FetchedAt.Valid || got.ETag.String != `"abc"` || got.ContentDigest.String != "sha256:aaaa" { + t.Errorf("expired row = %+v, want no fetched_at and the same validators", got) + } + for _, r := range []struct{ ecosystem, name string }{{"composer", "acme/new"}, {"composer", "acme/other"}, {testEcosystemNPM, "acme/lib"}} { + if got, _ := db.GetMetadataCache(r.ecosystem, r.name); !got.FetchedAt.Valid { + t.Errorf("%s %s expired, want it left alone", r.ecosystem, r.name) + } + } + + expired, err = db.ExpireAllMetadataCache("composer", cutoff) + if err != nil { + t.Fatal(err) + } + if want := []string{"acme/other"}; !slices.Equal(expired, want) { + t.Errorf("expired all = %v, want %v (routed and newer rows kept)", expired, want) + } +} + +// TestExpireMetadataCacheBatches checks that more names than one statement +// takes are all expired. +func TestExpireMetadataCacheBatches(t *testing.T) { + db := setupMetadataCacheDB(t) + cutoff := time.Now().UTC() + names := make([]string, expireMetadataBatch+2) + for i := range names { + names[i] = fmt.Sprintf("pkg-%d", i) + } + for _, name := range []string{names[0], names[len(names)-1]} { + err := db.UpsertMetadataCache(&MetadataCacheEntry{ + Ecosystem: testEcosystemNPM, Name: name, StoragePath: "_metadata/npm/" + name, + FetchedAt: sql.NullTime{Time: cutoff.Add(-time.Minute), Valid: true}, + }) + if err != nil { + t.Fatal(err) + } + } + expired, err := db.ExpireMetadataCache(testEcosystemNPM, names, cutoff) + if err != nil { + t.Fatal(err) + } + if len(expired) != 2 { + t.Errorf("expired = %v, want both stored names", expired) + } +} diff --git a/internal/database/metadata_snapshots.go b/internal/database/metadata_snapshots.go new file mode 100644 index 0000000..268baf7 --- /dev/null +++ b/internal/database/metadata_snapshots.go @@ -0,0 +1,156 @@ +package database + +import ( + "database/sql" + "fmt" + "math" + "time" +) + +// MetadataSnapshot is one kept version of a metadata document, so a request +// for a past date can be answered with the document that was current then. +// It is valid from ValidFromMS (Unix milliseconds, the time the proxy first +// stored it) until the next snapshot of the same ecosystem and name. +type MetadataSnapshot struct { + ID int64 `db:"id"` + Ecosystem string `db:"ecosystem"` + Name string `db:"name"` + StoragePath string `db:"storage_path"` + ContentType sql.NullString `db:"content_type"` + ContentEncoding sql.NullString `db:"content_encoding"` + ContentDigest string `db:"content_digest"` + Size int64 `db:"size"` + ValidFromMS int64 `db:"valid_from_ms"` +} + +// ValidFrom returns the time the snapshot became current. +func (s *MetadataSnapshot) ValidFrom() time.Time { + return time.UnixMilli(s.ValidFromMS) +} + +const metadataSnapshotColumns = `id, ecosystem, name, storage_path, content_type, content_encoding, + content_digest, size, valid_from_ms` + +// MetadataSnapshotAt returns the snapshot of ecosystem and name that was +// current at at: the newest one that became current before it. It returns nil +// when there is none. +func (db *DB) MetadataSnapshotAt(ecosystem, name string, at time.Time) (*MetadataSnapshot, error) { + return db.metadataSnapshotBefore(ecosystem, name, at.UnixMilli()) +} + +// LatestMetadataSnapshot returns the newest snapshot of ecosystem and name, +// or nil when there is none. +func (db *DB) LatestMetadataSnapshot(ecosystem, name string) (*MetadataSnapshot, error) { + return db.metadataSnapshotBefore(ecosystem, name, math.MaxInt64) +} + +func (db *DB) metadataSnapshotBefore(ecosystem, name string, beforeMS int64) (*MetadataSnapshot, error) { + var snap MetadataSnapshot + err := db.Get(&snap, db.Rebind(`SELECT `+metadataSnapshotColumns+` + FROM metadata_snapshots + WHERE ecosystem = ? AND name = ? AND valid_from_ms < ? + ORDER BY valid_from_ms DESC, id DESC + LIMIT 1`), ecosystem, name, beforeMS) + if err == sql.ErrNoRows { + return nil, nil + } + if err != nil { + return nil, fmt.Errorf("reading metadata snapshot: %w", err) + } + return &snap, nil +} + +// AddMetadataSnapshot records snap as the version of its document current +// from snap.ValidFromMS, unless the snapshot current at that time already has +// its digest, and reports whether it did. On Postgres it first takes an +// advisory lock on the document, so two replicas can't both read the previous +// digest and both insert. The casts let Postgres type the parameters of the +// INSERT ... SELECT. +func (db *DB) AddMetadataSnapshot(snap *MetadataSnapshot) (bool, error) { + tx, err := db.Beginx() + if err != nil { + return false, fmt.Errorf("recording metadata snapshot: %w", err) + } + defer func() { _ = tx.Rollback() }() + if db.dialect == DialectPostgres { + if _, err := tx.Exec("SELECT pg_advisory_xact_lock($1)", metadataSnapshotLockKey(snap.Ecosystem, snap.Name)); err != nil { + return false, fmt.Errorf("locking metadata snapshots: %w", err) + } + } + res, err := tx.Exec(db.Rebind(` + INSERT INTO metadata_snapshots (ecosystem, name, storage_path, content_type, content_encoding, + content_digest, size, valid_from_ms) + SELECT CAST(? AS TEXT), CAST(? AS TEXT), CAST(? AS TEXT), CAST(? AS TEXT), CAST(? AS TEXT), + CAST(? AS TEXT), CAST(? AS BIGINT), CAST(? AS BIGINT) + WHERE COALESCE(( + SELECT content_digest FROM metadata_snapshots + WHERE ecosystem = ? AND name = ? AND valid_from_ms <= CAST(? AS BIGINT) + ORDER BY valid_from_ms DESC, id DESC + LIMIT 1 + ), '') <> CAST(? AS TEXT) + `), snap.Ecosystem, snap.Name, snap.StoragePath, snap.ContentType, snap.ContentEncoding, + snap.ContentDigest, snap.Size, snap.ValidFromMS, + snap.Ecosystem, snap.Name, snap.ValidFromMS, snap.ContentDigest) + if err != nil { + return false, fmt.Errorf("recording metadata snapshot: %w", err) + } + n, err := res.RowsAffected() + if err != nil { + return false, err + } + if err := tx.Commit(); err != nil { + return false, fmt.Errorf("recording metadata snapshot: %w", err) + } + return n > 0, nil +} + +// metadataSnapshotLockKey is the advisory lock AddMetadataSnapshot takes for +// a document. +func metadataSnapshotLockKey(ecosystem, name string) int64 { + return lockKey("metadata-snapshot:" + ecosystem + "\x00" + name) +} + +// PruneMetadataSnapshots deletes the snapshots of ecosystem that stopped +// being current before cutoff, that is those replaced by a newer snapshot +// that became current before cutoff, and queues their blobs for deletion. The +// newest snapshot of each document is always kept. It returns the number of +// snapshots deleted. +func (db *DB) PruneMetadataSnapshots(ecosystem string, cutoff time.Time) (int, error) { + tx, err := db.Beginx() + if err != nil { + return 0, err + } + defer func() { _ = tx.Rollback() }() + + var expired []struct { + ID int64 `db:"id"` + StoragePath string `db:"storage_path"` + } + err = tx.Select(&expired, db.Rebind(` + SELECT s.id, s.storage_path FROM metadata_snapshots s + WHERE s.ecosystem = ? + AND EXISTS ( + SELECT 1 FROM metadata_snapshots n + WHERE n.ecosystem = s.ecosystem AND n.name = s.name + AND (n.valid_from_ms > s.valid_from_ms OR (n.valid_from_ms = s.valid_from_ms AND n.id > s.id)) + AND n.valid_from_ms < ? + ) + `), ecosystem, cutoff.UnixMilli()) + if err != nil { + return 0, fmt.Errorf("listing expired metadata snapshots: %w", err) + } + + queuedAt := time.Now().UTC() + for _, row := range expired { + if _, err := tx.Exec(db.Rebind(`DELETE FROM metadata_snapshots WHERE id = ?`), row.ID); err != nil { + return 0, fmt.Errorf("deleting metadata snapshot: %w", err) + } + if _, err := tx.Exec(db.Rebind(queuePendingDeleteQuery), row.StoragePath, queuedAt); err != nil { + return 0, fmt.Errorf("queueing metadata snapshot blob: %w", err) + } + } + if err := tx.Commit(); err != nil { + return 0, err + } + return len(expired), nil +} diff --git a/internal/database/metadata_snapshots_test.go b/internal/database/metadata_snapshots_test.go new file mode 100644 index 0000000..71865b9 --- /dev/null +++ b/internal/database/metadata_snapshots_test.go @@ -0,0 +1,190 @@ +package database + +import ( + "testing" + "time" +) + +func addSnapshot(t *testing.T, db *DB, name, digest string, validFrom time.Time) bool { + t.Helper() + added, err := db.AddMetadataSnapshot(&MetadataSnapshot{ + Ecosystem: "alpine", + Name: name, + StoragePath: "_snapshots/alpine/" + name + "/" + digest, + ContentDigest: digest, + Size: 1, + ValidFromMS: validFrom.UnixMilli(), + }) + if err != nil { + t.Fatalf("AddMetadataSnapshot: %v", err) + } + return added +} + +func snapshotDigestAt(t *testing.T, db *DB, name string, at time.Time) string { + t.Helper() + snap, err := db.MetadataSnapshotAt("alpine", name, at) + if err != nil { + t.Fatalf("MetadataSnapshotAt: %v", err) + } + if snap == nil { + return "" + } + return snap.ContentDigest +} + +func TestMetadataSnapshots_AddAndLookup(t *testing.T) { + runWithBothDatabases(t, func(t *testing.T, db *DB) { + day := time.Date(2026, 3, 1, 0, 0, 0, 0, time.UTC) + if !addSnapshot(t, db, "idx", "sha256:a", day) { + t.Fatal("first snapshot not added") + } + if addSnapshot(t, db, "idx", "sha256:a", day.Add(time.Hour)) { + t.Error("unchanged digest added again") + } + if !addSnapshot(t, db, "idx", "sha256:b", day.Add(48*time.Hour)) { + t.Fatal("changed digest not added") + } + // A rollback to an earlier version is a new snapshot. + if !addSnapshot(t, db, "idx", "sha256:a", day.Add(96*time.Hour)) { + t.Fatal("rolled back digest not added") + } + + for _, tc := range []struct { + at time.Time + want string + }{ + {day, ""}, + {day.Add(time.Minute), "sha256:a"}, + {day.Add(72 * time.Hour), "sha256:b"}, + {day.Add(100 * time.Hour), "sha256:a"}, + } { + if got := snapshotDigestAt(t, db, "idx", tc.at); got != tc.want { + t.Errorf("snapshot at %s = %q, want %q", tc.at, got, tc.want) + } + } + latest, err := db.LatestMetadataSnapshot("alpine", "idx") + if err != nil || latest == nil || !latest.ValidFrom().Equal(day.Add(96*time.Hour)) { + t.Errorf("LatestMetadataSnapshot = %+v, %v", latest, err) + } + }) +} + +// TestMetadataSnapshots_RecordedLate adds a version after a newer one was +// recorded, as a request that fetched it first but recorded it last does. It +// is compared with the version current at its own time, so it keeps its place +// in the history. +func TestMetadataSnapshots_RecordedLate(t *testing.T) { + runWithBothDatabases(t, func(t *testing.T, db *DB) { + day := time.Date(2026, 3, 1, 0, 0, 0, 0, time.UTC) + addSnapshot(t, db, "idx", "sha256:a", day) + addSnapshot(t, db, "idx", "sha256:c", day.Add(2*time.Hour)) + if !addSnapshot(t, db, "idx", "sha256:b", day.Add(time.Hour)) { + t.Fatal("version recorded after a newer one not added") + } + if addSnapshot(t, db, "idx", "sha256:b", day.Add(90*time.Minute)) { + t.Error("version already current at that time added again") + } + for _, tc := range []struct { + at time.Time + want string + }{ + {day.Add(30 * time.Minute), "sha256:a"}, + {day.Add(100 * time.Minute), "sha256:b"}, + {day.Add(3 * time.Hour), "sha256:c"}, + } { + if got := snapshotDigestAt(t, db, "idx", tc.at); got != tc.want { + t.Errorf("snapshot at %s = %q, want %q", tc.at, got, tc.want) + } + } + }) +} + +func TestMetadataSnapshots_Prune(t *testing.T) { + runWithBothDatabases(t, func(t *testing.T, db *DB) { + now := time.Date(2026, 6, 1, 0, 0, 0, 0, time.UTC) + addSnapshot(t, db, "idx", "sha256:a", now.AddDate(0, 0, -100)) + addSnapshot(t, db, "idx", "sha256:b", now.AddDate(0, 0, -60)) + addSnapshot(t, db, "idx", "sha256:c", now.AddDate(0, 0, -10)) + // The only version of another index stays however old it is. + addSnapshot(t, db, "other", "sha256:x", now.AddDate(0, 0, -200)) + + pruned, err := db.PruneMetadataSnapshots("alpine", now.AddDate(0, 0, -30)) + if err != nil { + t.Fatalf("PruneMetadataSnapshots: %v", err) + } + // a was replaced 60 days ago, b only 10 days ago. + if pruned != 1 { + t.Errorf("pruned = %d, want 1", pruned) + } + if got := snapshotDigestAt(t, db, "idx", now.AddDate(0, 0, -90)); got != "" { + t.Errorf("snapshot of a pruned day = %q, want none", got) + } + if got := snapshotDigestAt(t, db, "idx", now.AddDate(0, 0, -50)); got != "sha256:b" { + t.Errorf("snapshot 50 days ago = %q, want sha256:b", got) + } + if got := snapshotDigestAt(t, db, "other", now); got != "sha256:x" { + t.Errorf("only snapshot of other = %q, want sha256:x", got) + } + + due, err := db.GetDuePendingDeletes(time.Now().Add(time.Hour), 10) + if err != nil { + t.Fatal(err) + } + if len(due) != 1 || due[0] != "_snapshots/alpine/idx/sha256:a" { + t.Errorf("queued deletes = %v, want the pruned blob", due) + } + }) +} + +// TestMetadataSnapshots_ConcurrentPostgres records a version while another +// replica's transaction has recorded the same one and not committed yet, as +// two replicas can. The second must wait and then find it, so one row +// remains. Without the lock both inserts succeed. +func TestMetadataSnapshots_ConcurrentPostgres(t *testing.T) { + db := createTestPostgresDB(t) + if db == nil { + t.Skip("PROXY_DATABASE_URL not set, skipping postgres test") + } + defer func() { _ = db.Close() }() + const name = "v3.22/main/x86_64/APKINDEX.tar.gz" + + other, err := db.Beginx() + if err != nil { + t.Fatal(err) + } + defer func() { _ = other.Rollback() }() + if _, err := other.Exec("SELECT pg_advisory_xact_lock($1)", metadataSnapshotLockKey("alpine", name)); err != nil { + t.Fatal(err) + } + if _, err := other.Exec(`INSERT INTO metadata_snapshots (ecosystem, name, storage_path, content_digest, size, valid_from_ms) + VALUES ('alpine', $1, 'other', 'sha256:a', 1, $2)`, name, time.Now().UnixMilli()); err != nil { + t.Fatal(err) + } + + done := make(chan bool, 1) + go func() { done <- addSnapshot(t, db, name, "sha256:a", time.Now()) }() + select { + case added := <-done: + t.Fatalf("recorded without waiting for the other replica (added=%v)", added) + case <-time.After(200 * time.Millisecond): + } + if err := other.Commit(); err != nil { + t.Fatal(err) + } + if added := <-done; added { + t.Error("recorded a version the other replica had just recorded") + } + var n int + if err := db.Get(&n, `SELECT COUNT(*) FROM metadata_snapshots WHERE name = $1`, name); err != nil { + t.Fatal(err) + } + if n != 1 { + t.Errorf("%d snapshot rows, want 1", n) + } + + // Going back to an earlier digest is still recorded. + if !addSnapshot(t, db, name, "sha256:b", time.Now()) || !addSnapshot(t, db, name, "sha256:a", time.Now().Add(time.Millisecond)) { + t.Error("a change back to an earlier digest was not recorded") + } +} diff --git a/internal/database/metadata_stats_test.go b/internal/database/metadata_stats_test.go new file mode 100644 index 0000000..e66e407 --- /dev/null +++ b/internal/database/metadata_stats_test.go @@ -0,0 +1,60 @@ +package database + +import ( + "database/sql" + "testing" +) + +func TestGetMetadataCacheStats(t *testing.T) { + db := newTestDB(t) + + stats, err := db.GetMetadataCacheStats() + if err != nil { + t.Fatalf("GetMetadataCacheStats on an empty cache: %v", err) + } + if len(stats) != 0 { + t.Fatalf("empty cache returned %+v, want no rows", stats) + } + + rows := []struct { + ecosystem, name string + size sql.NullInt64 + }{ + {"npm", "lodash", sql.NullInt64{Int64: 300, Valid: true}}, + {"npm", "react", sql.NullInt64{Int64: 200, Valid: true}}, + // gem and rubygems are one ecosystem and must share a row. + {"gem", "rails", sql.NullInt64{Int64: 1000, Valid: true}}, + {"rubygems", "rack", sql.NullInt64{Int64: 24, Valid: true}}, + // A row written before sizes were recorded still counts as an entry. + {"pypi", "requests", sql.NullInt64{}}, + } + for _, r := range rows { + if err := db.UpsertMetadataCache(&MetadataCacheEntry{ + Ecosystem: r.ecosystem, + Name: r.name, + StoragePath: "_metadata/" + r.ecosystem + "/" + r.name, + Size: r.size, + }); err != nil { + t.Fatalf("UpsertMetadataCache(%s/%s): %v", r.ecosystem, r.name, err) + } + } + + stats, err = db.GetMetadataCacheStats() + if err != nil { + t.Fatalf("GetMetadataCacheStats: %v", err) + } + + want := []MetadataCacheStats{ + {Ecosystem: "rubygems", Entries: 2, Size: 1024}, + {Ecosystem: "npm", Entries: 2, Size: 500}, + {Ecosystem: "pypi", Entries: 1, Size: 0}, + } + if len(stats) != len(want) { + t.Fatalf("got %+v, want %+v", stats, want) + } + for i := range want { + if stats[i] != want[i] { + t.Errorf("row %d = %+v, want %+v", i, stats[i], want[i]) + } + } +} diff --git a/internal/database/metadata_upstream_url_test.go b/internal/database/metadata_upstream_url_test.go new file mode 100644 index 0000000..361a2cc --- /dev/null +++ b/internal/database/metadata_upstream_url_test.go @@ -0,0 +1,90 @@ +package database + +import ( + "database/sql" + "path/filepath" + "reflect" + "testing" + "time" +) + +func TestMigrationAddsMetadataUpstreamURL(t *testing.T) { + dbPath := filepath.Join(t.TempDir(), "existing.db") + sqlDB, err := sql.Open("sqlite", dbPath) + if err != nil { + t.Fatalf("open: %v", err) + } + if _, err := sqlDB.Exec(schemaSQLite); err != nil { + t.Fatalf("create schema: %v", err) + } + if _, err := sqlDB.Exec(`ALTER TABLE metadata_cache DROP COLUMN upstream_url`); err != nil { + t.Fatalf("drop upstream_url column: %v", err) + } + if _, err := sqlDB.Exec(`DELETE FROM migrations WHERE name = '023_add_metadata_upstream_url'`); err != nil { + t.Fatalf("forget migration: %v", err) + } + if err := sqlDB.Close(); err != nil { + t.Fatalf("close: %v", err) + } + + db, err := Open(dbPath) + if err != nil { + t.Fatalf("Open: %v", err) + } + defer func() { _ = db.Close() }() + if err := db.MigrateSchema(); err != nil { + t.Fatalf("MigrateSchema: %v", err) + } + has, err := db.HasColumn("metadata_cache", "upstream_url") + if err != nil || !has { + t.Errorf("metadata_cache.upstream_url after migration = %v, %v", has, err) + } +} + +func upsertMetadataURL(t *testing.T, db *DB, ecosystem, name, url string) { + t.Helper() + entry := &MetadataCacheEntry{Ecosystem: ecosystem, Name: name, StoragePath: "_metadata/" + name} + if url != "" { + entry.UpstreamURL = sql.NullString{String: url, Valid: true} + } + if err := db.UpsertMetadataCache(entry); err != nil { + t.Fatal(err) + } +} + +func TestUpsertMetadataCacheKeepsUpstreamURL(t *testing.T) { + runWithBothDatabases(t, func(t *testing.T, db *DB) { + upsertMetadataURL(t, db, "apk", "k1", "https://dl-cdn.alpinelinux.org/alpine/v3.20/main/aarch64/APKINDEX.tar.gz") + // A writer that doesn't know the URL leaves it as it was. + upsertMetadataURL(t, db, "apk", "k1", "") + got, err := db.GetMetadataCache("apk", "k1") + if err != nil || got == nil { + t.Fatalf("GetMetadataCache: %+v, %v", got, err) + } + if got.UpstreamURL.String != "https://dl-cdn.alpinelinux.org/alpine/v3.20/main/aarch64/APKINDEX.tar.gz" { + t.Errorf("upstream_url = %q", got.UpstreamURL.String) + } + }) +} + +func TestRecentMetadataDocuments(t *testing.T) { + runWithBothDatabases(t, func(t *testing.T, db *DB) { + upsertMetadataURL(t, db, "apk", "k1", "https://a.test/v3.20/main/aarch64/APKINDEX.tar.gz") + upsertMetadataURL(t, db, "apk", "k2", "https://a.test/v3.19/main/aarch64/APKINDEX.tar.gz") + upsertMetadataURL(t, db, "apk", "k3", "") + upsertMetadataURL(t, db, "debian", "k4", "https://d.test/dists/bookworm/InRelease") + old := time.Now().Add(-30 * 24 * time.Hour).UTC() + if _, err := db.Exec(db.Rebind("UPDATE metadata_cache SET last_accessed_at = ?, updated_at = ? WHERE name = ?"), old, old, "k2"); err != nil { + t.Fatal(err) + } + + got, err := db.RecentMetadataDocuments("apk", time.Now().Add(-14*24*time.Hour)) + if err != nil { + t.Fatal(err) + } + want := []MetadataDocument{{Name: "k1", UpstreamURL: "https://a.test/v3.20/main/aarch64/APKINDEX.tar.gz"}} + if !reflect.DeepEqual(got, want) { + t.Errorf("RecentMetadataDocuments = %+v, want %+v", got, want) + } + }) +} diff --git a/internal/database/most_used.go b/internal/database/most_used.go new file mode 100644 index 0000000..a365cb7 --- /dev/null +++ b/internal/database/most_used.go @@ -0,0 +1,80 @@ +package database + +import ( + "time" +) + +// UsedPackage is a package clients download from the cache, with the files +// cached for it. +type UsedPackage struct { + Ecosystem string + Name string + PURL string + // Hits counts the downloads of the files downloaded since the cutoff. + Hits int64 + Files []UsedFile +} + +// UsedFile is a cached file of a UsedPackage. +type UsedFile struct { + Version string + Filename string + UpstreamURL string +} + +// MostUsedPackages returns, for each ecosystem, the top packages with the most +// downloads among the cached files downloaded since cutoff, ordered by +// ecosystem and then by hits. Each lists every file cached for it. Files +// from local sources, which have no upstream, are left out, and so are +// files a mirror run fetched that no client has downloaded since. +func (db *DB) MostUsedPackages(cutoff time.Time, top int) ([]UsedPackage, error) { + var rows []struct { + Ecosystem string `db:"ecosystem"` + Name string `db:"name"` + PURL string `db:"purl"` + Hits int64 `db:"hits"` + } + err := db.Select(&rows, db.Rebind(` + SELECT ecosystem, name, purl, hits FROM ( + SELECT p.ecosystem, p.name, p.purl, SUM(a.hit_count) AS hits, + ROW_NUMBER() OVER (PARTITION BY p.ecosystem ORDER BY SUM(a.hit_count) DESC, p.name) AS rank + FROM artifacts a + JOIN versions v ON v.purl = a.version_purl + JOIN packages p ON p.purl = v.package_purl + WHERE a.storage_path IS NOT NULL AND a.source = ? + AND (a.last_accessed_at >= ? OR (a.last_accessed_at IS NULL AND a.fetched_at >= ? + AND (a.mirrored_at IS NULL OR a.mirrored_at < a.fetched_at))) + GROUP BY p.ecosystem, p.name, p.purl + ) ranked + WHERE rank <= ? + ORDER BY ecosystem, hits DESC, name + `), SourceUpstream, cutoff.UTC(), cutoff.UTC(), top) + if err != nil { + return nil, err + } + packages := make([]UsedPackage, len(rows)) + for i, row := range rows { + packages[i] = UsedPackage{Ecosystem: row.Ecosystem, Name: row.Name, PURL: row.PURL, Hits: row.Hits} + var files []struct { + VersionPURL string `db:"version_purl"` + Filename string `db:"filename"` + UpstreamURL string `db:"upstream_url"` + } + err := db.Select(&files, db.Rebind(` + SELECT a.version_purl, a.filename, a.upstream_url + FROM artifacts a + JOIN versions v ON v.purl = a.version_purl + WHERE v.package_purl = ? AND a.storage_path IS NOT NULL AND a.source = ? + ORDER BY a.version_purl, a.filename + `), row.PURL, SourceUpstream) + if err != nil { + return nil, err + } + for _, f := range files { + packages[i].Files = append(packages[i].Files, UsedFile{ + Version: VersionFromPURL(f.VersionPURL), Filename: f.Filename, UpstreamURL: f.UpstreamURL, + }) + } + } + return packages, nil +} diff --git a/internal/database/most_used_test.go b/internal/database/most_used_test.go new file mode 100644 index 0000000..4b8693e --- /dev/null +++ b/internal/database/most_used_test.go @@ -0,0 +1,118 @@ +package database + +import ( + "reflect" + "testing" + "time" +) + +// seedUsedArtifact stores a cached artifact with hits, last downloaded at +// accessed. +func seedUsedArtifact(t *testing.T, db *DB, ecosystem, name, version, filename string, hits int64, accessed time.Time) { + t.Helper() + packagePURL := "pkg:" + ecosystem + "/" + name + versionPURL := packagePURL + "@" + version + if err := db.UpsertPackage(&Package{PURL: packagePURL, Ecosystem: ecosystem, Name: name}); err != nil { + t.Fatal(err) + } + if err := db.UpsertVersion(&Version{PURL: versionPURL, PackagePURL: packagePURL}); err != nil { + t.Fatal(err) + } + if err := db.UpsertArtifact(&Artifact{VersionPURL: versionPURL, Filename: filename, UpstreamURL: "https://example.test/" + filename}); err != nil { + t.Fatal(err) + } + if err := db.MarkArtifactCached(versionPURL, filename, ecosystem+"/"+filename, "sha256:00", 1, "application/octet-stream"); err != nil { + t.Fatal(err) + } + if _, err := db.Exec(db.Rebind("UPDATE artifacts SET hit_count = ?, last_accessed_at = ? WHERE version_purl = ? AND filename = ?"), + hits, accessed.UTC(), versionPURL, filename); err != nil { + t.Fatal(err) + } +} + +func TestMostUsedPackages(t *testing.T) { + runWithBothDatabases(t, func(t *testing.T, db *DB) { + now := time.Now() + seedUsedArtifact(t, db, "npm", "lodash", "4.17.20", "lodash-4.17.20.tgz", 5, now.Add(-time.Hour)) + seedUsedArtifact(t, db, "npm", "lodash", "4.17.21", "lodash-4.17.21.tgz", 4, now.Add(-20*24*time.Hour)) + seedUsedArtifact(t, db, "npm", "react", "18.3.1", "react-18.3.1.tgz", 10, now.Add(-time.Hour)) + seedUsedArtifact(t, db, "npm", "left-pad", "1.3.0", "left-pad-1.3.0.tgz", 100, now.Add(-30*24*time.Hour)) + seedUsedArtifact(t, db, "cargo", "serde", "1.0.200", "serde-1.0.200.crate", 1, now.Add(-time.Hour)) + + // Not cached: never counts. + if err := db.UpsertArtifact(&Artifact{VersionPURL: "pkg:npm/react@19.0.0", Filename: "react-19.0.0.tgz", UpstreamURL: "https://example.test/x"}); err != nil { + t.Fatal(err) + } + + got, err := db.MostUsedPackages(now.Add(-14*24*time.Hour), 2) + if err != nil { + t.Fatal(err) + } + want := []UsedPackage{ + {Ecosystem: "cargo", Name: "serde", PURL: "pkg:cargo/serde", Hits: 1, Files: []UsedFile{ + {Version: "1.0.200", Filename: "serde-1.0.200.crate", UpstreamURL: "https://example.test/serde-1.0.200.crate"}, + }}, + // react has more hits than lodash. Every cached file of lodash is + // listed, but only recent downloads count. + {Ecosystem: "npm", Name: "react", PURL: "pkg:npm/react", Hits: 10, Files: []UsedFile{ + {Version: "18.3.1", Filename: "react-18.3.1.tgz", UpstreamURL: "https://example.test/react-18.3.1.tgz"}, + }}, + {Ecosystem: "npm", Name: "lodash", PURL: "pkg:npm/lodash", Hits: 5, Files: []UsedFile{ + {Version: "4.17.20", Filename: "lodash-4.17.20.tgz", UpstreamURL: "https://example.test/lodash-4.17.20.tgz"}, + {Version: "4.17.21", Filename: "lodash-4.17.21.tgz", UpstreamURL: "https://example.test/lodash-4.17.21.tgz"}, + }}, + } + if !reflect.DeepEqual(got, want) { + t.Errorf("MostUsedPackages =\n%+v\nwant\n%+v", got, want) + } + + top1, err := db.MostUsedPackages(now.Add(-14*24*time.Hour), 1) + if err != nil { + t.Fatal(err) + } + if len(top1) != 2 || top1[0].Name != "serde" || top1[1].Name != "react" { + t.Errorf("top 1 per ecosystem = %+v, want serde and react", top1) + } + }) +} + +func TestMostUsedPackagesSkipsLocalArtifacts(t *testing.T) { + runWithBothDatabases(t, func(t *testing.T, db *DB) { + now := time.Now() + seedUsedArtifact(t, db, "npm", "internal-lib", "1.0.0", "internal-lib-1.0.0.tgz", 50, now) + if _, err := db.Exec(db.Rebind("UPDATE artifacts SET source = ? WHERE filename = ?"), SourceLocal, "internal-lib-1.0.0.tgz"); err != nil { + t.Fatal(err) + } + got, err := db.MostUsedPackages(now.Add(-time.Hour), 10) + if err != nil { + t.Fatal(err) + } + if len(got) != 0 { + t.Errorf("MostUsedPackages = %+v, want none: local packages have no upstream to refresh from", got) + } + }) +} + +func TestMostUsedPackagesSkipsMirroredArtifactsNotDownloaded(t *testing.T) { + runWithBothDatabases(t, func(t *testing.T, db *DB) { + now := time.Now() + seedUsedArtifact(t, db, "npm", "lodash", "4.17.21", "lodash-4.17.21.tgz", 0, now) + if _, err := db.Exec(db.Rebind("UPDATE artifacts SET last_accessed_at = NULL, mirrored_at = ?"), time.Now().UTC()); err != nil { + t.Fatal(err) + } + got, err := db.MostUsedPackages(now.Add(-time.Hour), 10) + if err != nil { + t.Fatal(err) + } + if len(got) != 0 { + t.Errorf("MostUsedPackages = %+v, want none: a mirror fetched it and no client has since", got) + } + + if err := db.RecordArtifactHit("pkg:npm/lodash@4.17.21", "lodash-4.17.21.tgz"); err != nil { + t.Fatal(err) + } + if got, err = db.MostUsedPackages(now.Add(-time.Hour), 10); err != nil || len(got) != 1 { + t.Errorf("MostUsedPackages = %+v, %v; want lodash once a client downloaded it", got, err) + } + }) +} diff --git a/internal/database/pending_deletes_test.go b/internal/database/pending_deletes_test.go index 9af6c48..f124557 100644 --- a/internal/database/pending_deletes_test.go +++ b/internal/database/pending_deletes_test.go @@ -79,7 +79,7 @@ func TestUpsertArtifactSkipsRecordThatMoved(t *testing.T) { UpstreamURL: "https://example.com/" + pendingFilename, StoragePath: sql.NullString{String: "npm/pending/1.0.0/c/pending-1.0.0.tgz", Valid: true}, } - applied, err := db.upsertArtifactFrom(late, read) + applied, err := db.upsertArtifactFrom(db, late, read) if err != nil { t.Fatalf("upsertArtifactFrom: %v", err) } @@ -91,7 +91,7 @@ func TestUpsertArtifactSkipsRecordThatMoved(t *testing.T) { } missing := &Artifact{VersionPURL: "pkg:npm/pending@2.0.0", Filename: pendingFilename, UpstreamURL: "u"} - applied, err = db.upsertArtifactFrom(missing, sql.NullString{}) + applied, err = db.upsertArtifactFrom(db, missing, sql.NullString{}) if err != nil || !applied { t.Errorf("insert of a new record: applied=%v err=%v", applied, err) } @@ -173,6 +173,46 @@ func TestDiscardArtifactClearsAndQueues(t *testing.T) { }) } +// When the replaced path can't be queued, the write is rolled back, so the +// record keeps pointing at the old object instead of orphaning it. +func TestUpsertArtifactRollsBackWhenQueueingFails(t *testing.T) { + runWithBothDatabases(t, func(t *testing.T, db *DB) { + upsertPendingArtifact(t, db, "npm/pending/1.0.0/a/pending-1.0.0.tgz") + if _, err := db.Exec(`DROP TABLE pending_deletes`); err != nil { + t.Fatalf("dropping pending_deletes: %v", err) + } + + err := db.UpsertArtifact(&Artifact{ + VersionPURL: pendingVersionPURL, + Filename: pendingFilename, + UpstreamURL: "https://example.com/" + pendingFilename, + StoragePath: sql.NullString{String: "npm/pending/1.0.0/b/pending-1.0.0.tgz", Valid: true}, + }) + if err == nil { + t.Fatal("UpsertArtifact succeeded without queueing the replaced path") + } + if got := recordedPath(t, db).String; got != "npm/pending/1.0.0/a/pending-1.0.0.tgz" { + t.Errorf("record points at %q, want the old path kept", got) + } + }) +} + +func TestDiscardArtifactRollsBackWhenQueueingFails(t *testing.T) { + runWithBothDatabases(t, func(t *testing.T, db *DB) { + upsertPendingArtifact(t, db, "npm/pending/1.0.0/a/pending-1.0.0.tgz") + if _, err := db.Exec(`DROP TABLE pending_deletes`); err != nil { + t.Fatalf("dropping pending_deletes: %v", err) + } + + if err := db.DiscardArtifact(pendingVersionPURL, pendingFilename, "npm/pending/1.0.0/a/pending-1.0.0.tgz"); err == nil { + t.Fatal("DiscardArtifact succeeded without queueing the path") + } + if got := recordedPath(t, db).String; got != "npm/pending/1.0.0/a/pending-1.0.0.tgz" { + t.Errorf("record points at %q, want it kept", got) + } + }) +} + func TestGetDuePendingDeletes(t *testing.T) { runWithBothDatabases(t, func(t *testing.T, db *DB) { for _, path := range []string{"old", "referenced"} { diff --git a/internal/database/projects.go b/internal/database/projects.go new file mode 100644 index 0000000..c14b0d6 --- /dev/null +++ b/internal/database/projects.go @@ -0,0 +1,222 @@ +package database + +import ( + "database/sql" + "errors" + "fmt" + "time" +) + +// Project is a repository that uploaded an SBOM to the project inventory. +type Project struct { + ID int64 `db:"id"` + Name string `db:"name"` + Ref sql.NullString `db:"ref"` + Branch sql.NullString `db:"branch"` + UploadedAt time.Time `db:"uploaded_at"` + // Components is the number of package versions recorded for it. + Components int64 `db:"components"` +} + +// ProjectComponent is a package version a project uses. PackagePURL is the +// unversioned package URL, as packages.purl records it. +type ProjectComponent struct { + PackagePURL string `db:"package_purl"` + Ecosystem string `db:"ecosystem"` + Name string `db:"name"` + Version string `db:"version"` +} + +// ProjectComponentInfo is a project's component together with the package +// record the proxy holds for it, if any. +type ProjectComponentInfo struct { + ProjectComponent + CachedEcosystem sql.NullString `db:"cached_ecosystem"` + CachedName sql.NullString `db:"cached_name"` + LatestVersion sql.NullString `db:"latest_version"` +} + +// ProjectUsage is a project using a version of a package. +type ProjectUsage struct { + Name string `db:"name"` + Ref sql.NullString `db:"ref"` + Branch sql.NullString `db:"branch"` + UploadedAt time.Time `db:"uploaded_at"` + Version string `db:"version"` +} + +const projectColumns = ` + SELECT pr.id, pr.name, pr.ref, pr.branch, pr.uploaded_at, + (SELECT COUNT(*) FROM project_components pc WHERE pc.project_id = pr.id) AS components` + +// SaveProject records the components of a project, replacing everything +// recorded for it before, in one transaction. Readers see either the old or +// the new set, never a mix. +func (db *DB) SaveProject(name, ref, branch string, uploadedAt time.Time, components []ProjectComponent) error { + tx, err := db.Beginx() + if err != nil { + return err + } + defer func() { _ = tx.Rollback() }() + + // The upsert locks the project row, so concurrent uploads of the same + // project and pruning take turns. + if _, err := tx.Exec(db.Rebind(` + INSERT INTO projects (name, ref, branch, uploaded_at) VALUES (?, ?, ?, ?) + ON CONFLICT(name) DO UPDATE SET ref = excluded.ref, branch = excluded.branch, uploaded_at = excluded.uploaded_at + `), name, nullString(ref), nullString(branch), uploadedAt.UTC()); err != nil { + return fmt.Errorf("recording project: %w", err) + } + var id int64 + if err := tx.Get(&id, db.Rebind(`SELECT id FROM projects WHERE name = ?`), name); err != nil { + return fmt.Errorf("reading project id: %w", err) + } + if _, err := tx.Exec(db.Rebind(`DELETE FROM project_components WHERE project_id = ?`), id); err != nil { + return fmt.Errorf("removing old components: %w", err) + } + + insert, err := tx.Preparex(db.Rebind(` + INSERT INTO project_components (project_id, package_purl, ecosystem, name, version) + VALUES (?, ?, ?, ?, ?) + ON CONFLICT(project_id, package_purl, version) DO NOTHING + `)) + if err != nil { + return err + } + defer func() { _ = insert.Close() }() + for _, c := range components { + if _, err := insert.Exec(id, c.PackagePURL, c.Ecosystem, c.Name, c.Version); err != nil { + return fmt.Errorf("recording component %s@%s: %w", c.PackagePURL, c.Version, err) + } + } + return tx.Commit() +} + +// DeleteProject removes a project and its components. It reports whether the +// project existed. +func (db *DB) DeleteProject(name string) (bool, error) { + tx, err := db.Beginx() + if err != nil { + return false, err + } + defer func() { _ = tx.Rollback() }() + + var id int64 + err = tx.Get(&id, db.Rebind(`DELETE FROM projects WHERE name = ? RETURNING id`), name) + if errors.Is(err, sql.ErrNoRows) { + return false, nil + } + if err != nil { + return false, fmt.Errorf("deleting project: %w", err) + } + if _, err := tx.Exec(db.Rebind(`DELETE FROM project_components WHERE project_id = ?`), id); err != nil { + return false, fmt.Errorf("deleting project components: %w", err) + } + return true, tx.Commit() +} + +// PruneProjects removes the projects last uploaded before cutoff, with their +// components, and returns how many it removed. A project uploaded again while +// the prune runs is kept. +func (db *DB) PruneProjects(cutoff time.Time) (int, error) { + var ids []int64 + if err := db.Select(&ids, db.Rebind(`SELECT id FROM projects WHERE uploaded_at < ?`), cutoff.UTC()); err != nil { + return 0, fmt.Errorf("listing expired projects: %w", err) + } + pruned := 0 + for _, id := range ids { + ok, err := db.pruneProject(id, cutoff) + if err != nil { + return pruned, err + } + if ok { + pruned++ + } + } + return pruned, nil +} + +func (db *DB) pruneProject(id int64, cutoff time.Time) (bool, error) { + tx, err := db.Beginx() + if err != nil { + return false, err + } + defer func() { _ = tx.Rollback() }() + + res, err := tx.Exec(db.Rebind(`DELETE FROM projects WHERE id = ? AND uploaded_at < ?`), id, cutoff.UTC()) + if err != nil { + return false, fmt.Errorf("pruning project: %w", err) + } + if n, err := res.RowsAffected(); err != nil || n == 0 { + return false, err + } + if _, err := tx.Exec(db.Rebind(`DELETE FROM project_components WHERE project_id = ?`), id); err != nil { + return false, fmt.Errorf("pruning project components: %w", err) + } + return true, tx.Commit() +} + +// ListProjects returns all projects ordered by name. +func (db *DB) ListProjects() ([]Project, error) { + projects := []Project{} + if err := db.Select(&projects, projectColumns+` FROM projects pr ORDER BY pr.name`); err != nil { + return nil, err + } + return projects, nil +} + +// GetProject returns the named project, or nil if there is none. +func (db *DB) GetProject(name string) (*Project, error) { + var p Project + err := db.Get(&p, db.Rebind(projectColumns+` FROM projects pr WHERE pr.name = ?`), name) + if errors.Is(err, sql.ErrNoRows) { + return nil, nil + } + if err != nil { + return nil, err + } + return &p, nil +} + +// GetProjectComponents returns the components of a project, ordered by +// ecosystem, name and version, with the package record the proxy holds for +// each. +func (db *DB) GetProjectComponents(projectID int64) ([]ProjectComponentInfo, error) { + components := []ProjectComponentInfo{} + err := db.Select(&components, db.Rebind(` + SELECT c.package_purl, c.ecosystem, c.name, c.version, + p.ecosystem AS cached_ecosystem, p.name AS cached_name, p.latest_version + FROM project_components c + LEFT JOIN packages p ON p.purl = c.package_purl + WHERE c.project_id = ? + ORDER BY c.ecosystem, c.name, c.version + `), projectID) + if err != nil { + return nil, err + } + return components, nil +} + +// GetProjectsUsingPackage returns the projects using a package, or only +// those using version when it is not empty, ordered by project and version. +func (db *DB) GetProjectsUsingPackage(packagePURL, version string) ([]ProjectUsage, error) { + query := ` + SELECT pr.name, pr.ref, pr.branch, pr.uploaded_at, c.version + FROM project_components c + JOIN projects pr ON pr.id = c.project_id + WHERE c.package_purl = ?` + args := []any{packagePURL} + if version != "" { + query += ` AND c.version = ?` + args = append(args, version) + } + usages := []ProjectUsage{} + if err := db.Select(&usages, db.Rebind(query+` ORDER BY pr.name, c.version`), args...); err != nil { + return nil, err + } + return usages, nil +} + +func nullString(s string) sql.NullString { + return sql.NullString{String: s, Valid: s != ""} +} diff --git a/internal/database/projects_test.go b/internal/database/projects_test.go new file mode 100644 index 0000000..27bb34c --- /dev/null +++ b/internal/database/projects_test.go @@ -0,0 +1,259 @@ +package database + +import ( + "database/sql" + "slices" + "sync" + "testing" + "time" +) + +var ( + lodash20 = ProjectComponent{PackagePURL: "pkg:npm/lodash", Ecosystem: "npm", Name: "lodash", Version: "4.17.20"} + lodash21 = ProjectComponent{PackagePURL: "pkg:npm/lodash", Ecosystem: "npm", Name: "lodash", Version: "4.17.21"} + console = ProjectComponent{PackagePURL: "pkg:composer/symfony/console", Ecosystem: "composer", Name: "symfony/console", Version: "v6.4.1"} +) + +func saveProject(t *testing.T, db *DB, name string, at time.Time, components ...ProjectComponent) { + t.Helper() + if err := db.SaveProject(name, "", "", at, components); err != nil { + t.Fatalf("SaveProject(%s): %v", name, err) + } +} + +func usageNames(usages []ProjectUsage) []string { + var names []string + for _, u := range usages { + names = append(names, u.Name+"@"+u.Version) + } + return names +} + +func TestSaveProjectReplacesComponents(t *testing.T) { + runWithBothDatabases(t, func(t *testing.T, db *DB) { + now := time.Now().UTC().Truncate(time.Second) + if err := db.SaveProject("acme/web", "abc123", "main", now, []ProjectComponent{lodash20, console, lodash20}); err != nil { + t.Fatal(err) + } + saveProject(t, db, "acme/web", now.Add(time.Minute), lodash21) + + project, err := db.GetProject("acme/web") + if err != nil || project == nil { + t.Fatalf("GetProject = %v, %v", project, err) + } + if project.Components != 1 || project.Ref.Valid || project.Branch.Valid { + t.Errorf("project = %+v, want one component and ref and branch cleared", project) + } + if !project.UploadedAt.Equal(now.Add(time.Minute)) { + t.Errorf("uploaded_at = %v, want %v", project.UploadedAt, now.Add(time.Minute)) + } + components, err := db.GetProjectComponents(project.ID) + if err != nil { + t.Fatal(err) + } + if len(components) != 1 || components[0].ProjectComponent != lodash21 { + t.Errorf("components = %+v, want only lodash 4.17.21", components) + } + + missing, err := db.GetProject("acme/other") + if err != nil || missing != nil { + t.Errorf("GetProject(missing) = %v, %v", missing, err) + } + }) +} + +func TestGetProjectsUsingPackage(t *testing.T) { + runWithBothDatabases(t, func(t *testing.T, db *DB) { + now := time.Now() + saveProject(t, db, "acme/web", now, lodash20, console) + saveProject(t, db, "acme/api", now, lodash21) + saveProject(t, db, "acme/cli", now, console) + + all, err := db.GetProjectsUsingPackage("pkg:npm/lodash", "") + if err != nil { + t.Fatal(err) + } + if got, want := usageNames(all), []string{"acme/api@4.17.21", "acme/web@4.17.20"}; !slices.Equal(got, want) { + t.Errorf("any version = %v, want %v", got, want) + } + one, err := db.GetProjectsUsingPackage("pkg:npm/lodash", "4.17.20") + if err != nil { + t.Fatal(err) + } + if got, want := usageNames(one), []string{"acme/web@4.17.20"}; !slices.Equal(got, want) { + t.Errorf("4.17.20 = %v, want %v", got, want) + } + none, err := db.GetProjectsUsingPackage("pkg:npm/lodash", "1.0.0") + if err != nil || len(none) != 0 { + t.Errorf("unused version = %v, %v", none, err) + } + }) +} + +func TestListAndDeleteProjects(t *testing.T) { + runWithBothDatabases(t, func(t *testing.T, db *DB) { + now := time.Now() + saveProject(t, db, "acme/web", now, lodash20, console) + saveProject(t, db, "acme/api", now) + + projects, err := db.ListProjects() + if err != nil { + t.Fatal(err) + } + if len(projects) != 2 || projects[0].Name != "acme/api" || projects[0].Components != 0 || projects[1].Components != 2 { + t.Fatalf("projects = %+v", projects) + } + + deleted, err := db.DeleteProject("acme/web") + if err != nil || !deleted { + t.Fatalf("DeleteProject = %v, %v", deleted, err) + } + deleted, err = db.DeleteProject("acme/web") + if err != nil || deleted { + t.Errorf("second DeleteProject = %v, %v, want false", deleted, err) + } + var rows int + if err := db.Get(&rows, `SELECT COUNT(*) FROM project_components`); err != nil { + t.Fatal(err) + } + if rows != 0 { + t.Errorf("%d component rows left after the delete", rows) + } + }) +} + +func TestPruneProjects(t *testing.T) { + runWithBothDatabases(t, func(t *testing.T, db *DB) { + now := time.Now() + saveProject(t, db, "acme/old", now.Add(-100*24*time.Hour), lodash20) + saveProject(t, db, "acme/new", now.Add(-time.Hour), lodash21) + + pruned, err := db.PruneProjects(now.Add(-90 * 24 * time.Hour)) + if err != nil { + t.Fatal(err) + } + if pruned != 1 { + t.Errorf("pruned = %d, want 1", pruned) + } + projects, err := db.ListProjects() + if err != nil { + t.Fatal(err) + } + if len(projects) != 1 || projects[0].Name != "acme/new" { + t.Errorf("projects after prune = %+v", projects) + } + usages, err := db.GetProjectsUsingPackage("pkg:npm/lodash", "") + if err != nil { + t.Fatal(err) + } + if got, want := usageNames(usages), []string{"acme/new@4.17.21"}; !slices.Equal(got, want) { + t.Errorf("usages after prune = %v, want %v", got, want) + } + }) +} + +func TestProjectComponentsJoinPackages(t *testing.T) { + runWithBothDatabases(t, func(t *testing.T, db *DB) { + if err := db.UpsertPackage(&Package{ + PURL: "pkg:npm/lodash", Ecosystem: "npm", Name: "lodash", + LatestVersion: sql.NullString{String: "4.17.21", Valid: true}, + }); err != nil { + t.Fatal(err) + } + saveProject(t, db, "acme/web", time.Now(), lodash20, console) + saveProject(t, db, "acme/api", time.Now(), lodash21) + + project, err := db.GetProject("acme/web") + if err != nil || project == nil { + t.Fatalf("GetProject = %v, %v", project, err) + } + components, err := db.GetProjectComponents(project.ID) + if err != nil { + t.Fatal(err) + } + if len(components) != 2 { + t.Fatalf("components = %+v", components) + } + // Ordered by ecosystem: composer first, which the proxy has no record of. + if components[0].CachedName.Valid { + t.Errorf("uncached component has a package record: %+v", components[0]) + } + if components[1].CachedName.String != "lodash" || components[1].LatestVersion.String != "4.17.21" { + t.Errorf("cached component = %+v", components[1]) + } + + }) +} + +func TestMigrateAddsProjects(t *testing.T) { + runWithBothDatabases(t, func(t *testing.T, db *DB) { + // A database from before the project inventory. + for _, table := range []string{"project_components", "projects"} { + if _, err := db.Exec("DROP TABLE " + table); err != nil { + t.Fatalf("dropping %s: %v", table, err) + } + } + if _, err := db.Exec(db.Rebind("DELETE FROM migrations WHERE name = ?"), "021_add_projects"); err != nil { + t.Fatalf("forgetting the migration: %v", err) + } + if err := db.MigrateSchema(); err != nil { + t.Fatalf("MigrateSchema: %v", err) + } + saveProject(t, db, "acme/web", time.Now(), lodash20) + usages, err := db.GetProjectsUsingPackage("pkg:npm/lodash", "4.17.20") + if err != nil || len(usages) != 1 { + t.Fatalf("GetProjectsUsingPackage after migration = %v, %v", usages, err) + } + }) +} + +// TestSaveProjectConcurrentUploads checks that concurrent uploads of one +// project all succeed and leave the components of exactly one of them. +func TestSaveProjectConcurrentUploads(t *testing.T) { + runWithBothDatabases(t, func(t *testing.T, db *DB) { + const uploads = 8 + sets := make([][]ProjectComponent, uploads) + for i := range sets { + for j := 0; j <= i; j++ { + sets[i] = append(sets[i], ProjectComponent{ + PackagePURL: "pkg:npm/dep" + string(rune('a'+j)), Ecosystem: "npm", + Name: "dep" + string(rune('a'+j)), Version: "1.0." + string(rune('0'+i)), + }) + } + } + now := time.Now().UTC() + errs := make(chan error, uploads) + var wg sync.WaitGroup + for i := range uploads { + wg.Go(func() { errs <- db.SaveProject("acme/web", "", "", now, sets[i]) }) + } + wg.Wait() + close(errs) + for err := range errs { + if err != nil { + t.Errorf("SaveProject: %v", err) + } + } + + project, err := db.GetProject("acme/web") + if err != nil || project == nil { + t.Fatalf("GetProject = %v, %v", project, err) + } + components, err := db.GetProjectComponents(project.ID) + if err != nil { + t.Fatal(err) + } + if len(components) == 0 || len(components) > uploads { + t.Fatalf("%d components, want those of one upload", len(components)) + } + version := components[0].Version + for _, c := range components { + if c.Version != version { + t.Fatalf("components mix uploads: %+v", components) + } + } + if want := int(version[len(version)-1]-'0') + 1; len(components) != want { + t.Errorf("%d components of the upload with version %s, want %d", len(components), version, want) + } + }) +} diff --git a/internal/database/queries.go b/internal/database/queries.go index cd7c51c..6f69317 100644 --- a/internal/database/queries.go +++ b/internal/database/queries.go @@ -4,7 +4,9 @@ import ( "database/sql" "errors" "fmt" + "slices" "sort" + "strings" "time" "github.com/git-pkgs/artifacts" @@ -52,7 +54,17 @@ func (db *DB) GetPackageByEcosystemName(ecosystem, name string) (*Package, error return &pkg, nil } +// execer runs statements on the database or inside a transaction. +type execer interface { + Exec(query string, args ...any) (sql.Result, error) + Get(dest any, query string, args ...any) error +} + func (db *DB) UpsertPackage(pkg *Package) error { + return db.upsertPackage(db, pkg) +} + +func (db *DB) upsertPackage(exec execer, pkg *Package) error { now := time.Now() var query string @@ -90,7 +102,7 @@ func (db *DB) UpsertPackage(pkg *Package) error { ` } - _, err := db.Exec(query, + _, err := exec.Exec(query, pkg.PURL, pkg.Ecosystem, pkg.Name, pkg.LatestVersion, pkg.License, pkg.Description, pkg.Homepage, pkg.RepositoryURL, pkg.RegistryURL, pkg.EnrichedAt, now, now, @@ -136,6 +148,10 @@ func (db *DB) GetVersionsByPackagePURL(packagePURL string) ([]Version, error) { } func (db *DB) UpsertVersion(v *Version) error { + return db.upsertVersion(db, v) +} + +func (db *DB) upsertVersion(exec execer, v *Version) error { now := time.Now() var query string @@ -167,9 +183,9 @@ func (db *DB) UpsertVersion(v *Version) error { ` } - _, err := db.Exec(query, + _, err := exec.Exec(query, v.PURL, v.PackagePURL, v.License, v.Integrity, - v.PublishedAt, v.Yanked, v.EnrichedAt, now, now, + inUTC(v.PublishedAt), v.Yanked, v.EnrichedAt, now, now, ) if err != nil { return fmt.Errorf("upserting version: %w", err) @@ -202,13 +218,32 @@ func (db *DB) SetVersionPublishedAt(versionPURL, packagePURL string, publishedAt ` } - _, err := db.Exec(query, versionPURL, packagePURL, publishedAt, now, now) + _, err := db.Exec(query, versionPURL, packagePURL, publishedAt.UTC(), now, now) if err != nil { return fmt.Errorf("setting version publish time: %w", err) } return nil } +// GetFetchedVersionPURLs returns the versions of a package that have an +// artifact row, cached now or evicted since. Versions without one were only +// seen in metadata. +func (db *DB) GetFetchedVersionPURLs(packagePURL string) (map[string]bool, error) { + var purls []string + query := db.Rebind(` + SELECT DISTINCT version_purl FROM artifacts + WHERE version_purl IN (SELECT purl FROM versions WHERE package_purl = ?) + `) + if err := db.Select(&purls, query, packagePURL); err != nil { + return nil, fmt.Errorf("listing fetched versions: %w", err) + } + fetched := make(map[string]bool, len(purls)) + for _, p := range purls { + fetched[p] = true + } + return fetched, nil +} + // Artifact queries func (db *DB) GetArtifact(versionPURL, filename string) (*Artifact, error) { @@ -251,6 +286,34 @@ func (db *DB) GetCachedArtifact(packagePURL, versionPURL, filename string) (*Cac return row.artifact(versionPURL, filename), nil } +// StoredContent is a stored object with a given content hash. +type StoredContent struct { + StoragePath string `db:"storage_path"` + Size int64 `db:"size"` + ContentType sql.NullString `db:"content_type"` +} + +// FindStoredContent returns a cached artifact whose content has the sha256 +// hash, under any name, or nil if none is stored. Pushed artifacts are left +// out. +func (db *DB) FindStoredContent(hash string) (*StoredContent, error) { + var found StoredContent + query := db.Rebind(` + SELECT storage_path, size, content_type FROM artifacts + WHERE content_hash = ? AND storage_path IS NOT NULL AND fetched_at IS NOT NULL + AND size IS NOT NULL AND source <> 'local' + LIMIT 1 + `) + err := db.Get(&found, query, hash) + if err == sql.ErrNoRows { + return nil, nil + } + if err != nil { + return nil, err + } + return &found, nil +} + type cachedArtifactRow struct { Ecosystem string `db:"ecosystem"` StoragePath string `db:"storage_path"` @@ -334,32 +397,87 @@ func inUTC(t sql.NullTime) sql.NullTime { } func (db *DB) UpsertArtifact(a *Artifact) error { - for range upsertArtifactAttempts { - var previous sql.NullString - query := db.Rebind(`SELECT storage_path FROM artifacts WHERE version_purl = ? AND filename = ?`) - if err := db.Get(&previous, query, a.VersionPURL, a.Filename); err != nil && !errors.Is(err, sql.ErrNoRows) { - return fmt.Errorf("reading artifact: %w", err) - } - applied, err := db.upsertArtifactFrom(a, previous) - if err != nil { - return err - } - if !applied { - continue - } - if previous.Valid && previous.String != a.StoragePath.String { - if err := db.QueuePendingDelete(previous.String); err != nil { - return fmt.Errorf("queueing replaced artifact: %w", err) - } - } - return nil - } - return errors.New("upserting artifact: record kept changing") + return db.recordArtifact(a, nil, ErrLocalArtifactExists) } -// upsertArtifactFrom writes a if the record is absent or still holds -// previous, and reports whether it did. -func (db *DB) upsertArtifactFrom(a *Artifact, previous sql.NullString) (bool, error) { +// ErrLocalArtifactExists is returned when an artifact would replace one that +// was pushed to the proxy. Pushed artifacts are only removed by deleting them. +var ErrLocalArtifactExists = errors.New("a pushed artifact already exists") + +// RecordCachedArtifact records an artifact fetched from an upstream together +// with its package and version, in one transaction. If the artifact was +// pushed in the meantime, nothing is written and ErrLocalArtifactExists is +// returned, so the push's version integrity is kept as well. +func (db *DB) RecordCachedArtifact(pkg *Package, v *Version, a *Artifact) error { + return db.recordArtifact(a, func(tx execer) error { + if err := db.upsertPackage(tx, pkg); err != nil { + return err + } + return db.upsertVersion(tx, v) + }, ErrLocalArtifactExists) +} + +// artifactSlot is what an artifact record holds before it is replaced. +type artifactSlot struct { + StoragePath sql.NullString `db:"storage_path"` + Source sql.NullString `db:"source"` +} + +// recordArtifact writes before's records and a in one transaction. A pushed +// artifact is never replaced: the transaction is rolled back and localErr +// returned. A storage path the record stops pointing at is queued for +// deletion in the same transaction, since each fetch or push stores its own +// object and nothing else would remove it. The write applies only if the +// record still holds the path read before it, so commits racing on one +// artifact each queue the path they replaced. +func (db *DB) recordArtifact(a *Artifact, before func(tx execer) error, localErr error) error { + for range upsertArtifactAttempts { + done, err := db.tryRecordArtifact(a, before, localErr) + if err != nil || done { + return err + } + } + return errors.New("recording artifact: record kept changing") +} + +func (db *DB) tryRecordArtifact(a *Artifact, before func(tx execer) error, localErr error) (bool, error) { + tx, err := db.Beginx() + if err != nil { + return false, err + } + defer func() { _ = tx.Rollback() }() + + if before != nil { + if err := before(tx); err != nil { + return false, err + } + } + + var current artifactSlot + query := db.Rebind(`SELECT storage_path, source FROM artifacts WHERE version_purl = ? AND filename = ?`) + if err := tx.Get(¤t, query, a.VersionPURL, a.Filename); err != nil && !errors.Is(err, sql.ErrNoRows) { + return false, fmt.Errorf("reading artifact: %w", err) + } + if current.Source.String == SourceLocal { + return false, localErr + } + + applied, err := db.upsertArtifactFrom(tx, a, current.StoragePath) + if err != nil || !applied { + return false, err + } + previous := current.StoragePath + if previous.Valid && previous.String != a.StoragePath.String { + if _, err := tx.Exec(db.Rebind(queuePendingDeleteQuery), previous.String, time.Now().UTC()); err != nil { + return false, fmt.Errorf("queueing replaced artifact: %w", err) + } + } + return true, tx.Commit() +} + +// upsertArtifactFrom writes a if the record is absent, or still holds +// previous and wasn't pushed, and reports whether it did. +func (db *DB) upsertArtifactFrom(exec execer, a *Artifact, previous sql.NullString) (bool, error) { now := time.Now() var query string @@ -380,6 +498,7 @@ func (db *DB) upsertArtifactFrom(a *Artifact, previous sql.NullString) (bool, er source = EXCLUDED.source, manifest = EXCLUDED.manifest WHERE artifacts.storage_path IS NOT DISTINCT FROM $15 + AND (artifacts.source IS NULL OR artifacts.source <> 'local') ` } else { query = ` @@ -398,10 +517,11 @@ func (db *DB) upsertArtifactFrom(a *Artifact, previous sql.NullString) (bool, er source = excluded.source, manifest = excluded.manifest WHERE artifacts.storage_path IS ? + AND (artifacts.source IS NULL OR artifacts.source <> 'local') ` } - res, err := db.Exec(query, + res, err := exec.Exec(query, a.VersionPURL, a.Filename, a.UpstreamURL, a.StoragePath, a.ContentHash, a.Size, a.ContentType, inUTC(a.FetchedAt), a.HitCount, inUTC(a.LastAccessedAt), now, now, a.sourceOrUpstream(), a.Manifest, previous, @@ -482,33 +602,43 @@ func (db *DB) GetCachedArtifactCount() (int64, error) { } // ClearArtifactCache marks an artifact uncached if its record still points at -// storagePath, and reports whether it did. A record a newer fetch has moved -// elsewhere is left alone, so a clear never orphans the object that fetch -// committed. +// storagePath, queues storagePath for deletion in the same transaction, and +// reports whether it did. A record a newer fetch has moved elsewhere is left +// alone, so a clear never orphans the object that fetch committed. If +// queueing fails, the record keeps its path. func (db *DB) ClearArtifactCache(versionPURL, filename, storagePath string) (bool, error) { + tx, err := db.Beginx() + if err != nil { + return false, err + } + defer func() { _ = tx.Rollback() }() + query := db.Rebind(` UPDATE artifacts SET storage_path = NULL, content_hash = NULL, size = NULL, content_type = NULL, fetched_at = NULL, updated_at = ? WHERE version_purl = ? AND filename = ? AND storage_path = ? `) - res, err := db.Exec(query, time.Now(), versionPURL, filename, storagePath) + res, err := tx.Exec(query, time.Now(), versionPURL, filename, storagePath) if err != nil { return false, err } n, err := res.RowsAffected() - return n > 0, err + if err != nil || n == 0 { + return false, err + } + if _, err := tx.Exec(db.Rebind(queuePendingDeleteQuery), storagePath, time.Now().UTC()); err != nil { + return false, fmt.Errorf("queueing %s for deletion: %w", storagePath, err) + } + return true, tx.Commit() } -// DiscardArtifact clears the record as ClearArtifactCache does and queues -// storagePath for deletion, for callers that must not delete an object another +// DiscardArtifact clears the record and queues storagePath as +// ClearArtifactCache does, for callers that must not delete an object another // request may be reading. func (db *DB) DiscardArtifact(versionPURL, filename, storagePath string) error { - cleared, err := db.ClearArtifactCache(versionPURL, filename, storagePath) - if err != nil || !cleared { - return err - } - return db.QueuePendingDelete(storagePath) + _, err := db.ClearArtifactCache(versionPURL, filename, storagePath) + return err } // QueuePendingDelete queues a storage path no record points at any more. @@ -526,13 +656,17 @@ const queuePendingDeleteQuery = ` ON CONFLICT(path) DO UPDATE SET queued_at = excluded.queued_at` // GetDuePendingDeletes returns up to limit paths queued before cutoff, oldest -// first. A path a record points at again is skipped. +// first. A path a record points at again is skipped: a metadata document is +// stored at a path fixed by its key, so one fetched again after eviction +// reuses the path queued for it. func (db *DB) GetDuePendingDeletes(cutoff time.Time, limit int) ([]string, error) { var paths []string query := db.Rebind(` SELECT path FROM pending_deletes WHERE queued_at < ? AND NOT EXISTS (SELECT 1 FROM artifacts WHERE artifacts.storage_path = pending_deletes.path) + AND NOT EXISTS (SELECT 1 FROM metadata_cache WHERE metadata_cache.storage_path = pending_deletes.path) + AND NOT EXISTS (SELECT 1 FROM metadata_snapshots WHERE metadata_snapshots.storage_path = pending_deletes.path) ORDER BY queued_at LIMIT ? `) @@ -715,12 +849,13 @@ func (db *DB) SearchPackages(query string, ecosystem string, limit int, offset i } var results []SearchResult - searchPattern := "%" + query + "%" + searchPattern := nameSearchPattern(query) var sqlQuery string var args []any if ecosystem != "" { + condition, ecosystemArgs := ecosystemFilter(ecosystem) sqlQuery = db.Rebind(` SELECT p.ecosystem, p.name, p.latest_version, p.license, COALESCE(SUM(a.hit_count), 0) as hits, @@ -729,12 +864,12 @@ func (db *DB) SearchPackages(query string, ecosystem string, limit int, offset i FROM packages p LEFT JOIN versions v ON v.package_purl = p.purl LEFT JOIN artifacts a ON a.version_purl = v.purl - WHERE p.name LIKE ? AND p.ecosystem = ? AND a.storage_path IS NOT NULL + WHERE ` + nameSearchCondition + ` AND ` + condition + ` AND a.storage_path IS NOT NULL GROUP BY p.purl, p.ecosystem, p.name, p.latest_version, p.license ORDER BY hits DESC LIMIT ? OFFSET ? `) - args = []any{searchPattern, ecosystem, limit, offset} + args = append(append([]any{searchPattern}, ecosystemArgs...), limit, offset) } else { sqlQuery = db.Rebind(` SELECT p.ecosystem, p.name, p.latest_version, p.license, @@ -744,7 +879,7 @@ func (db *DB) SearchPackages(query string, ecosystem string, limit int, offset i FROM packages p LEFT JOIN versions v ON v.package_purl = p.purl LEFT JOIN artifacts a ON a.version_purl = v.purl - WHERE p.name LIKE ? AND a.storage_path IS NOT NULL + WHERE ` + nameSearchCondition + ` AND a.storage_path IS NOT NULL GROUP BY p.purl, p.ecosystem, p.name, p.latest_version, p.license ORDER BY hits DESC LIMIT ? OFFSET ? @@ -759,6 +894,18 @@ func (db *DB) SearchPackages(query string, ecosystem string, limit int, offset i return results, nil } +// nameSearchCondition matches package names containing a search pattern +// from nameSearchPattern, ignoring case on SQLite and Postgres alike. +const nameSearchCondition = `LOWER(p.name) LIKE LOWER(?) ESCAPE '!'` + +// nameSearchPattern is the LIKE pattern for names containing query. A % +// in query is matched literally, but _ stays a single-character wildcard +// so typing_extensions still finds typing-extensions. +func nameSearchPattern(query string) string { + escaped := strings.NewReplacer("!", "!!", "%", "!%").Replace(query) + return "%" + escaped + "%" +} + func (db *DB) CountSearchResults(query string, ecosystem string) (int64, error) { hasArtifacts, err := db.HasTable("artifacts") if err != nil { @@ -768,26 +915,27 @@ func (db *DB) CountSearchResults(query string, ecosystem string) (int64, error) return 0, nil } - searchPattern := "%" + query + "%" + searchPattern := nameSearchPattern(query) var sqlQuery string var args []any if ecosystem != "" { + condition, ecosystemArgs := ecosystemFilter(ecosystem) sqlQuery = db.Rebind(` SELECT COUNT(DISTINCT p.purl) FROM packages p LEFT JOIN versions v ON v.package_purl = p.purl LEFT JOIN artifacts a ON a.version_purl = v.purl - WHERE p.name LIKE ? AND p.ecosystem = ? AND a.storage_path IS NOT NULL + WHERE ` + nameSearchCondition + ` AND ` + condition + ` AND a.storage_path IS NOT NULL `) - args = []any{searchPattern, ecosystem} + args = append([]any{searchPattern}, ecosystemArgs...) } else { sqlQuery = db.Rebind(` SELECT COUNT(DISTINCT p.purl) FROM packages p LEFT JOIN versions v ON v.package_purl = p.purl LEFT JOIN artifacts a ON a.version_purl = v.purl - WHERE p.name LIKE ? AND a.storage_path IS NOT NULL + WHERE ` + nameSearchCondition + ` AND a.storage_path IS NOT NULL `) args = []any{searchPattern} } @@ -1019,8 +1167,9 @@ func (db *DB) ListCachedPackages(ecosystem string, sortBy string, limit int, off whereClause := "WHERE a.storage_path IS NOT NULL" args := []any{} if ecosystem != "" { - whereClause += " AND p.ecosystem = ?" - args = append(args, ecosystem) + condition, ecosystemArgs := ecosystemFilter(ecosystem) + whereClause += " AND " + condition + args = append(args, ecosystemArgs...) } groupByClause := "GROUP BY p.purl, p.ecosystem, p.name, p.latest_version, p.license" @@ -1102,8 +1251,9 @@ func (db *DB) CountCachedPackages(ecosystem string) (int64, error) { whereClause := "WHERE a.storage_path IS NOT NULL" args := []any{} if ecosystem != "" { - whereClause += " AND p.ecosystem = ?" - args = append(args, ecosystem) + condition, ecosystemArgs := ecosystemFilter(ecosystem) + whereClause += " AND " + condition + args = append(args, ecosystemArgs...) } query := fmt.Sprintf(` @@ -1123,11 +1273,67 @@ func (db *DB) CountCachedPackages(ecosystem string) (int64, error) { // Metadata cache queries +// MetadataCacheStats is one ecosystem's share of the metadata cache. +type MetadataCacheStats struct { + Ecosystem string + Entries int64 + Size int64 +} + +// GetMetadataCacheStats returns the number and total size of cached metadata +// documents per ecosystem, largest first. Ecosystem names are normalized so +// aliases such as "gem" and "rubygems" share one row. Rows written before +// sizes were recorded count as entries with no size. +func (db *DB) GetMetadataCacheStats() ([]MetadataCacheStats, error) { + hasTable, err := db.HasTable("metadata_cache") + if err != nil || !hasTable { + return nil, err + } + + rows, err := db.Query(`SELECT ecosystem, COUNT(*), COALESCE(SUM(size), 0) FROM metadata_cache GROUP BY ecosystem`) + if err != nil { + return nil, err + } + defer func() { _ = rows.Close() }() + + byEcosystem := make(map[string]*MetadataCacheStats) + for rows.Next() { + var ecosystem string + var entries, size int64 + if err := rows.Scan(&ecosystem, &entries, &size); err != nil { + return nil, err + } + key := purl.NormalizeEcosystem(ecosystem) + row, ok := byEcosystem[key] + if !ok { + row = &MetadataCacheStats{Ecosystem: key} + byEcosystem[key] = row + } + row.Entries += entries + row.Size += size + } + if err := rows.Err(); err != nil { + return nil, err + } + + stats := make([]MetadataCacheStats, 0, len(byEcosystem)) + for _, row := range byEcosystem { + stats = append(stats, *row) + } + sort.Slice(stats, func(i, j int) bool { + if stats[i].Size != stats[j].Size { + return stats[i].Size > stats[j].Size + } + return stats[i].Ecosystem < stats[j].Ecosystem + }) + return stats, nil +} + func (db *DB) GetMetadataCache(ecosystem, name string) (*MetadataCacheEntry, error) { var entry MetadataCacheEntry query := db.Rebind(` SELECT id, ecosystem, name, storage_path, etag, link, content_type, content_encoding, - content_digest, size, last_modified, fetched_at, created_at, updated_at + content_digest, upstream_url, size, last_modified, fetched_at, last_accessed_at, created_at, updated_at FROM metadata_cache WHERE ecosystem = ? AND name = ? `) err := db.Get(&entry, query, ecosystem, name) @@ -1140,6 +1346,125 @@ func (db *DB) GetMetadataCache(ecosystem, name string) (*MetadataCacheEntry, err return &entry, nil } +// MetadataDocument names a cached metadata document and where it was +// fetched from. +type MetadataDocument struct { + Name string `db:"name"` + UpstreamURL string `db:"upstream_url"` +} + +// RecentMetadataDocuments returns the documents of an ecosystem cached or +// served since cutoff whose upstream URL was recorded. +func (db *DB) RecentMetadataDocuments(ecosystem string, cutoff time.Time) ([]MetadataDocument, error) { + var docs []MetadataDocument + err := db.Select(&docs, db.Rebind(` + SELECT name, upstream_url FROM metadata_cache + WHERE ecosystem = ? AND upstream_url IS NOT NULL + AND COALESCE(last_accessed_at, updated_at) >= ? + ORDER BY upstream_url, name + `), ecosystem, cutoff.UTC()) + return docs, err +} + +// RefreshMetadataCache sets fetched_at on the metadata cache row for ecosystem +// and name, provided the row still records digest, and reports whether it did. +// It is for an upstream 304, which leaves the stored document as it is. +func (db *DB) RefreshMetadataCache(ecosystem, name, digest string, fetchedAt time.Time) (bool, error) { + // fetched_at is stored in UTC, as in UpsertMetadataCache. + res, err := db.Exec(db.Rebind(` + UPDATE metadata_cache SET fetched_at = ?, updated_at = ? + WHERE ecosystem = ? AND name = ? AND content_digest = ? + `), fetchedAt.UTC(), time.Now(), ecosystem, name, digest) + if err != nil { + return false, err + } + n, err := res.RowsAffected() + return n > 0, err +} + +// SetMetadataUpstreamURL records the upstream URL of the metadata cache row +// for ecosystem and name, for rows cached before URLs were recorded. +func (db *DB) SetMetadataUpstreamURL(ecosystem, name, upstreamURL string) error { + _, err := db.Exec(db.Rebind(`UPDATE metadata_cache SET upstream_url = ? WHERE ecosystem = ? AND name = ?`), + upstreamURL, ecosystem, name) + return err +} + +// MoveMetadataCache points the metadata cache row for ecosystem and name at +// to, provided it is still at from and records digest, and reports whether +// it did. The caller has copied the document from from to to. +func (db *DB) MoveMetadataCache(ecosystem, name, from, to, digest string) (bool, error) { + res, err := db.Exec(db.Rebind(` + UPDATE metadata_cache SET storage_path = ?, updated_at = ? + WHERE ecosystem = ? AND name = ? AND storage_path = ? AND content_digest = ? + `), to, time.Now(), ecosystem, name, from, digest) + if err != nil { + return false, err + } + n, err := res.RowsAffected() + return n > 0, err +} + +// ForgetMetadataDocument points the metadata cache row for ecosystem and name +// at to, provided it is still at from, and clears what described the document +// at from: its digest, validators and fetch time. The row stays, so the next +// lookup fetches the document again rather than serving or revalidating it. +func (db *DB) ForgetMetadataDocument(ecosystem, name, from, to string) error { + _, err := db.Exec(db.Rebind(` + UPDATE metadata_cache + SET storage_path = ?, content_digest = NULL, etag = NULL, last_modified = NULL, + fetched_at = NULL, updated_at = ? + WHERE ecosystem = ? AND name = ? AND storage_path = ? + `), to, time.Now(), ecosystem, name, from) + return err +} + +// expireMetadataBatch is how many names one ExpireMetadataCache statement +// covers, well below the bind parameter limits of SQLite and Postgres. +const expireMetadataBatch = 500 + +// ExpireMetadataCache clears fetched_at on the metadata cache rows for +// ecosystem and names that were fetched before cutoff, and returns the names +// of the rows it changed. The rows keep their documents and validators, so +// the next lookup of each revalidates it upstream instead of serving it as +// fresh. It is for an upstream that reports which documents changed. +func (db *DB) ExpireMetadataCache(ecosystem string, names []string, cutoff time.Time) ([]string, error) { + var expired []string + for batch := range slices.Chunk(names, expireMetadataBatch) { + args := []any{time.Now(), ecosystem, cutoff.UTC()} + for _, name := range batch { + args = append(args, name) + } + var got []string + err := db.DB.Select(&got, db.Rebind(` + UPDATE metadata_cache SET fetched_at = NULL, updated_at = ? + WHERE ecosystem = ? AND fetched_at < ? + AND name IN (`+strings.TrimSuffix(strings.Repeat("?, ", len(batch)), ", ")+`) + RETURNING name + `), args...) + if err != nil { + return expired, err + } + expired = append(expired, got...) + } + return expired, nil +} + +// ExpireAllMetadataCache is ExpireMetadataCache for every row of ecosystem, +// except those of packages routed to another registry (named "routes/..."), +// for an upstream that can't say which of its documents changed. +func (db *DB) ExpireAllMetadataCache(ecosystem string, cutoff time.Time) ([]string, error) { + var expired []string + err := db.DB.Select(&expired, db.Rebind(` + UPDATE metadata_cache SET fetched_at = NULL, updated_at = ? + WHERE ecosystem = ? AND fetched_at < ? AND name NOT LIKE 'routes/%' + RETURNING name + `), time.Now(), ecosystem, cutoff.UTC()) + return expired, err +} + +// UpsertMetadataCache writes entry and marks it accessed now, since a +// document is stored because a request asked for it. func (db *DB) UpsertMetadataCache(entry *MetadataCacheEntry) error { now := time.Now() // fetched_at is a TIMESTAMP without zone on Postgres, and lib/pq reads it @@ -1154,8 +1479,8 @@ func (db *DB) UpsertMetadataCache(entry *MetadataCacheEntry) error { if db.dialect == DialectPostgres { query = ` INSERT INTO metadata_cache (ecosystem, name, storage_path, etag, link, content_type, content_encoding, - content_digest, size, last_modified, fetched_at, created_at, updated_at) - VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13) + content_digest, upstream_url, size, last_modified, fetched_at, last_accessed_at, created_at, updated_at) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15) ON CONFLICT(ecosystem, name) DO UPDATE SET storage_path = EXCLUDED.storage_path, etag = EXCLUDED.etag, @@ -1163,16 +1488,18 @@ func (db *DB) UpsertMetadataCache(entry *MetadataCacheEntry) error { content_type = EXCLUDED.content_type, content_encoding = EXCLUDED.content_encoding, content_digest = EXCLUDED.content_digest, + upstream_url = COALESCE(EXCLUDED.upstream_url, metadata_cache.upstream_url), size = EXCLUDED.size, last_modified = EXCLUDED.last_modified, fetched_at = EXCLUDED.fetched_at, + last_accessed_at = EXCLUDED.last_accessed_at, updated_at = EXCLUDED.updated_at ` } else { query = ` INSERT INTO metadata_cache (ecosystem, name, storage_path, etag, link, content_type, content_encoding, - content_digest, size, last_modified, fetched_at, created_at, updated_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + content_digest, upstream_url, size, last_modified, fetched_at, last_accessed_at, created_at, updated_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT(ecosystem, name) DO UPDATE SET storage_path = excluded.storage_path, etag = excluded.etag, @@ -1180,16 +1507,18 @@ func (db *DB) UpsertMetadataCache(entry *MetadataCacheEntry) error { content_type = excluded.content_type, content_encoding = excluded.content_encoding, content_digest = excluded.content_digest, + upstream_url = COALESCE(excluded.upstream_url, metadata_cache.upstream_url), size = excluded.size, last_modified = excluded.last_modified, fetched_at = excluded.fetched_at, + last_accessed_at = excluded.last_accessed_at, updated_at = excluded.updated_at ` } _, err := db.Exec(query, entry.Ecosystem, entry.Name, entry.StoragePath, entry.ETag, entry.Link, - entry.ContentType, entry.ContentEncoding, entry.ContentDigest, entry.Size, entry.LastModified, fetchedAt, now, now, + entry.ContentType, entry.ContentEncoding, entry.ContentDigest, entry.UpstreamURL, entry.Size, entry.LastModified, fetchedAt, now.UTC(), now, now, ) if err != nil { return fmt.Errorf("upserting metadata cache: %w", err) @@ -1237,15 +1566,18 @@ func (db *DB) GetEcosystemStats() ([]EcosystemStats, error) { return nil, err } - // Left joined and bucketed for the same reason as artifacts below: a version - // whose package row is missing would otherwise vanish here while still - // counting in GetCacheStats' COUNT(*), leaving the two unable to reconcile. + // Left joined for the same reason as artifacts below: a version whose + // package row is missing would otherwise vanish here while still counting + // in GetCacheStats' COUNT(*), leaving the two unable to reconcile. Such + // versions are mostly publish times cooldown stored for versions nobody + // downloaded, so they count under the type of their package PURL, and + // only a PURL that can't be parsed is unattributed. if err := db.eachCount(` - SELECT COALESCE(p.ecosystem, '`+unattributedEcosystem+`'), COUNT(*) + SELECT COALESCE(p.ecosystem, '`+orphanVersionPrefix+`' || v.package_purl), COUNT(*) FROM versions v LEFT JOIN packages p ON p.purl = v.package_purl - GROUP BY COALESCE(p.ecosystem, '`+unattributedEcosystem+`') - `, func(ecosystem string, n int64) { get(ecosystem).Versions = n }); err != nil { + GROUP BY COALESCE(p.ecosystem, '`+orphanVersionPrefix+`' || v.package_purl) + `, func(key string, n int64) { get(versionEcosystem(key)).Versions += n }); err != nil { return nil, err } @@ -1328,6 +1660,26 @@ func mergeAliasedEcosystems(stats []EcosystemStats) []EcosystemStats { // Grafana. Bucketing them keeps the two reconcilable. const unattributedEcosystem = "unattributed" +// orphanVersionPrefix marks the package PURL of a version without a package +// row in GetEcosystemStats. No ecosystem name starts with it. +const orphanVersionPrefix = "~" + +// versionEcosystem returns the ecosystem a GetEcosystemStats version count +// is for: the package row's, or the type of the package PURL of a version +// without one. The ecosystems that store publish times are named like their +// PURL types. +func versionEcosystem(key string) string { + packagePURL, orphan := strings.CutPrefix(key, orphanVersionPrefix) + if !orphan { + return key + } + p, err := purl.Parse(packagePURL) + if err != nil { + return unattributedEcosystem + } + return p.Type +} + func (db *DB) eachArtifactStat(get func(string) *EcosystemStats) error { rows, err := db.Query(` SELECT COALESCE(p.ecosystem, '` + unattributedEcosystem + `'), diff --git a/internal/database/queries_packages_list_test.go b/internal/database/queries_packages_list_test.go index e30d364..5eaa402 100644 --- a/internal/database/queries_packages_list_test.go +++ b/internal/database/queries_packages_list_test.go @@ -3,6 +3,7 @@ package database import ( "database/sql" "maps" + "slices" "testing" "time" ) @@ -218,3 +219,76 @@ func TestListCachedPackages(t *testing.T) { } }) } + +// git-pkgs, and proxy mirror before it used the handler names, wrote +// "rubygems" where the gem handler writes "gem". Filtering by either name +// finds both. +func TestCachedPackageFiltersMatchEcosystemAliases(t *testing.T) { + runWithBothDatabases(t, func(t *testing.T, db *DB) { + seedArtifact(t, db, "rubygems", "rake", "13.2.1", 100, 1) + seedArtifact(t, db, "gem", "rails", "8.0.0", 100, 1) + seedArtifact(t, db, "npm", "express", "1.0.0", 100, 1) + + for _, ecosystem := range []string{"gem", "rubygems"} { + listed, err := db.ListCachedPackages(ecosystem, "name", 50, 0) + if err != nil { + t.Fatal(err) + } + var names []string + for _, p := range listed { + names = append(names, p.Name) + } + if len(names) != 2 || names[0] != "rails" || names[1] != "rake" { + t.Errorf("ListCachedPackages(%q) = %v, want rails and rake", ecosystem, names) + } + if count, err := db.CountCachedPackages(ecosystem); err != nil || count != 2 { + t.Errorf("CountCachedPackages(%q) = %d, %v, want 2", ecosystem, count, err) + } + found, err := db.SearchPackages("ra", ecosystem, 50, 0) + if err != nil || len(found) != 2 { + t.Errorf("SearchPackages(ra, %q) = %d results, %v, want 2", ecosystem, len(found), err) + } + } + }) +} + +func TestSearchPackagesIgnoresCaseAndEscapesPercent(t *testing.T) { + runWithBothDatabases(t, func(t *testing.T, db *DB) { + seedArtifact(t, db, "pypi", "Django", "5.0.0", 100, 1) + seedArtifact(t, db, "pypi", "typing-extensions", "4.12.0", 100, 1) + seedArtifact(t, db, "npm", "my_pkg", "1.0.0", 100, 1) + seedArtifact(t, db, "npm", "100%-done", "1.0.0", 100, 1) + seedArtifact(t, db, "npm", "1000-done", "1.0.0", 100, 1) + seedArtifact(t, db, "npm", `back\slash`, "1.0.0", 100, 1) + + for _, tc := range []struct { + query string + want []string + }{ + {"django", []string{"Django"}}, + {"DJANGO", []string{"Django"}}, + {"my_pkg", []string{"my_pkg"}}, + // _ stays a single-character wildcard, so it matches - too. + {"typing_extensions", []string{"typing-extensions"}}, + {"typing-extensions", []string{"typing-extensions"}}, + {"100%", []string{"100%-done"}}, + {`k\s`, []string{`back\slash`}}, + } { + found, err := db.SearchPackages(tc.query, "", 50, 0) + if err != nil { + t.Fatalf("SearchPackages(%q): %v", tc.query, err) + } + var names []string + for _, p := range found { + names = append(names, p.Name) + } + if !slices.Equal(names, tc.want) { + t.Errorf("SearchPackages(%q) = %v, want %v", tc.query, names, tc.want) + } + count, err := db.CountSearchResults(tc.query, "") + if err != nil || count != int64(len(tc.want)) { + t.Errorf("CountSearchResults(%q) = %d, %v, want %d", tc.query, count, err, len(tc.want)) + } + } + }) +} diff --git a/internal/database/read_pool_bench_test.go b/internal/database/read_pool_bench_test.go new file mode 100644 index 0000000..bae4cc5 --- /dev/null +++ b/internal/database/read_pool_bench_test.go @@ -0,0 +1,157 @@ +package database + +import ( + "fmt" + "path/filepath" + "sync" + "sync/atomic" + "testing" + "time" +) + +// benchArtifacts is the artifact count the read pool benchmarks seed: about +// what a busy cache holds, and enough for the stats queries to take a while. +const ( + benchPackages = 30_000 + benchVersions = 100_000 + benchArtifacts = 300_000 +) + +// seedBenchDB creates a database at path with benchArtifacts artifacts +// spread over three ecosystems, written in one statement per table. +func seedBenchDB(b *testing.B, path string) { + b.Helper() + db, err := Create(path) + if err != nil { + b.Fatalf("Create: %v", err) + } + defer func() { _ = db.Close() }() + stmts := []string{ + fmt.Sprintf(`WITH RECURSIVE n(i) AS (SELECT 0 UNION ALL SELECT i+1 FROM n WHERE i+1 < %d) + INSERT INTO packages (purl, ecosystem, name, created_at, updated_at) + SELECT 'pkg:' || e || '/p' || i, e, 'p' || i, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP + FROM (SELECT i, CASE i %% 3 WHEN 0 THEN 'npm' WHEN 1 THEN 'pypi' ELSE 'cargo' END AS e FROM n)`, benchPackages), + fmt.Sprintf(`WITH RECURSIVE n(i) AS (SELECT 0 UNION ALL SELECT i+1 FROM n WHERE i+1 < %d) + INSERT INTO versions (purl, package_purl, integrity, created_at, updated_at) + SELECT p.purl || '@' || n.i, p.purl, 'sha256-x', CURRENT_TIMESTAMP, CURRENT_TIMESTAMP + FROM n JOIN packages p ON p.id = (n.i %% %d) + 1`, benchVersions, benchPackages), + fmt.Sprintf(`WITH RECURSIVE n(i) AS (SELECT 0 UNION ALL SELECT i+1 FROM n WHERE i+1 < %d) + INSERT INTO artifacts (version_purl, filename, upstream_url, storage_path, content_hash, size, + content_type, fetched_at, hit_count, last_accessed_at, created_at, updated_at) + SELECT v.purl, 'f' || n.i, 'https://example.org/' || n.i, 'blobs/' || n.i, 'h', 1000 + n.i, + 'application/octet-stream', CURRENT_TIMESTAMP, n.i %% 7, CURRENT_TIMESTAMP, + CURRENT_TIMESTAMP, CURRENT_TIMESTAMP + FROM n JOIN versions v ON v.id = (n.i %% %d) + 1`, benchArtifacts, benchVersions), + } + for _, s := range stmts { + if _, err := db.Exec(s); err != nil { + b.Fatalf("seeding: %v", err) + } + } +} + +// openBenchDB opens path. With oneConn it routes reads to the writer, as +// before the read pool existed. +func openBenchDB(b *testing.B, path string, oneConn bool) *DB { + b.Helper() + db, err := Open(path) + if err != nil { + b.Fatalf("Open: %v", err) + } + if oneConn { + _ = db.reader.Close() + db.reader = db.DB + } + b.Cleanup(func() { _ = db.Close() }) + return db +} + +// benchKey returns the lookup arguments for artifact i, as seeded above. +func benchKey(i int) (pkgPURL, versionPURL, filename string) { + v := i % benchVersions + p := v % benchPackages + eco := [...]string{"npm", "pypi", "cargo"}[p%3] + pkgPURL = fmt.Sprintf("pkg:%s/p%d", eco, p) + return pkgPURL, fmt.Sprintf("%s@%d", pkgPURL, v), fmt.Sprintf("f%d", i) +} + +func lookup(b *testing.B, db *DB, i int) { + pkgPURL, versionPURL, filename := benchKey(i % benchArtifacts) + art, err := db.GetCachedArtifact(pkgPURL, versionPURL, filename) + if err != nil || art == nil { + b.Fatalf("GetCachedArtifact(%s, %s) = %v, %v", versionPURL, filename, art, err) + } +} + +var poolModes = []struct { + name string + oneConn bool +}{ + {"one-connection", true}, + {"read-pool", false}, +} + +// BenchmarkSQLiteParallelLookups runs GetCachedArtifact from parallel +// goroutines, as concurrent downloads do. +func BenchmarkSQLiteParallelLookups(b *testing.B) { + path := filepath.Join(b.TempDir(), "bench.db") + seedBenchDB(b, path) + for _, mode := range poolModes { + b.Run(mode.name, func(b *testing.B) { + db := openBenchDB(b, path, mode.oneConn) + var next atomic.Int64 + b.ResetTimer() + b.RunParallel(func(pb *testing.PB) { + for pb.Next() { + lookup(b, db, int(next.Add(7919))) + } + }) + }) + } +} + +// BenchmarkSQLiteLookupDuringStats runs GetCachedArtifact one at a time +// while another goroutine keeps running GetEcosystemStats and GetCacheStats, +// as the metrics updater and the dashboard do. It reports the slowest lookup. +func BenchmarkSQLiteLookupDuringStats(b *testing.B) { + path := filepath.Join(b.TempDir(), "bench.db") + seedBenchDB(b, path) + for _, mode := range poolModes { + b.Run(mode.name, func(b *testing.B) { + db := openBenchDB(b, path, mode.oneConn) + stop := make(chan struct{}) + var wg sync.WaitGroup + wg.Add(1) + go func() { + defer wg.Done() + for { + select { + case <-stop: + return + default: + } + if _, err := db.GetEcosystemStats(); err != nil { + b.Errorf("GetEcosystemStats: %v", err) + return + } + if _, err := db.GetCacheStats(); err != nil { + b.Errorf("GetCacheStats: %v", err) + return + } + } + }() + + var slowest time.Duration + b.ResetTimer() + for i := range b.N { + start := time.Now() + lookup(b, db, i*7919) + slowest = max(slowest, time.Since(start)) + } + b.StopTimer() + close(stop) + wg.Wait() + b.ReportMetric(float64(slowest.Microseconds())/1000, "max-ms") + }) + } +} diff --git a/internal/database/read_pool_test.go b/internal/database/read_pool_test.go new file mode 100644 index 0000000..20436e1 --- /dev/null +++ b/internal/database/read_pool_test.go @@ -0,0 +1,393 @@ +package database + +import ( + "context" + "database/sql" + "errors" + "fmt" + "os" + "path/filepath" + "strings" + "sync" + "testing" + "time" +) + +func seedOnePackage(t *testing.T, db *DB) { + t.Helper() + pkg := &Package{PURL: "pkg:npm/left-pad", Ecosystem: "npm", Name: "left-pad"} + ver := &Version{PURL: "pkg:npm/left-pad@1.3.0", PackagePURL: pkg.PURL} + art := &Artifact{ + VersionPURL: ver.PURL, + Filename: "left-pad-1.3.0.tgz", + UpstreamURL: "https://registry.npmjs.org/left-pad/-/left-pad-1.3.0.tgz", + StoragePath: sql.NullString{String: "npm/left-pad/1.3.0/left-pad-1.3.0.tgz", Valid: true}, + Size: sql.NullInt64{Int64: 10, Valid: true}, + FetchedAt: sql.NullTime{Time: time.Now(), Valid: true}, + } + if err := db.RecordCachedArtifact(pkg, ver, art); err != nil { + t.Fatalf("RecordCachedArtifact: %v", err) + } +} + +func TestSQLiteUsesSeparateReadPool(t *testing.T) { + db := newTestDB(t) + if db.reader == db.DB { + t.Fatal("file database shares one pool for reads and writes") + } + if got, want := db.reader.Stats().MaxOpenConnections, sqliteReaderConns(); got != want { + t.Errorf("reader MaxOpenConnections = %d, want %d", got, want) + } + if got := db.DB.Stats().MaxOpenConnections; got != 1 { + t.Errorf("writer MaxOpenConnections = %d, want 1", got) + } +} + +func TestSQLiteReadPoolRejectsWrites(t *testing.T) { + db := newTestDB(t) + + if _, err := db.reader.Exec(`INSERT INTO pending_deletes (path, queued_at) VALUES ('x', CURRENT_TIMESTAMP)`); err == nil { + t.Fatal("write on the reader pool succeeded") + } else if !strings.Contains(err.Error(), "readonly") { + t.Fatalf("write on the reader pool failed with %v, want a read-only error", err) + } + + // Get goes to the reader, so a write sent through it must fail too + // rather than run. + var path string + err := db.Get(&path, `INSERT INTO pending_deletes (path, queued_at) VALUES ('y', CURRENT_TIMESTAMP) RETURNING path`) + if err == nil { + t.Fatal("INSERT ... RETURNING through Get succeeded") + } + + var n int + if err := db.Get(&n, `SELECT COUNT(*) FROM pending_deletes`); err != nil { + t.Fatalf("count: %v", err) + } + if n != 0 { + t.Fatalf("pending_deletes has %d rows after rejected writes, want 0", n) + } +} + +// pragmaInt reads an integer pragma on conn. +func pragmaInt(t *testing.T, conn *sql.Conn, name string) int { + t.Helper() + var v int + if err := conn.QueryRowContext(context.Background(), "PRAGMA "+name).Scan(&v); err != nil { + t.Fatalf("PRAGMA %s: %v", name, err) + } + return v +} + +func pragmaString(t *testing.T, conn *sql.Conn, name string) string { + t.Helper() + var v string + if err := conn.QueryRowContext(context.Background(), "PRAGMA "+name).Scan(&v); err != nil { + t.Fatalf("PRAGMA %s: %v", name, err) + } + return v +} + +// TestSQLitePragmasOnEveryConnection holds every connection of both pools at +// once, so each one is a separate SQLite connection, and checks that each +// got the settings from the DSN. +func TestSQLitePragmasOnEveryConnection(t *testing.T) { + db := newTestDB(t) + ctx := context.Background() + + writer, err := db.Conn(ctx) + if err != nil { + t.Fatalf("writer conn: %v", err) + } + defer func() { _ = writer.Close() }() + if got := pragmaInt(t, writer, "busy_timeout"); got != 5000 { + t.Errorf("writer busy_timeout = %d, want 5000", got) + } + if got := pragmaString(t, writer, "journal_mode"); got != "wal" { + t.Errorf("writer journal_mode = %q, want wal", got) + } + if got := pragmaInt(t, writer, "synchronous"); got != 1 { + t.Errorf("writer synchronous = %d, want 1 (NORMAL)", got) + } + if got := pragmaInt(t, writer, "query_only"); got != 0 { + t.Errorf("writer query_only = %d, want 0", got) + } + + n := sqliteReaderConns() + conns := make([]*sql.Conn, 0, n) + defer func() { + for _, c := range conns { + _ = c.Close() + } + }() + for i := range n { + c, err := db.reader.Conn(ctx) + if err != nil { + t.Fatalf("reader conn %d: %v", i, err) + } + conns = append(conns, c) + if got := pragmaInt(t, c, "busy_timeout"); got != 5000 { + t.Errorf("reader %d busy_timeout = %d, want 5000", i, got) + } + if got := pragmaString(t, c, "journal_mode"); got != "wal" { + t.Errorf("reader %d journal_mode = %q, want wal", i, got) + } + if got := pragmaInt(t, c, "query_only"); got != 1 { + t.Errorf("reader %d query_only = %d, want 1", i, got) + } + } + if got := db.reader.Stats().OpenConnections; got != n { + t.Errorf("reader pool has %d open connections, want %d", got, n) + } +} + +// TestSQLiteReadNotBlockedBySlowRead holds one reader connection in an open +// read, as a long stats scan does, and a write transaction on the writer. +// A lookup must still complete, and must not see the uncommitted write. +func TestSQLiteReadNotBlockedBySlowRead(t *testing.T) { + db := newTestDB(t) + seedOnePackage(t, db) + + rows, err := db.Query(`SELECT purl FROM packages`) + if err != nil { + t.Fatalf("Query: %v", err) + } + defer func() { _ = rows.Close() }() + if !rows.Next() { + t.Fatal("no package row") + } + + // Bounded, so with a single shared connection the test fails instead + // of waiting forever for the connection the open read holds. + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + tx, err := db.BeginTxx(ctx, nil) + if err != nil { + t.Fatalf("BeginTxx while a read is open: %v", err) + } + defer func() { _ = tx.Rollback() }() + if _, err := tx.Exec(`INSERT INTO pending_deletes (path, queued_at) VALUES ('uncommitted', CURRENT_TIMESTAMP)`); err != nil { + t.Fatalf("insert in tx: %v", err) + } + + type result struct { + art *CachedArtifact + pending int + err error + } + done := make(chan result, 1) + go func() { + var r result + r.art, r.err = db.GetCachedArtifact("pkg:npm/left-pad", "pkg:npm/left-pad@1.3.0", "left-pad-1.3.0.tgz") + if r.err == nil { + r.err = db.GetContext(ctx, &r.pending, `SELECT COUNT(*) FROM pending_deletes`) + } + done <- r + }() + + select { + case r := <-done: + if r.err != nil { + t.Fatalf("lookup: %v", r.err) + } + if r.art == nil { + t.Fatal("lookup found no artifact") + } + if r.pending != 0 { + t.Errorf("reader saw %d uncommitted pending deletes, want 0", r.pending) + } + case <-time.After(5 * time.Second): + t.Fatal("lookup blocked behind an open read and a write transaction") + } + + if err := tx.Commit(); err != nil { + t.Fatalf("Commit: %v", err) + } + var pending int + if err := db.Get(&pending, `SELECT COUNT(*) FROM pending_deletes`); err != nil { + t.Fatalf("count after commit: %v", err) + } + if pending != 1 { + t.Errorf("reader saw %d pending deletes after commit, want 1", pending) + } +} + +// TestSQLiteReadAfterWrite checks that a read right after a write, on the +// other pool, sees it. +func TestSQLiteReadAfterWrite(t *testing.T) { + db := newTestDB(t) + for i := range 50 { + path := fmt.Sprintf("npm/p/%d.tgz", i) + if err := db.QueuePendingDelete(path); err != nil { + t.Fatalf("QueuePendingDelete: %v", err) + } + var n int + if err := db.Get(&n, db.Rebind(`SELECT COUNT(*) FROM pending_deletes WHERE path = ?`), path); err != nil { + t.Fatalf("count: %v", err) + } + if n != 1 { + t.Fatalf("write %d not visible to the reader", i) + } + } +} + +func TestSQLiteMemoryDatabaseSharesOneConnection(t *testing.T) { + db, err := Open(":memory:") + if err != nil { + t.Fatalf("Open: %v", err) + } + defer func() { _ = db.Close() }() + if db.reader != db.DB { + t.Fatal("in-memory database got a separate reader pool") + } + if err := db.CreateSchema(); err != nil { + t.Fatalf("CreateSchema: %v", err) + } + seedOnePackage(t, db) + art, err := db.GetCachedArtifact("pkg:npm/left-pad", "pkg:npm/left-pad@1.3.0", "left-pad-1.3.0.tgz") + if err != nil || art == nil { + t.Fatalf("GetCachedArtifact = %v, %v", art, err) + } +} + +func TestSQLiteCloseClosesBothPools(t *testing.T) { + db, err := Create(filepath.Join(t.TempDir(), "close.db")) + if err != nil { + t.Fatalf("Create: %v", err) + } + reader := db.reader + if err := db.Close(); err != nil { + t.Fatalf("Close: %v", err) + } + if err := reader.Ping(); err == nil { + t.Fatal("reader pool still open after Close") + } + if err := db.Ping(); err == nil { + t.Fatal("writer pool still open after Close") + } +} + +func TestPostgresSharesOnePool(t *testing.T) { + url := os.Getenv("PROXY_DATABASE_URL") + if url == "" { + t.Skip("PROXY_DATABASE_URL not set, skipping postgres test") + } + db, err := OpenPostgres(url) + if err != nil { + t.Fatalf("OpenPostgres: %v", err) + } + defer func() { _ = db.Close() }() + if db.reader != db.DB { + t.Fatal("postgres got a separate reader pool") + } +} + +func TestIsMemoryPath(t *testing.T) { + for path, want := range map[string]bool{ + "": true, + ":memory:": true, + "file::memory:": true, + "file::memory:?cache=shared": true, + "file:cache?mode=memory": true, + "/var/lib/proxy/cache.db": false, + "cache.db": false, + } { + if got := isMemoryPath(path); got != want { + t.Errorf("isMemoryPath(%q) = %v, want %v", path, got, want) + } + } +} + +// TestSQLiteExistingRollbackJournalDatabase opens a database file left in +// rollback-journal mode, as an older or foreign tool may leave it. The +// writer must switch it to WAL before readers open it, or reads would block +// on writes. +func TestSQLiteExistingRollbackJournalDatabase(t *testing.T) { + path := filepath.Join(t.TempDir(), "old.db") + db, err := Create(path) + if err != nil { + t.Fatalf("Create: %v", err) + } + seedOnePackage(t, db) + if _, err := db.Exec("PRAGMA journal_mode = DELETE"); err != nil { + t.Fatalf("leaving WAL: %v", err) + } + if err := db.Close(); err != nil { + t.Fatalf("Close: %v", err) + } + + db, err = Open(path) + if err != nil { + t.Fatalf("Open: %v", err) + } + defer func() { _ = db.Close() }() + var mode string + if err := db.reader.Get(&mode, "PRAGMA journal_mode"); err != nil || mode != "wal" { + t.Fatalf("reader journal_mode = %q, %v; want wal", mode, err) + } + art, err := db.GetCachedArtifact("pkg:npm/left-pad", "pkg:npm/left-pad@1.3.0", "left-pad-1.3.0.tgz") + if err != nil || art == nil { + t.Fatalf("GetCachedArtifact = %v, %v", art, err) + } +} + +// TestSQLiteConcurrentReadsAndWrites runs the writes a busy proxy makes +// (recording artifacts and hits) alongside request lookups and stats scans. +// None may fail with a busy, locked or read-only error. +func TestSQLiteConcurrentReadsAndWrites(t *testing.T) { + db := newTestDB(t) + seedOnePackage(t, db) + deadline := time.Now().Add(time.Second) + errs := make(chan error, 64) + var wg sync.WaitGroup + run := func(f func(i int) error) { + wg.Add(1) + go func() { + defer wg.Done() + for i := 0; time.Now().Before(deadline); i++ { + if err := f(i); err != nil { + errs <- err + return + } + } + }() + } + for w := range 2 { + run(func(i int) error { + name := fmt.Sprintf("pkg-%d-%d", w, i) + pkg := &Package{PURL: "pkg:npm/" + name, Ecosystem: "npm", Name: name} + ver := &Version{PURL: pkg.PURL + "@1.0.0", PackagePURL: pkg.PURL} + art := &Artifact{ + VersionPURL: ver.PURL, + Filename: name + ".tgz", + UpstreamURL: "https://registry.npmjs.org/" + name, + StoragePath: sql.NullString{String: "npm/" + name, Valid: true}, + Size: sql.NullInt64{Int64: 10, Valid: true}, + FetchedAt: sql.NullTime{Time: time.Now(), Valid: true}, + } + return db.RecordCachedArtifact(pkg, ver, art) + }) + } + run(func(int) error { return db.RecordArtifactHit("pkg:npm/left-pad@1.3.0", "left-pad-1.3.0.tgz") }) + for range 4 { + run(func(int) error { + art, err := db.GetCachedArtifact("pkg:npm/left-pad", "pkg:npm/left-pad@1.3.0", "left-pad-1.3.0.tgz") + if err == nil && art == nil { + err = errors.New("seeded artifact not found") + } + return err + }) + } + run(func(int) error { + if _, err := db.GetCacheStats(); err != nil { + return err + } + _, err := db.GetEcosystemStats() + return err + }) + wg.Wait() + close(errs) + for err := range errs { + t.Error(err) + } +} diff --git a/internal/database/rekey_artifact.go b/internal/database/rekey_artifact.go new file mode 100644 index 0000000..68a8dbd --- /dev/null +++ b/internal/database/rekey_artifact.go @@ -0,0 +1,40 @@ +package database + +import ( + "fmt" + "time" +) + +// RekeyCachedArtifact moves one unchanged upstream record without replacing +// an existing destination. Access history and stored bytes are preserved. +func (db *DB) RekeyCachedArtifact(old *Artifact, pkg *Package, version *Version) (bool, error) { + tx, err := db.Beginx() + if err != nil { + return false, err + } + defer func() { _ = tx.Rollback() }() + now := time.Now() + _, err = tx.Exec(db.Rebind(`INSERT INTO packages (purl, ecosystem, name, created_at, updated_at) + VALUES (?, ?, ?, ?, ?) ON CONFLICT(purl) DO NOTHING`), pkg.PURL, pkg.Ecosystem, pkg.Name, now, now) + if err != nil { + return false, fmt.Errorf("creating artifact package: %w", err) + } + _, err = tx.Exec(db.Rebind(`INSERT INTO versions (purl, package_purl, created_at, updated_at) + VALUES (?, ?, ?, ?) ON CONFLICT(purl) DO NOTHING`), version.PURL, version.PackagePURL, now, now) + if err != nil { + return false, fmt.Errorf("creating artifact version: %w", err) + } + result, err := tx.Exec(db.Rebind(`UPDATE artifacts SET version_purl = ?, updated_at = ? + WHERE id = ? AND version_purl = ? AND storage_path = ? AND upstream_url = ? AND source = ? + AND NOT EXISTS (SELECT 1 FROM artifacts WHERE version_purl = ? AND filename = ?)`), + version.PURL, now, old.ID, old.VersionPURL, old.StoragePath, old.UpstreamURL, SourceUpstream, + version.PURL, old.Filename) + if err != nil { + return false, fmt.Errorf("moving cached artifact: %w", err) + } + count, err := result.RowsAffected() + if err != nil || count == 0 { + return false, err + } + return true, tx.Commit() +} diff --git a/internal/database/rekey_artifact_test.go b/internal/database/rekey_artifact_test.go new file mode 100644 index 0000000..d5fd270 --- /dev/null +++ b/internal/database/rekey_artifact_test.go @@ -0,0 +1,69 @@ +package database + +import ( + "database/sql" + "testing" +) + +func TestRekeyCachedArtifact(t *testing.T) { + runWithBothDatabases(t, func(t *testing.T, db *DB) { + for _, scenario := range []string{"move", "destination exists", "source changed", "local source"} { + t.Run(scenario, func(t *testing.T) { + oldPackage := &Package{PURL: "pkg:golang/example.com/old", Ecosystem: "golang", Name: "example.com/Old"} + oldVersion := &Version{PURL: oldPackage.PURL + "@v1.0.0", PackagePURL: oldPackage.PURL} + old := &Artifact{VersionPURL: oldVersion.PURL, Filename: scenario + ".zip", + UpstreamURL: "https://proxy.example/example.com/!old/@v/v1.0.0.zip", + StoragePath: sql.NullString{String: scenario + "/old.zip", Valid: true}} + if err := db.RecordCachedArtifact(oldPackage, oldVersion, old); err != nil { + t.Fatal(err) + } + old, err := db.GetArtifact(oldVersion.PURL, old.Filename) + if err != nil || old == nil { + t.Fatalf("source artifact = %+v, %v", old, err) + } + pkg := &Package{PURL: "pkg:golang/example.com/Old", Ecosystem: "golang", Name: "example.com/Old"} + version := &Version{PURL: pkg.PURL + "@v1.0.0", PackagePURL: pkg.PURL} + prepareRekeyConflict(t, db, scenario, old, pkg, version) + moved, err := db.RekeyCachedArtifact(old, pkg, version) + if err != nil || moved != (scenario == "move") { + t.Fatalf("RekeyCachedArtifact = %v, %v", moved, err) + } + checkRekeyResult(t, db, scenario, old, version) + }) + } + }) +} + +func checkRekeyResult(t *testing.T, db *DB, scenario string, old *Artifact, version *Version) { + t.Helper() + current, err := db.GetArtifact(version.PURL, old.Filename) + if err != nil { + t.Fatal(err) + } + if scenario == "move" && (current == nil || current.ID != old.ID || current.StoragePath != old.StoragePath) { + t.Errorf("moved artifact = %+v, old = %+v", current, old) + } + if scenario == "destination exists" && (current == nil || current.StoragePath.String != "destination.zip") { + t.Errorf("destination replaced: %+v", current) + } + if paths := allPendingDeletes(t, db); len(paths) != 0 { + t.Errorf("rekey queued stored bytes for deletion: %v", paths) + } +} + +func prepareRekeyConflict(t *testing.T, db *DB, scenario string, old *Artifact, pkg *Package, version *Version) { + t.Helper() + var err error + switch scenario { + case "destination exists": + err = db.RecordCachedArtifact(pkg, version, &Artifact{VersionPURL: version.PURL, Filename: old.Filename, + StoragePath: sql.NullString{String: "destination.zip", Valid: true}}) + case "source changed": + _, err = db.Exec(db.Rebind(`UPDATE artifacts SET storage_path = ? WHERE id = ?`), "replacement.zip", old.ID) + case "local source": + _, err = db.Exec(db.Rebind(`UPDATE artifacts SET source = ? WHERE id = ?`), SourceLocal, old.ID) + } + if err != nil { + t.Fatal(err) + } +} diff --git a/internal/database/retention.go b/internal/database/retention.go index 90fffd2..0036362 100644 --- a/internal/database/retention.go +++ b/internal/database/retention.go @@ -17,28 +17,33 @@ type RetentionCandidate struct { Size sql.NullInt64 `db:"size"` FetchedAt sql.NullTime `db:"fetched_at"` LastAccessedAt sql.NullTime `db:"last_accessed_at"` + MirroredAt sql.NullTime `db:"mirrored_at"` Ecosystem string `db:"ecosystem"` PackagePURL string `db:"package_purl"` } -// ExpiredBefore reports whether the artifact was neither fetched nor -// accessed at or after cutoff. Both are checked: clearing a record keeps its -// last access time, so a record fetched again after an eviction has a fresh -// fetch time next to an old access time. +// ExpiredBefore reports whether the artifact was neither fetched, accessed +// nor found by a mirror run at or after cutoff. Fetch and access are both +// checked: clearing a record keeps its last access time, so a record fetched +// again after an eviction has a fresh fetch time next to an old access time. func (c RetentionCandidate) ExpiredBefore(cutoff time.Time) bool { if !c.FetchedAt.Valid || !c.FetchedAt.Time.Before(cutoff) { return false } + if c.MirroredAt.Valid && !c.MirroredAt.Time.Before(cutoff) { + return false + } return !c.LastAccessedAt.Valid || c.LastAccessedAt.Time.Before(cutoff) } -// expiredCondition selects cached artifacts fetched before the cutoff and not -// accessed since. It takes the cutoff twice. +// expiredCondition selects cached artifacts fetched before the cutoff and +// neither accessed nor mirrored since. It takes the cutoff three times. const expiredCondition = ` storage_path IS NOT NULL AND source <> 'local' AND fetched_at < ? - AND (last_accessed_at IS NULL OR last_accessed_at < ?)` + AND (last_accessed_at IS NULL OR last_accessed_at < ?) + AND (mirrored_at IS NULL OR mirrored_at < ?)` // MaxArtifactID returns the highest artifact id, or zero for an empty table. func (db *DB) MaxArtifactID() (int64, error) { @@ -56,7 +61,7 @@ func (db *DB) GetRetentionCandidates(fromID, toID int64, cutoff time.Time) ([]Re var candidates []RetentionCandidate query := db.Rebind(` SELECT a.id, a.version_purl, a.filename, a.storage_path, a.size, - a.fetched_at, a.last_accessed_at, p.ecosystem, p.purl AS package_purl + a.fetched_at, a.last_accessed_at, a.mirrored_at, p.ecosystem, p.purl AS package_purl FROM ( SELECT * FROM artifacts WHERE id > ? AND id <= ? AND` + expiredCondition + ` @@ -65,7 +70,7 @@ func (db *DB) GetRetentionCandidates(fromID, toID int64, cutoff time.Time) ([]Re JOIN packages p ON p.purl = v.package_purl ORDER BY a.id `) - if err := db.Select(&candidates, query, fromID, toID, cutoff.UTC(), cutoff.UTC()); err != nil { + if err := db.Select(&candidates, query, fromID, toID, cutoff.UTC(), cutoff.UTC(), cutoff.UTC()); err != nil { return nil, err } return candidates, nil @@ -89,7 +94,7 @@ func (db *DB) ClearExpiredArtifact(versionPURL, filename, storagePath string, cu SET storage_path = NULL, content_hash = NULL, size = NULL, content_type = NULL, fetched_at = NULL, updated_at = ? WHERE version_purl = ? AND filename = ? AND storage_path = ? AND` + expiredCondition) - res, err := tx.Exec(query, time.Now(), versionPURL, filename, storagePath, cutoff.UTC(), cutoff.UTC()) + res, err := tx.Exec(query, time.Now(), versionPURL, filename, storagePath, cutoff.UTC(), cutoff.UTC(), cutoff.UTC()) if err != nil { return false, err } @@ -103,6 +108,16 @@ func (db *DB) ClearExpiredArtifact(versionPURL, filename, storagePath string, cu return true, tx.Commit() } +// MarkArtifactMirrored records that a mirror run found the artifact cached, +// which keeps it from retention without counting as a cache hit. +func (db *DB) MarkArtifactMirrored(versionPURL, filename string) error { + _, err := db.Exec(db.Rebind(` + UPDATE artifacts SET mirrored_at = ? + WHERE version_purl = ? AND filename = ? AND storage_path IS NOT NULL + `), time.Now().UTC(), versionPURL, filename) + return err +} + // GetArtifactEcosystem returns the packages.ecosystem value of the package an // artifact version belongs to, or "" when it has no package record. func (db *DB) GetArtifactEcosystem(versionPURL string) (string, error) { diff --git a/internal/database/retention_test.go b/internal/database/retention_test.go index 213ae22..2382011 100644 --- a/internal/database/retention_test.go +++ b/internal/database/retention_test.go @@ -341,18 +341,20 @@ func TestRetentionCandidateExpiredBefore(t *testing.T) { recent := sql.NullTime{Time: now, Valid: true} tests := []struct { - name string - fetched, accessed sql.NullTime - want bool + name string + fetched, accessed, mirrored sql.NullTime + want bool }{ - {"fetched and accessed before", old, old, true}, - {"never served", old, sql.NullTime{}, true}, - {"accessed since", old, recent, false}, - {"fetched again since", recent, old, false}, - {"not cached", sql.NullTime{}, old, false}, + {"fetched and accessed before", old, old, sql.NullTime{}, true}, + {"never served", old, sql.NullTime{}, sql.NullTime{}, true}, + {"accessed since", old, recent, sql.NullTime{}, false}, + {"fetched again since", recent, old, sql.NullTime{}, false}, + {"not cached", sql.NullTime{}, old, sql.NullTime{}, false}, + {"mirrored since", old, old, recent, false}, + {"mirrored before", old, old, old, true}, } for _, tt := range tests { - c := RetentionCandidate{FetchedAt: tt.fetched, LastAccessedAt: tt.accessed} + c := RetentionCandidate{FetchedAt: tt.fetched, LastAccessedAt: tt.accessed, MirroredAt: tt.mirrored} if got := c.ExpiredBefore(cutoff); got != tt.want { t.Errorf("%s: ExpiredBefore() = %v, want %v", tt.name, got, tt.want) } @@ -394,3 +396,36 @@ func TestGetRetentionCandidatesTimezone(t *testing.T) { } }) } + +func TestArtifactFilenameIndex(t *testing.T) { + runWithBothDatabases(t, func(t *testing.T, db *DB) { + indexQuery := `SELECT COUNT(*) FROM sqlite_master WHERE type = 'index' AND name = 'idx_artifacts_filename'` + if db.Dialect() == DialectPostgres { + indexQuery = `SELECT COUNT(*) FROM pg_indexes WHERE indexname = 'idx_artifacts_filename'` + } + hasIndex := func() bool { + t.Helper() + var count int + if err := db.Get(&count, indexQuery); err != nil { + t.Fatalf("querying indexes: %v", err) + } + return count == 1 + } + + if !hasIndex() { + t.Error("fresh schema has no idx_artifacts_filename") + } + if _, err := db.Exec(`DROP INDEX idx_artifacts_filename`); err != nil { + t.Fatalf("dropping index: %v", err) + } + if err := migrateAddArtifactFilenameIndex(db); err != nil { + t.Fatalf("migration: %v", err) + } + if err := migrateAddArtifactFilenameIndex(db); err != nil { + t.Fatalf("migration is not idempotent: %v", err) + } + if !hasIndex() { + t.Error("migration did not create idx_artifacts_filename") + } + }) +} diff --git a/internal/database/schema.go b/internal/database/schema.go index ce12490..bca37bd 100644 --- a/internal/database/schema.go +++ b/internal/database/schema.go @@ -1,6 +1,7 @@ package database import ( + "context" "fmt" "strings" "time" @@ -74,10 +75,13 @@ CREATE TABLE IF NOT EXISTS artifacts ( created_at DATETIME, updated_at DATETIME, source TEXT NOT NULL DEFAULT 'upstream', - manifest TEXT + manifest TEXT, + mirrored_at DATETIME ); CREATE UNIQUE INDEX IF NOT EXISTS idx_artifacts_version_filename ON artifacts(version_purl, filename); CREATE INDEX IF NOT EXISTS idx_artifacts_storage_path ON artifacts(storage_path); +CREATE INDEX IF NOT EXISTS idx_artifacts_content_hash ON artifacts(content_hash); +CREATE INDEX IF NOT EXISTS idx_artifacts_filename ON artifacts(filename); CREATE INDEX IF NOT EXISTS idx_artifacts_last_accessed ON artifacts(last_accessed_at); CREATE TABLE IF NOT EXISTS pending_deletes ( @@ -86,6 +90,18 @@ CREATE TABLE IF NOT EXISTS pending_deletes ( ); CREATE INDEX IF NOT EXISTS idx_pending_deletes_queued_at ON pending_deletes(queued_at); +CREATE TABLE IF NOT EXISTS job_runs ( + name TEXT NOT NULL PRIMARY KEY, + started_at DATETIME NOT NULL +); + +CREATE TABLE IF NOT EXISTS fetch_leases ( + key TEXT NOT NULL PRIMARY KEY, + owner TEXT NOT NULL, + expires_at DATETIME NOT NULL, + failed BOOLEAN NOT NULL DEFAULT FALSE +); + CREATE TABLE IF NOT EXISTS vulnerabilities ( id INTEGER PRIMARY KEY, vuln_id TEXT NOT NULL, @@ -113,13 +129,18 @@ CREATE TABLE IF NOT EXISTS metadata_cache ( content_type TEXT, content_encoding TEXT, content_digest TEXT, + upstream_url TEXT, size INTEGER, last_modified DATETIME, fetched_at DATETIME, + last_accessed_at DATETIME, created_at DATETIME, updated_at DATETIME ); CREATE UNIQUE INDEX IF NOT EXISTS idx_metadata_eco_name ON metadata_cache(ecosystem, name); +CREATE INDEX IF NOT EXISTS idx_metadata_storage_path ON metadata_cache(storage_path); +CREATE INDEX IF NOT EXISTS idx_metadata_last_used ON metadata_cache(COALESCE(last_accessed_at, updated_at)); +CREATE INDEX IF NOT EXISTS idx_artifacts_last_used ON artifacts(COALESCE(last_accessed_at, fetched_at)); CREATE TABLE IF NOT EXISTS metadata_dates ( ecosystem TEXT NOT NULL, @@ -130,6 +151,45 @@ CREATE TABLE IF NOT EXISTS metadata_dates ( PRIMARY KEY (ecosystem, proxy_url, name) ); +CREATE TABLE IF NOT EXISTS upstream_holds ( + host TEXT NOT NULL PRIMARY KEY, + until_ms INTEGER NOT NULL +); + +CREATE TABLE IF NOT EXISTS metadata_snapshots ( + id INTEGER PRIMARY KEY, + ecosystem TEXT NOT NULL, + name TEXT NOT NULL, + storage_path TEXT NOT NULL, + content_type TEXT, + content_encoding TEXT, + content_digest TEXT NOT NULL, + size INTEGER NOT NULL, + valid_from_ms INTEGER NOT NULL +); +CREATE INDEX IF NOT EXISTS idx_metadata_snapshots_key ON metadata_snapshots(ecosystem, name, valid_from_ms); +CREATE INDEX IF NOT EXISTS idx_metadata_snapshots_path ON metadata_snapshots(storage_path); + +CREATE TABLE IF NOT EXISTS projects ( + id INTEGER PRIMARY KEY, + name TEXT NOT NULL, + ref TEXT, + branch TEXT, + uploaded_at DATETIME NOT NULL +); +CREATE UNIQUE INDEX IF NOT EXISTS idx_projects_name ON projects(name); +CREATE INDEX IF NOT EXISTS idx_projects_uploaded_at ON projects(uploaded_at); + +CREATE TABLE IF NOT EXISTS project_components ( + project_id INTEGER NOT NULL, + package_purl TEXT NOT NULL, + ecosystem TEXT NOT NULL, + name TEXT NOT NULL, + version TEXT NOT NULL, + PRIMARY KEY (project_id, package_purl, version) +); +CREATE INDEX IF NOT EXISTS idx_project_components_package ON project_components(package_purl, version); + CREATE TABLE IF NOT EXISTS migrations ( name TEXT NOT NULL PRIMARY KEY, applied_at DATETIME NOT NULL @@ -194,10 +254,13 @@ CREATE TABLE IF NOT EXISTS artifacts ( created_at TIMESTAMP, updated_at TIMESTAMP, source TEXT NOT NULL DEFAULT 'upstream', - manifest TEXT + manifest TEXT, + mirrored_at TIMESTAMP ); CREATE UNIQUE INDEX IF NOT EXISTS idx_artifacts_version_filename ON artifacts(version_purl, filename); CREATE INDEX IF NOT EXISTS idx_artifacts_storage_path ON artifacts(storage_path); +CREATE INDEX IF NOT EXISTS idx_artifacts_content_hash ON artifacts(content_hash); +CREATE INDEX IF NOT EXISTS idx_artifacts_filename ON artifacts(filename); CREATE INDEX IF NOT EXISTS idx_artifacts_last_accessed ON artifacts(last_accessed_at); CREATE TABLE IF NOT EXISTS pending_deletes ( @@ -206,6 +269,18 @@ CREATE TABLE IF NOT EXISTS pending_deletes ( ); CREATE INDEX IF NOT EXISTS idx_pending_deletes_queued_at ON pending_deletes(queued_at); +CREATE TABLE IF NOT EXISTS job_runs ( + name TEXT NOT NULL PRIMARY KEY, + started_at TIMESTAMP NOT NULL +); + +CREATE TABLE IF NOT EXISTS fetch_leases ( + key TEXT NOT NULL PRIMARY KEY, + owner TEXT NOT NULL, + expires_at TIMESTAMP NOT NULL, + failed BOOLEAN NOT NULL DEFAULT FALSE +); + CREATE TABLE IF NOT EXISTS vulnerabilities ( id SERIAL PRIMARY KEY, vuln_id TEXT NOT NULL, @@ -233,13 +308,18 @@ CREATE TABLE IF NOT EXISTS metadata_cache ( content_type TEXT, content_encoding TEXT, content_digest TEXT, + upstream_url TEXT, size BIGINT, last_modified TIMESTAMP, fetched_at TIMESTAMP, + last_accessed_at TIMESTAMP, created_at TIMESTAMP, updated_at TIMESTAMP ); CREATE UNIQUE INDEX IF NOT EXISTS idx_metadata_eco_name ON metadata_cache(ecosystem, name); +CREATE INDEX IF NOT EXISTS idx_metadata_storage_path ON metadata_cache(storage_path); +CREATE INDEX IF NOT EXISTS idx_metadata_last_used ON metadata_cache((COALESCE(last_accessed_at, updated_at)) NULLS FIRST); +CREATE INDEX IF NOT EXISTS idx_artifacts_last_used ON artifacts((COALESCE(last_accessed_at, fetched_at)) NULLS FIRST); CREATE TABLE IF NOT EXISTS metadata_dates ( ecosystem TEXT NOT NULL, @@ -250,6 +330,45 @@ CREATE TABLE IF NOT EXISTS metadata_dates ( PRIMARY KEY (ecosystem, proxy_url, name) ); +CREATE TABLE IF NOT EXISTS upstream_holds ( + host TEXT NOT NULL PRIMARY KEY, + until_ms BIGINT NOT NULL +); + +CREATE TABLE IF NOT EXISTS metadata_snapshots ( + id SERIAL PRIMARY KEY, + ecosystem TEXT NOT NULL, + name TEXT NOT NULL, + storage_path TEXT NOT NULL, + content_type TEXT, + content_encoding TEXT, + content_digest TEXT NOT NULL, + size BIGINT NOT NULL, + valid_from_ms BIGINT NOT NULL +); +CREATE INDEX IF NOT EXISTS idx_metadata_snapshots_key ON metadata_snapshots(ecosystem, name, valid_from_ms); +CREATE INDEX IF NOT EXISTS idx_metadata_snapshots_path ON metadata_snapshots(storage_path); + +CREATE TABLE IF NOT EXISTS projects ( + id SERIAL PRIMARY KEY, + name TEXT NOT NULL, + ref TEXT, + branch TEXT, + uploaded_at TIMESTAMP NOT NULL +); +CREATE UNIQUE INDEX IF NOT EXISTS idx_projects_name ON projects(name); +CREATE INDEX IF NOT EXISTS idx_projects_uploaded_at ON projects(uploaded_at); + +CREATE TABLE IF NOT EXISTS project_components ( + project_id INTEGER NOT NULL, + package_purl TEXT NOT NULL, + ecosystem TEXT NOT NULL, + name TEXT NOT NULL, + version TEXT NOT NULL, + PRIMARY KEY (project_id, package_purl, version) +); +CREATE INDEX IF NOT EXISTS idx_project_components_package ON project_components(package_purl, version); + CREATE TABLE IF NOT EXISTS migrations ( name TEXT NOT NULL PRIMARY KEY, applied_at TIMESTAMP NOT NULL @@ -273,10 +392,13 @@ CREATE TABLE IF NOT EXISTS artifacts ( created_at DATETIME, updated_at DATETIME, source TEXT NOT NULL DEFAULT 'upstream', - manifest TEXT + manifest TEXT, + mirrored_at DATETIME ); CREATE UNIQUE INDEX IF NOT EXISTS idx_artifacts_version_filename ON artifacts(version_purl, filename); CREATE INDEX IF NOT EXISTS idx_artifacts_storage_path ON artifacts(storage_path); +CREATE INDEX IF NOT EXISTS idx_artifacts_content_hash ON artifacts(content_hash); +CREATE INDEX IF NOT EXISTS idx_artifacts_filename ON artifacts(filename); CREATE INDEX IF NOT EXISTS idx_artifacts_last_accessed ON artifacts(last_accessed_at); ` @@ -296,10 +418,13 @@ CREATE TABLE IF NOT EXISTS artifacts ( created_at TIMESTAMP, updated_at TIMESTAMP, source TEXT NOT NULL DEFAULT 'upstream', - manifest TEXT + manifest TEXT, + mirrored_at TIMESTAMP ); CREATE UNIQUE INDEX IF NOT EXISTS idx_artifacts_version_filename ON artifacts(version_purl, filename); CREATE INDEX IF NOT EXISTS idx_artifacts_storage_path ON artifacts(storage_path); +CREATE INDEX IF NOT EXISTS idx_artifacts_content_hash ON artifacts(content_hash); +CREATE INDEX IF NOT EXISTS idx_artifacts_filename ON artifacts(filename); CREATE INDEX IF NOT EXISTS idx_artifacts_last_accessed ON artifacts(last_accessed_at); ` @@ -411,6 +536,16 @@ var migrations = []migration{ {"011_add_metadata_dates", migrateAddMetadataDates}, {"012_add_artifact_source", migrateAddArtifactSource}, {"013_add_artifact_manifest", migrateAddArtifactManifest}, + {"014_add_metadata_last_accessed", migrateAddMetadataLastAccessed}, + {"015_add_job_runs", migrateAddJobRuns}, + {"016_add_fetch_leases", migrateAddFetchLeases}, + {"017_add_artifact_content_hash_index", migrateAddArtifactContentHashIndex}, + {"018_add_upstream_holds", migrateAddUpstreamHolds}, + {"019_add_artifact_filename_index", migrateAddArtifactFilenameIndex}, + {"020_add_metadata_snapshots", migrateAddMetadataSnapshots}, + {"021_add_projects", migrateAddProjects}, + {"022_add_artifact_mirrored_at", migrateAddArtifactMirroredAt}, + {"023_add_metadata_upstream_url", migrateAddMetadataUpstreamURL}, } // isTableNotFound returns true if the error indicates a missing table. @@ -480,9 +615,19 @@ func (db *DB) recordAllMigrations() error { return nil } +// schemaLock serialises schema creation and migrations across instances +// sharing a Postgres database. +const schemaLock = "schema" + // MigrateSchema applies any unapplied migrations in order. // For a fully migrated database this executes a single SELECT query. +// Instances sharing a Postgres database run it one after the other, so each +// sees the migrations the one before it recorded. func (db *DB) MigrateSchema() error { + return db.WithLock(context.Background(), schemaLock, db.migrateSchema) +} + +func (db *DB) migrateSchema() error { applied, err := db.appliedMigrations() if err != nil { return err @@ -661,6 +806,22 @@ func migrateAddMetadataLink(db *DB) error { return nil } +// migrateAddMetadataUpstreamURL adds the URL a metadata document was +// fetched from, which the mirror refresh fetches it from again. +func migrateAddMetadataUpstreamURL(db *DB) error { + hasColumn, err := db.HasColumn("metadata_cache", "upstream_url") + if err != nil { + return fmt.Errorf("checking metadata_cache upstream_url column: %w", err) + } + if hasColumn { + return nil + } + if _, err := db.Exec("ALTER TABLE metadata_cache ADD COLUMN upstream_url TEXT"); err != nil { + return fmt.Errorf("adding metadata_cache upstream_url column: %w", err) + } + return nil +} + func migrateAddMetadataContentEncoding(db *DB) error { hasColumn, err := db.HasColumn("metadata_cache", "content_encoding") if err != nil { @@ -700,6 +861,94 @@ func migrateAddPendingDeletes(db *DB) error { return nil } +// migrateAddJobRuns creates the table that records when a scheduled job +// last started, so instances sharing the database run it once per interval. +func migrateAddJobRuns(db *DB) error { + ts := sqliteDatetime + if db.dialect == DialectPostgres { + ts = postgresTimestamp + } + query := fmt.Sprintf(`CREATE TABLE IF NOT EXISTS job_runs ( + name TEXT NOT NULL PRIMARY KEY, + started_at %s NOT NULL + )`, ts) + if _, err := db.Exec(query); err != nil { + return fmt.Errorf("creating job_runs table: %w", err) + } + return nil +} + +// migrateAddFetchLeases creates the table instances sharing a Postgres +// database use to fetch each cache miss from upstream only once. +func migrateAddFetchLeases(db *DB) error { + ts := sqliteDatetime + if db.dialect == DialectPostgres { + ts = postgresTimestamp + } + query := fmt.Sprintf(`CREATE TABLE IF NOT EXISTS fetch_leases ( + key TEXT NOT NULL PRIMARY KEY, + owner TEXT NOT NULL, + expires_at %s NOT NULL, + failed BOOLEAN NOT NULL DEFAULT FALSE + )`, ts) + if _, err := db.Exec(query); err != nil { + return fmt.Errorf("creating fetch_leases table: %w", err) + } + return nil +} + +// migrateAddUpstreamHolds creates the table through which instances sharing +// the database honour each other's upstream rate-limit holds. +func migrateAddUpstreamHolds(db *DB) error { + millis := "INTEGER" + if db.dialect == DialectPostgres { + millis = "BIGINT" + } + query := fmt.Sprintf(`CREATE TABLE IF NOT EXISTS upstream_holds ( + host TEXT NOT NULL PRIMARY KEY, + until_ms %s NOT NULL + )`, millis) + if _, err := db.Exec(query); err != nil { + return fmt.Errorf("creating upstream_holds table: %w", err) + } + return nil +} + +// migrateAddProjects creates the tables of the project inventory: the +// projects that uploaded an SBOM and the package versions each one uses. +func migrateAddProjects(db *DB) error { + id, ts := "INTEGER PRIMARY KEY", sqliteDatetime + if db.dialect == DialectPostgres { + id, ts = "SERIAL PRIMARY KEY", postgresTimestamp + } + statements := []string{ + fmt.Sprintf(`CREATE TABLE IF NOT EXISTS projects ( + id %s, + name TEXT NOT NULL, + ref TEXT, + branch TEXT, + uploaded_at %s NOT NULL + )`, id, ts), + `CREATE UNIQUE INDEX IF NOT EXISTS idx_projects_name ON projects(name)`, + `CREATE INDEX IF NOT EXISTS idx_projects_uploaded_at ON projects(uploaded_at)`, + `CREATE TABLE IF NOT EXISTS project_components ( + project_id INTEGER NOT NULL, + package_purl TEXT NOT NULL, + ecosystem TEXT NOT NULL, + name TEXT NOT NULL, + version TEXT NOT NULL, + PRIMARY KEY (project_id, package_purl, version) + )`, + `CREATE INDEX IF NOT EXISTS idx_project_components_package ON project_components(package_purl, version)`, + } + for _, stmt := range statements { + if _, err := db.Exec(stmt); err != nil { + return fmt.Errorf("creating project tables: %w", err) + } + } + return nil +} + // migrateAddPendingDeletesQueuedAtIndex indexes the column reclaim orders // the queue by, which grows large after a retention sweep. func migrateAddPendingDeletesQueuedAtIndex(db *DB) error { @@ -710,6 +959,56 @@ func migrateAddPendingDeletesQueuedAtIndex(db *DB) error { return nil } +// migrateAddArtifactContentHashIndex indexes artifacts by content, so an +// artifact already stored under another name can be found by its hash. +func migrateAddArtifactContentHashIndex(db *DB) error { + _, err := db.Exec(`CREATE INDEX IF NOT EXISTS idx_artifacts_content_hash ON artifacts(content_hash)`) + if err != nil { + return fmt.Errorf("creating artifacts content_hash index: %w", err) + } + return nil +} + +// migrateAddArtifactFilenameIndex indexes artifacts by filename, for +// lookups that don't know the version, such as CachedArtifactNames. +func migrateAddArtifactFilenameIndex(db *DB) error { + _, err := db.Exec(`CREATE INDEX IF NOT EXISTS idx_artifacts_filename ON artifacts(filename)`) + if err != nil { + return fmt.Errorf("creating artifacts filename index: %w", err) + } + return nil +} + +// migrateAddMetadataSnapshots creates the table of kept earlier versions of +// metadata documents, which dated snapshot requests are served from. +func migrateAddMetadataSnapshots(db *DB) error { + pk, integer := "id INTEGER PRIMARY KEY", "INTEGER" + if db.dialect == DialectPostgres { + pk, integer = "id SERIAL PRIMARY KEY", "BIGINT" + } + statements := []string{ + fmt.Sprintf(`CREATE TABLE IF NOT EXISTS metadata_snapshots ( + %s, + ecosystem TEXT NOT NULL, + name TEXT NOT NULL, + storage_path TEXT NOT NULL, + content_type TEXT, + content_encoding TEXT, + content_digest TEXT NOT NULL, + size %s NOT NULL, + valid_from_ms %s NOT NULL + )`, pk, integer, integer), + `CREATE INDEX IF NOT EXISTS idx_metadata_snapshots_key ON metadata_snapshots(ecosystem, name, valid_from_ms)`, + `CREATE INDEX IF NOT EXISTS idx_metadata_snapshots_path ON metadata_snapshots(storage_path)`, + } + for _, query := range statements { + if _, err := db.Exec(query); err != nil { + return fmt.Errorf("creating metadata_snapshots: %w", err) + } + } + return nil +} + // migrateAddMetadataDates creates the table of Last-Modified dates for // rewritten metadata, which replicas sharing the database agree on. func migrateAddMetadataDates(db *DB) error { @@ -805,6 +1104,26 @@ func migrateAddArtifactSource(db *DB) error { return nil } +// migrateAddArtifactMirroredAt records when a mirror run last found an +// artifact cached, which retention counts as use and LRU eviction doesn't. +func migrateAddArtifactMirroredAt(db *DB) error { + hasCol, err := db.HasColumn("artifacts", "mirrored_at") + if err != nil { + return fmt.Errorf("checking column mirrored_at: %w", err) + } + if hasCol { + return nil + } + ts := sqliteDatetime + if db.dialect == DialectPostgres { + ts = postgresTimestamp + } + if _, err := db.Exec(fmt.Sprintf("ALTER TABLE artifacts ADD COLUMN mirrored_at %s", ts)); err != nil { + return fmt.Errorf("adding column mirrored_at to artifacts: %w", err) + } + return nil +} + // migrateAddArtifactManifest stores the manifest read from a pushed archive, // which the metadata of its ecosystem lists the version with. func migrateAddArtifactManifest(db *DB) error { @@ -820,3 +1139,37 @@ func migrateAddArtifactManifest(db *DB) error { } return nil } + +// migrateAddMetadataLastAccessed records when cached metadata was last served, +// for size eviction. Existing rows are backfilled in the background +// (BackfillMetadataLastAccessed), so startup does not wait for them. +func migrateAddMetadataLastAccessed(db *DB) error { + hasCol, err := db.HasColumn("metadata_cache", "last_accessed_at") + if err != nil { + return fmt.Errorf("checking column last_accessed_at: %w", err) + } + if !hasCol { + ts := sqliteDatetime + if db.dialect == DialectPostgres { + ts = postgresTimestamp + } + if _, err := db.Exec(fmt.Sprintf("ALTER TABLE metadata_cache ADD COLUMN last_accessed_at %s", ts)); err != nil { + return fmt.Errorf("adding column last_accessed_at to metadata_cache: %w", err) + } + } + indexes := []string{ + `CREATE INDEX IF NOT EXISTS idx_metadata_storage_path ON metadata_cache(storage_path)`, + `CREATE INDEX IF NOT EXISTS idx_metadata_last_used ON metadata_cache(COALESCE(last_accessed_at, updated_at))`, + `CREATE INDEX IF NOT EXISTS idx_artifacts_last_used ON artifacts(COALESCE(last_accessed_at, fetched_at))`, + } + if db.dialect == DialectPostgres { + indexes[1] = `CREATE INDEX IF NOT EXISTS idx_metadata_last_used ON metadata_cache((COALESCE(last_accessed_at, updated_at)) NULLS FIRST)` + indexes[2] = `CREATE INDEX IF NOT EXISTS idx_artifacts_last_used ON artifacts((COALESCE(last_accessed_at, fetched_at)) NULLS FIRST)` + } + for _, q := range indexes { + if _, err := db.Exec(q); err != nil { + return fmt.Errorf("indexing metadata_cache: %w", err) + } + } + return nil +} diff --git a/internal/database/types.go b/internal/database/types.go index e931f5b..4e31a68 100644 --- a/internal/database/types.go +++ b/internal/database/types.go @@ -151,6 +151,9 @@ type Artifact struct { UpdatedAt time.Time `db:"updated_at" json:"updated_at"` Source string `db:"source" json:"source"` Manifest sql.NullString `db:"manifest" json:"manifest,omitempty"` + // MirroredAt is when a mirror run last found the artifact cached. It + // keeps the artifact from retention but not from LRU eviction. + MirroredAt sql.NullTime `db:"mirrored_at" json:"-"` } func (a *Artifact) sourceOrUpstream() string { @@ -184,11 +187,15 @@ type MetadataCacheEntry struct { ContentType sql.NullString `db:"content_type" json:"content_type,omitempty"` ContentEncoding sql.NullString `db:"content_encoding" json:"content_encoding,omitempty"` ContentDigest sql.NullString `db:"content_digest" json:"content_digest,omitempty"` - Size sql.NullInt64 `db:"size" json:"size,omitempty"` - LastModified sql.NullTime `db:"last_modified" json:"last_modified,omitempty"` - FetchedAt sql.NullTime `db:"fetched_at" json:"fetched_at,omitempty"` - CreatedAt time.Time `db:"created_at" json:"created_at"` - UpdatedAt time.Time `db:"updated_at" json:"updated_at"` + // UpstreamURL is where the document was fetched from. Rows written + // before it was recorded, and by writers that don't know it, have none. + UpstreamURL sql.NullString `db:"upstream_url" json:"upstream_url,omitempty"` + Size sql.NullInt64 `db:"size" json:"size,omitempty"` + LastModified sql.NullTime `db:"last_modified" json:"last_modified,omitempty"` + FetchedAt sql.NullTime `db:"fetched_at" json:"fetched_at,omitempty"` + LastAccessedAt sql.NullTime `db:"last_accessed_at" json:"last_accessed_at,omitempty"` + CreatedAt time.Time `db:"created_at" json:"created_at"` + UpdatedAt time.Time `db:"updated_at" json:"updated_at"` } // Vulnerability represents a cached vulnerability record. diff --git a/internal/database/upstream_holds.go b/internal/database/upstream_holds.go new file mode 100644 index 0000000..6f842ca --- /dev/null +++ b/internal/database/upstream_holds.go @@ -0,0 +1,58 @@ +package database + +import ( + "fmt" + "time" +) + +// Upstream holds let instances sharing a database honour a rate-limit hold +// any one of them placed, so each does not need its own 429 before it stops +// sending. Times are the instances' own clocks in Unix milliseconds; a few +// seconds of skew does not matter next to holds of a minute or more. + +type upstreamHoldRow struct { + Host string `db:"host"` + UntilMS int64 `db:"until_ms"` +} + +// PutUpstreamHold records that requests to host are held until until. A hold +// already recorded for longer is kept. +func (db *DB) PutUpstreamHold(host string, until time.Time) error { + _, err := db.Exec(db.Rebind(` + INSERT INTO upstream_holds (host, until_ms) VALUES (?, ?) + ON CONFLICT (host) DO UPDATE SET until_ms = CASE + WHEN excluded.until_ms > upstream_holds.until_ms THEN excluded.until_ms + ELSE upstream_holds.until_ms END + `), host, until.UnixMilli()) + if err != nil { + return fmt.Errorf("recording upstream hold: %w", err) + } + return nil +} + +// UpstreamHolds returns the holds that have not ended by now, and deletes +// those that have. +func (db *DB) UpstreamHolds(now time.Time) (map[string]time.Time, error) { + var rows []upstreamHoldRow + if err := db.Select(&rows, `SELECT host, until_ms FROM upstream_holds`); err != nil { + return nil, fmt.Errorf("reading upstream holds: %w", err) + } + holds := make(map[string]time.Time, len(rows)) + expired := false + for _, row := range rows { + until := time.UnixMilli(row.UntilMS) + if now.Before(until) { + holds[row.Host] = until + } else { + expired = true + } + } + // Only write when there is something to delete, so the frequent reads + // stay reads. + if expired { + if _, err := db.Exec(db.Rebind(`DELETE FROM upstream_holds WHERE until_ms <= ?`), now.UnixMilli()); err != nil { + return holds, fmt.Errorf("deleting expired upstream holds: %w", err) + } + } + return holds, nil +} diff --git a/internal/database/upstream_holds_test.go b/internal/database/upstream_holds_test.go new file mode 100644 index 0000000..5d6617c --- /dev/null +++ b/internal/database/upstream_holds_test.go @@ -0,0 +1,48 @@ +package database + +import ( + "testing" + "time" +) + +func TestUpstreamHolds(t *testing.T) { + runWithBothDatabases(t, func(t *testing.T, db *DB) { + now := time.UnixMilli(time.Now().UnixMilli()) + if err := db.PutUpstreamHold("registry.npmjs.org", now.Add(time.Minute)); err != nil { + t.Fatal(err) + } + // A shorter hold reported later keeps the longer one. + if err := db.PutUpstreamHold("registry.npmjs.org", now.Add(30*time.Second)); err != nil { + t.Fatal(err) + } + if err := db.PutUpstreamHold("pypi.org", now.Add(10*time.Second)); err != nil { + t.Fatal(err) + } + holds, err := db.UpstreamHolds(now) + if err != nil { + t.Fatal(err) + } + if len(holds) != 2 || !holds["registry.npmjs.org"].Equal(now.Add(time.Minute)) { + t.Fatalf("holds = %v", holds) + } + + // A longer one replaces it. + if err := db.PutUpstreamHold("registry.npmjs.org", now.Add(time.Hour)); err != nil { + t.Fatal(err) + } + holds, err = db.UpstreamHolds(now.Add(20 * time.Second)) + if err != nil { + t.Fatal(err) + } + if len(holds) != 1 || !holds["registry.npmjs.org"].Equal(now.Add(time.Hour)) { + t.Fatalf("holds after pypi.org ended = %v", holds) + } + var rows int + if err := db.Get(&rows, "SELECT COUNT(*) FROM upstream_holds"); err != nil { + t.Fatal(err) + } + if rows != 1 { + t.Errorf("rows = %d, want the ended hold deleted", rows) + } + }) +} diff --git a/internal/denylist/denylist.go b/internal/denylist/denylist.go index c4384ad..eea8ee3 100644 --- a/internal/denylist/denylist.go +++ b/internal/denylist/denylist.go @@ -5,6 +5,7 @@ import ( "fmt" "strings" + "github.com/git-pkgs/proxy/internal/packageurl" "github.com/git-pkgs/purl" ) @@ -14,7 +15,8 @@ type Policy struct { } // New validates and canonicalizes versioned PURLs. Qualifiers and subpaths are -// rejected because the proxy cannot reliably distinguish them at every endpoint. +// rejected because the proxy cannot reliably distinguish them at every endpoint, +// except a conda channel, which download URLs always name. func New(packages []string) (*Policy, error) { if len(packages) == 0 { return nil, nil @@ -25,19 +27,39 @@ func New(packages []string) (*Policy, error) { if err != nil { return nil, fmt.Errorf("invalid denylist package %q: %w", value, err) } - if pkg.Version == "" || len(pkg.Qualifiers) != 0 || pkg.Subpath != "" || + if pkg.Version == "" || !allowedQualifiers(pkg) || pkg.Subpath != "" || strings.ContainsAny(pkg.Namespace+pkg.Name+pkg.Version, "*?[]<>=| \t\r\n") { return nil, fmt.Errorf("invalid denylist package %q: expected an exact versioned PURL without qualifiers or subpath", value) } - key := pkg.WithoutVersion().String() + id := identify(pkg) + key := id.key + if id.channel != "" { + key = id.channelKey() + } if p.packages[key] == nil { p.packages[key] = make(map[string]bool) } - p.packages[key][pkg.Version] = true + p.packages[key][id.version] = true + // Debian and RPM filenames leave the epoch out, so an entry with + // one also matches the version without it. + if pkg.Type == "deb" || pkg.Type == "rpm" { + if _, version, ok := strings.Cut(id.version, ":"); ok && version != "" { + p.packages[key][version] = true + } + } } return p, nil } +func allowedQualifiers(pkg *purl.PURL) bool { + for _, q := range pkg.Qualifiers { + if pkg.Type != "conda" || q.Key != "channel" { + return false + } + } + return true +} + // Denied reports whether a versioned PURL is denied. func (p *Policy) Denied(value string) bool { if p == nil || len(p.packages) == 0 { @@ -47,21 +69,89 @@ func (p *Policy) Denied(value string) bool { if err != nil { return false } - return p.packages[pkg.WithoutVersion().String()][pkg.Version] + id := identify(pkg) + versions := []string{id.version} + // A platform gem's version carries the platform ("1.16.0-x86_64-linux"), + // so also match the plain version. + if pkg.Type == "gem" { + if base, _, found := strings.Cut(id.version, "-"); found && base != "" { + versions = append(versions, base) + } + } + for _, version := range versions { + if p.packages[id.key][version] || (id.channel != "" && p.packages[id.channelKey()][version]) { + return true + } + } + return false } // Versions returns a caller-owned set of denied versions for a package PURL. func (p *Policy) Versions(packagePURL string) map[string]bool { - if p == nil { + if p == nil || len(p.packages) == 0 { return nil } - versions := p.packages[packagePURL] - if len(versions) == 0 { + pkg, err := purl.Parse(packagePURL) + if err != nil { return nil } - result := make(map[string]bool, len(versions)) - for version := range versions { + id := identify(pkg) + result := make(map[string]bool) + for version := range p.packages[id.key] { result[version] = true } + if id.channel != "" { + for version := range p.packages[id.channelKey()] { + result[version] = true + } + } + if len(result) == 0 { + return nil + } return result } + +// identity is the form a PURL is compared in: the same for denylist entries +// and for the PURLs handlers build, however each spells the package. +type identity struct { + key string // versionless PURL without channel + channel string // conda channel, if any + version string +} + +func (id identity) channelKey() string { + return id.key + "?channel=" + id.channel +} + +// genericSwiftRegistry returns the scope and name of a Swift registry archive, +// which the proxy stores as pkg:generic/swift-registry/{scope}.{name}. +func genericSwiftRegistry(pkg *purl.PURL) (scope, name string, ok bool) { + if pkg.Type != "generic" || !strings.EqualFold(pkg.Namespace, "swift-registry") { + return "", "", false + } + scope, name, found := strings.Cut(pkg.Name, ".") + return scope, name, found && scope != "" && name != "" +} + +// identify compares PURLs in purl's comparison form. The generic +// swift-registry spelling is the proxy's own, so it is mapped here first. +// The namespace of a distro type names the distribution, which handlers +// include for some types and not others, so it is dropped as retention and +// the inventory do. +func identify(pkg *purl.PURL) identity { + if scope, name, ok := genericSwiftRegistry(pkg); ok { + pkg = purl.New("swift", scope, name, pkg.Version, nil) + } + c := pkg.ComparisonForm() + var channel string + if c.Type == "conda" { + // An entry without a channel matches every channel. + channel = c.Qualifier("channel") + } + namespace := c.Namespace + if packageurl.DistroType(c.Type) { + namespace = "" + } + key := purl.New(c.Type, namespace, c.Name, "", nil).String() + return identity{key: packageurl.PolicyPackageKey(key), channel: channel, version: c.Version} +} diff --git a/internal/denylist/denylist_test.go b/internal/denylist/denylist_test.go index 380f1ee..03edc99 100644 --- a/internal/denylist/denylist_test.go +++ b/internal/denylist/denylist_test.go @@ -29,7 +29,7 @@ func TestPolicy(t *testing.T) { } func TestInvalidPolicy(t *testing.T) { - for _, value := range []string{"", "not-a-purl", "pkg:npm/foo", "pkg:npm/foo@*", "pkg:npm/foo@>=1", "pkg:npm/foo@1?arch=x86", "pkg:npm/foo@1#src"} { + for _, value := range []string{"", "not-a-purl", "pkg:npm/foo", "pkg:npm/foo@*", "pkg:npm/foo@>=1", "pkg:npm/foo@1?arch=x86", "pkg:npm/foo@1#src", "pkg:conda/numpy@1?subdir=linux-64", "pkg:pypi/foo@1?channel=x"} { t.Run(value, func(t *testing.T) { if _, err := New([]string{value}); err == nil { t.Fatal("invalid denylist accepted") @@ -37,3 +37,91 @@ func TestInvalidPolicy(t *testing.T) { }) } } + +func TestEcosystemSpellings(t *testing.T) { + p, err := New([]string{ + "pkg:pypi/zope.interface@6.0", + "pkg:nuget/Newtonsoft.Json@13.0.1-Beta", + "pkg:gem/nokogiri@1.16.0", + "pkg:gem/sorbet-static@0.5.1-universal-darwin-22", + "pkg:conda/numpy@1.26.4", + "pkg:conda/scipy@1.0?channel=conda-forge", + "pkg:conda/bioconda/samtools@1.0", + "pkg:composer/symfony/console@6.1.7", + "pkg:composer/monolog/monolog@v3.5.0", + "pkg:oci/library/alpine@sha256:abc", + "pkg:oci/upstream%2Fghcr%2Forg%2Fimage@sha256:def", + "pkg:swift/Apple/Swift-NIO@2.0.0", + "pkg:generic/swift-registry/apple.example@1.0.0", + }) + if err != nil { + t.Fatal(err) + } + for _, value := range []string{ + "pkg:pypi/zope-interface@6.0", "pkg:pypi/Zope__Interface@6.0", + "pkg:nuget/newtonsoft.json@13.0.1-beta", + "pkg:gem/nokogiri@1.16.0", "pkg:gem/nokogiri@1.16.0-x86_64-linux", + "pkg:gem/sorbet-static@0.5.1-universal-darwin-22", + "pkg:conda/numpy@1.26.4", "pkg:conda/conda-forge%2Fnumpy@1.26.4", + "pkg:conda/conda-forge%2Fscipy@1.0", "pkg:conda/bioconda%2Fsamtools@1.0", + "pkg:composer/symfony/console@v6.1.7", "pkg:composer/symfony/console@V6.1.7", + "pkg:composer/monolog/monolog@3.5.0", + "pkg:oci/library%2Falpine@sha256:abc", "pkg:oci/library/alpine@sha256:abc", + "pkg:oci/upstream/ghcr/org/image@sha256:def", + "pkg:generic/swift-registry/apple.swift-nio@2.0.0", "pkg:swift/apple/swift-nio@2.0.0", + "pkg:swift/apple/example@1.0.0", + } { + if !p.Denied(value) { + t.Errorf("not denied: %s", value) + } + } + for _, value := range []string{ + "pkg:pypi/zopeinterface@6.0", "pkg:gem/nokogiri@1.16.1-x86_64-linux", "pkg:gem/Nokogiri@1.16.0", + "pkg:conda/bioconda%2Fscipy@1.0", "pkg:conda/scipy@1.0", "pkg:conda/conda-forge%2Fsamtools@1.0", + "pkg:composer/symfony/console@6.1.70", "pkg:composer/symfony/console@vv6.1.7", "pkg:npm/demo@v6.1.7", + "pkg:oci/alpine@sha256:abc", "pkg:oci/library%2Falpine@sha256:abd", + "pkg:generic/other/apple.swift-nio@2.0.0", "pkg:swift/github.com/apple/swift-nio@2.0.0", + } { + if p.Denied(value) { + t.Errorf("unexpected denial: %s", value) + } + } + if !p.Versions("pkg:pypi/zope_interface")["6.0"] { + t.Error("pypi versions not found under another spelling") + } +} + +// TestDistroNamespaces checks that the distribution namespace of a distro +// package is ignored on both sides, as handlers build some of these PURLs +// without one and some with one. +func TestDistroNamespaces(t *testing.T) { + p, err := New([]string{"pkg:deb/debian/curl@8.5.0-2", "pkg:rpm/fedora/curl@8.6.0-1.fc40", "pkg:apk/busybox@1.36.1-r15", "pkg:alpm/glibc@2.39-1"}) + if err != nil { + t.Fatal(err) + } + for _, value := range []string{"pkg:deb/curl@8.5.0-2", "pkg:rpm/curl@8.6.0-1.fc40", "pkg:apk/alpine/busybox@1.36.1-r15", "pkg:alpm/arch/glibc@2.39-1"} { + if !p.Denied(value) { + t.Errorf("not denied: %s", value) + } + } + if p.Denied("pkg:deb/curl@8.5.0-3") { + t.Error("other version denied") + } +} + +// TestDistroEpochs checks that a deb or rpm entry with an epoch matches the +// version as it appears in a filename, which leaves the epoch out. +func TestDistroEpochs(t *testing.T) { + p, err := New([]string{"pkg:deb/foo@1:2.3-1", "pkg:rpm/bar@2:1.0-1.fc40"}) + if err != nil { + t.Fatal(err) + } + for _, value := range []string{"pkg:deb/foo@2.3-1", "pkg:deb/foo@1:2.3-1", "pkg:rpm/bar@1.0-1.fc40"} { + if !p.Denied(value) { + t.Errorf("not denied: %s", value) + } + } + if p.Denied("pkg:deb/foo@2.3-2") { + t.Error("other version denied") + } +} diff --git a/internal/enrichment/enrichment.go b/internal/enrichment/enrichment.go index db8cc13..2246e39 100644 --- a/internal/enrichment/enrichment.go +++ b/internal/enrichment/enrichment.go @@ -1,106 +1,59 @@ -// Package enrichment provides package metadata enrichment using external data sources. -// It fetches license information, vulnerability data, and version information -// from package registries and vulnerability databases. +// Package enrichment adapts github.com/git-pkgs/enrichment to the proxy's +// enrichment API. It builds package URLs from the proxy's ecosystem names, +// normalizes licenses for display and treats retracted versions as yanked. package enrichment import ( "context" + "errors" "log/slog" "sync" - "time" + shared "github.com/git-pkgs/enrichment" "github.com/git-pkgs/proxy/internal/packageurl" - "github.com/git-pkgs/purl" "github.com/git-pkgs/registries" - _ "github.com/git-pkgs/registries/all" // Import all registry implementations "github.com/git-pkgs/spdx" - "github.com/git-pkgs/vers" - "github.com/git-pkgs/vulns" - "github.com/git-pkgs/vulns/osv" ) -// Service provides package enrichment capabilities. +// Service looks up package, version and vulnerability data. type Service struct { logger *slog.Logger - regClient *registries.Client - vulnSource vulns.Source + registries *shared.RegistriesClient + vulns *shared.VulnerabilityClient } // New creates a new enrichment service. func New(logger *slog.Logger) *Service { return &Service{ logger: logger, - regClient: registries.DefaultClient(), - vulnSource: osv.New(), + registries: shared.NewRegistriesClient(), + vulns: shared.NewVulnerabilityClient(), } } -// PackageInfo contains enriched package metadata. -type PackageInfo struct { - Ecosystem string - Name string - LatestVersion string - License string - Description string - Homepage string - Repository string - RegistryURL string -} +type ( + PackageInfo = shared.PackageInfo + VersionInfo = shared.VersionInfo + VulnInfo = shared.VulnInfo +) -// VersionInfo contains enriched version metadata. -type VersionInfo struct { - Number string - License string - PublishedAt time.Time - Integrity string - Yanked bool -} - -// VulnInfo contains vulnerability information for a package version. -type VulnInfo struct { - ID string - Summary string - Severity string - CVSSScore float64 - FixedVersion string - References []string -} - -// EnrichPackage fetches metadata for a package from registry APIs. +// EnrichPackage fetches metadata for a package from its registry. It returns +// nil without an error when the registry doesn't have the package or the name +// can't be expressed as a PURL. func (s *Service) EnrichPackage(ctx context.Context, ecosystem, name string) (*PackageInfo, error) { purlStr := packageurl.MakeString(ecosystem, name, "") if purlStr == "" { return nil, nil } - - pkg, err := registries.FetchPackageFromPURL(ctx, purlStr, s.regClient) - if err != nil { - return nil, err - } - - if pkg == nil { + info, err := s.registries.GetPackage(ctx, purlStr) + if errors.Is(err, registries.ErrNotFound) { return nil, nil } - - info := &PackageInfo{ - Ecosystem: ecosystem, - Name: pkg.Name, - LatestVersion: pkg.LatestVersion, - Description: pkg.Description, - Homepage: pkg.Homepage, - Repository: pkg.Repository, - RegistryURL: registries.DefaultURL(ecosystem), + if err != nil || info == nil { + return nil, err } - - // Normalize license to SPDX format - if pkg.Licenses != "" { - if normalized, err := spdx.NormalizeExpressionLax(pkg.Licenses); err == nil { - info.License = normalized - } else { - info.License = pkg.Licenses - } - } - + info.Ecosystem = ecosystem + info.License = normalizeLicense(info.License) return info, nil } @@ -110,36 +63,24 @@ func (s *Service) EnrichVersion(ctx context.Context, ecosystem, name, version st if purlStr == "" { return nil, nil } - - ver, err := registries.FetchVersionFromPURL(ctx, purlStr, s.regClient) - if err != nil { + info, err := s.registries.GetVersion(ctx, purlStr) + if err != nil || info == nil { return nil, err } - - if ver == nil { - return nil, nil - } - - info := &VersionInfo{ - Number: ver.Number, - PublishedAt: ver.PublishedAt, - Integrity: ver.Integrity, - Yanked: ver.Status == registries.StatusYanked || ver.Status == registries.StatusRetracted, - } - - // Normalize license - if ver.Licenses != "" { - if normalized, err := spdx.NormalizeExpressionLax(ver.Licenses); err == nil { - info.License = normalized - } else { - info.License = ver.Licenses - } - } - + adaptVersion(info) return info, nil } -// BulkEnrichPackages fetches metadata for multiple packages in parallel. +// adaptVersion reports retracted versions as yanked and normalizes the license. +func adaptVersion(info *VersionInfo) { + if info.Status == string(registries.StatusRetracted) { + info.Yanked = true + } + info.License = normalizeLicense(info.License) +} + +// BulkEnrichPackages fetches metadata for multiple packages in parallel, +// keyed by PURL. Packages that can't be fetched are left out. func (s *Service) BulkEnrichPackages(ctx context.Context, packages []struct{ Ecosystem, Name string }) map[string]*PackageInfo { purls := make([]string, 0, len(packages)) for _, pkg := range packages { @@ -150,126 +91,37 @@ func (s *Service) BulkEnrichPackages(ctx context.Context, packages []struct{ Eco if len(purls) == 0 { return map[string]*PackageInfo{} } - - pkgData := registries.BulkFetchPackages(ctx, purls, s.regClient) - - result := make(map[string]*PackageInfo, len(pkgData)) - for purlStr, pkg := range pkgData { - if pkg == nil { - continue - } - - p, err := purl.Parse(purlStr) - if err != nil { - continue - } - info := &PackageInfo{ - Ecosystem: p.Type, - Name: pkg.Name, - LatestVersion: pkg.LatestVersion, - Description: pkg.Description, - Homepage: pkg.Homepage, - Repository: pkg.Repository, - RegistryURL: registries.DefaultURL(p.Type), - } - - if pkg.Licenses != "" { - if normalized, err := spdx.NormalizeExpressionLax(pkg.Licenses); err == nil { - info.License = normalized - } else { - info.License = pkg.Licenses - } - } - - result[purlStr] = info + result, _ := s.registries.BulkLookup(ctx, purls) + for _, info := range result { + info.License = normalizeLicense(info.License) } - return result } // CheckVulnerabilities queries for vulnerabilities affecting a package version. func (s *Service) CheckVulnerabilities(ctx context.Context, ecosystem, name, version string) ([]VulnInfo, error) { - p := packageurl.Make(ecosystem, name, version) - if p == nil { - return nil, nil - } - - vulnList, err := s.vulnSource.Query(ctx, p) - if err != nil { - return nil, err - } - - results := make([]VulnInfo, 0, len(vulnList)) - for _, v := range vulnList { - info := VulnInfo{ - ID: v.ID, - Summary: v.Summary, - Severity: v.SeverityLevel(), - CVSSScore: v.CVSSScore(), - FixedVersion: v.FixedVersion(ecosystem, name), - } - - for _, ref := range v.References { - info.References = append(info.References, ref.URL) - } - - results = append(results, info) - } - - return results, nil -} - -// IsOutdated checks if a version is older than the latest version. -func (s *Service) IsOutdated(currentVersion, latestVersion string) bool { - if latestVersion == "" || currentVersion == "" { - return false - } - return vers.Compare(currentVersion, latestVersion) < 0 + return s.vulns.Check(ctx, ecosystem, name, version) } // GetLatestVersion fetches the latest version for a package. func (s *Service) GetLatestVersion(ctx context.Context, ecosystem, name string) (string, error) { - purlStr := packageurl.MakeString(ecosystem, name, "") - if purlStr == "" { - return "", nil - } - - latest, err := registries.FetchLatestVersionFromPURL(ctx, purlStr, s.regClient) - if err != nil { + info, err := s.EnrichPackage(ctx, ecosystem, name) + if err != nil || info == nil { return "", err } - - if latest == nil { - return "", nil - } - - return latest.Number, nil + return info.LatestVersion, nil } -// LicenseCategory represents the category of a license. -type LicenseCategory string - -const ( - LicensePermissive LicenseCategory = "permissive" - LicenseCopyleft LicenseCategory = "copyleft" - LicenseUnknown LicenseCategory = "unknown" -) - -// CategorizeLicense returns the category of a license. -func (s *Service) CategorizeLicense(license string) LicenseCategory { - if license == "" || license == "Unknown" { - return LicenseUnknown +// normalizeLicense returns license as an SPDX expression when it can be +// parsed as one, and unchanged otherwise. +func normalizeLicense(license string) string { + if license == "" { + return "" } - - if spdx.HasCopyleft(license) { - return LicenseCopyleft + if normalized, err := spdx.NormalizeExpressionLax(license); err == nil { + return normalized } - - if spdx.IsFullyPermissive(license) { - return LicensePermissive - } - - return LicenseUnknown + return license } // EnrichmentResult contains all enrichment data for a package version. @@ -278,40 +130,25 @@ type EnrichmentResult struct { Version *VersionInfo Vulnerabilities []VulnInfo IsOutdated bool - LicenseCategory LicenseCategory + LicenseCategory shared.LicenseCategory } -// EnrichFull performs full enrichment for a package version. +// EnrichFull fetches package, version and vulnerability data for a package +// version concurrently. Unsupported vulnerability identities return an error; +// other failed lookups are logged and left empty. func (s *Service) EnrichFull(ctx context.Context, ecosystem, name, version string) (*EnrichmentResult, error) { result := &EnrichmentResult{} var wg sync.WaitGroup var pkgErr, verErr, vulnErr error - - // Fetch package info - wg.Add(1) - go func() { - defer wg.Done() - result.Package, pkgErr = s.EnrichPackage(ctx, ecosystem, name) - }() - - // Fetch version info - wg.Add(1) - go func() { - defer wg.Done() - result.Version, verErr = s.EnrichVersion(ctx, ecosystem, name, version) - }() - - // Check vulnerabilities - wg.Add(1) - go func() { - defer wg.Done() - result.Vulnerabilities, vulnErr = s.CheckVulnerabilities(ctx, ecosystem, name, version) - }() - + wg.Go(func() { result.Package, pkgErr = s.EnrichPackage(ctx, ecosystem, name) }) + wg.Go(func() { result.Version, verErr = s.EnrichVersion(ctx, ecosystem, name, version) }) + wg.Go(func() { result.Vulnerabilities, vulnErr = s.CheckVulnerabilities(ctx, ecosystem, name, version) }) wg.Wait() + if errors.Is(vulnErr, shared.ErrUnsupportedVulnerabilityIdentity) { + return nil, vulnErr + } - // Log errors but don't fail if pkgErr != nil { s.logger.Debug("failed to enrich package", "ecosystem", ecosystem, "name", name, "error", pkgErr) } @@ -322,19 +159,17 @@ func (s *Service) EnrichFull(ctx context.Context, ecosystem, name, version strin s.logger.Debug("failed to check vulnerabilities", "ecosystem", ecosystem, "name", name, "version", version, "error", vulnErr) } - // Determine outdated status - if result.Package != nil && result.Package.LatestVersion != "" { - result.IsOutdated = s.IsOutdated(version, result.Package.LatestVersion) + if result.Package != nil { + result.IsOutdated = shared.IsOutdated(version, result.Package.LatestVersion) } - // Categorize license license := "" if result.Version != nil && result.Version.License != "" { license = result.Version.License - } else if result.Package != nil && result.Package.License != "" { + } else if result.Package != nil { license = result.Package.License } - result.LicenseCategory = s.CategorizeLicense(license) + result.LicenseCategory = shared.CategorizeLicense(license) return result, nil } diff --git a/internal/enrichment/enrichment_test.go b/internal/enrichment/enrichment_test.go index 3952eb2..f01bb29 100644 --- a/internal/enrichment/enrichment_test.go +++ b/internal/enrichment/enrichment_test.go @@ -2,9 +2,13 @@ package enrichment import ( "context" + "errors" "log/slog" "os" "testing" + + shared "github.com/git-pkgs/enrichment" + "github.com/git-pkgs/registries" ) func TestNew(t *testing.T) { @@ -15,16 +19,16 @@ func TestNew(t *testing.T) { t.Fatal("New() returned nil") } - if svc.regClient == nil { - t.Error("regClient is nil") + if svc.registries == nil { + t.Error("registries is nil") } - if svc.vulnSource == nil { - t.Error("vulnSource is nil") + if svc.vulns == nil { + t.Error("vulns is nil") } } -func TestSwiftRegistryIdentitySkipsPURLDependentLookups(t *testing.T) { +func TestSwiftRegistryIdentityLookups(t *testing.T) { svc := New(slog.New(slog.NewTextHandler(os.Stdout, nil))) ctx := context.Background() @@ -39,8 +43,11 @@ func TestSwiftRegistryIdentitySkipsPURLDependentLookups(t *testing.T) { } vulnerabilities, err := svc.CheckVulnerabilities(ctx, "swift", "apple/example", "1.2.3") - if err != nil || vulnerabilities != nil { - t.Errorf("CheckVulnerabilities() = %#v, %v; want nil, nil", vulnerabilities, err) + if !errors.Is(err, shared.ErrUnsupportedVulnerabilityIdentity) || vulnerabilities != nil { + t.Errorf("CheckVulnerabilities() = %#v, %v; want unsupported identity", vulnerabilities, err) + } + if _, err := svc.EnrichFull(ctx, "swift", "apple/example", "1.2.3"); !errors.Is(err, shared.ErrUnsupportedVulnerabilityIdentity) { + t.Errorf("EnrichFull error = %v, want unsupported identity", err) } latest, err := svc.GetLatestVersion(ctx, "swift", "apple/example") @@ -54,54 +61,23 @@ func TestSwiftRegistryIdentitySkipsPURLDependentLookups(t *testing.T) { } } -func TestIsOutdated(t *testing.T) { - logger := slog.New(slog.NewTextHandler(os.Stdout, nil)) - svc := New(logger) - +func TestAdaptVersion(t *testing.T) { tests := []struct { - current string - latest string - expected bool + status registries.VersionStatus + yanked bool + license string + wantYanked bool + wantLicense string }{ - {"1.0.0", "2.0.0", true}, - {"2.0.0", "2.0.0", false}, - {"2.0.0", "1.0.0", false}, - {"1.0.0", "", false}, - {"", "2.0.0", false}, - {"1.2.3", "1.2.4", true}, - {"1.2.4", "1.2.3", false}, + {status: registries.StatusRetracted, license: "mit", wantYanked: true, wantLicense: "MIT"}, + {status: registries.StatusYanked, yanked: true, wantYanked: true}, + {status: registries.StatusDeprecated, license: "Custom terms", wantLicense: "Custom terms"}, } - for _, tc := range tests { - result := svc.IsOutdated(tc.current, tc.latest) - if result != tc.expected { - t.Errorf("IsOutdated(%q, %q) = %v, want %v", tc.current, tc.latest, result, tc.expected) - } - } -} - -func TestCategorizeLicense(t *testing.T) { - logger := slog.New(slog.NewTextHandler(os.Stdout, nil)) - svc := New(logger) - - tests := []struct { - license string - expected LicenseCategory - }{ - {"MIT", LicensePermissive}, - {"Apache-2.0", LicensePermissive}, - {"BSD-3-Clause", LicensePermissive}, - {"GPL-3.0", LicenseCopyleft}, - {"AGPL-3.0", LicenseCopyleft}, - {"LGPL-2.1", LicenseCopyleft}, - {"", LicenseUnknown}, - {"Unknown", LicenseUnknown}, - } - - for _, tc := range tests { - result := svc.CategorizeLicense(tc.license) - if result != tc.expected { - t.Errorf("CategorizeLicense(%q) = %v, want %v", tc.license, result, tc.expected) + info := &VersionInfo{Status: string(tc.status), Yanked: tc.yanked, License: tc.license} + adaptVersion(info) + if info.Yanked != tc.wantYanked || info.License != tc.wantLicense { + t.Errorf("adaptVersion(%s, %q) = yanked %v, license %q; want %v, %q", tc.status, tc.license, info.Yanked, info.License, tc.wantYanked, tc.wantLicense) } } } diff --git a/internal/gitcache/budget.go b/internal/gitcache/budget.go new file mode 100644 index 0000000..2b0c228 --- /dev/null +++ b/internal/gitcache/budget.go @@ -0,0 +1,139 @@ +package gitcache + +import ( + "context" + "errors" + "sync/atomic" + "time" +) + +const ( + // maxReserveChunk caps the space a fetch reserves ahead of what it has + // received, so the cache is not locked for every read. Each fetch takes + // at most a sixteenth of MaxSize ahead, so fetches share a small cache. + maxReserveChunk = 4 << 20 + reserveChunks = 16 + // cutWait bounds how long a fetch waits for one that was cut off to + // give back its space. + cutWait = time.Minute +) + +// reservation holds space within MaxSize for the bytes a fetch receives, +// until they are counted in the repository's size. Fetches still running +// therefore count toward MaxSize, so the cache stays within it however many +// run at once. +type reservation struct { + c *Cache + // reserved is written under c.mu; reads that find it large enough skip + // the lock. + reserved atomic.Int64 + // cut, guarded by c.mu, marks a fetch stopped because the cache could + // not make room for it. + cut bool + // ended, guarded by c.mu, marks a reservation given back. A read + // relayed after that, by a git helper the fetch left behind, reserves + // nothing. + ended bool +} + +// errReservationEnded is returned by cover once the fetch has ended. +var errReservationEnded = errors.New("fetch has ended") + +func (c *Cache) newReservation() *reservation { + return &reservation{c: c} +} + +// cover reserves space for a fetch that has received relayed bytes, +// evicting idle repositories as needed. It returns ErrCacheFull when evicting +// every idle repository would not make room, unless another fetch has just +// been cut off, whose space it waits for: one cut off waits for nothing, so +// two fetches that do not fit together do not both fail. +func (r *reservation) cover(ctx context.Context, relayed int64) error { + c := r.c + if c.opts.MaxSize <= 0 || relayed <= r.reserved.Load() { + return nil + } + var timeout <-chan time.Time + for { + c.mu.Lock() + if r.ended { + c.mu.Unlock() + return errReservationEnded + } + if r.cut { + c.mu.Unlock() + return ErrCacheFull + } + need := relayed - r.reserved.Load() + removed, total := c.evictLocked(need) + fits := total+need <= c.opts.MaxSize + var freed chan struct{} + switch { + case fits: + chunk := min(maxReserveChunk, c.opts.MaxSize/reserveChunks) + n := min(need+chunk, c.opts.MaxSize-total) + r.reserved.Add(n) + c.reserved += n + case c.cutPending > 0: + freed = c.freed + default: + r.cut = true + c.cutPending++ + } + c.mu.Unlock() + c.removeEvicted(removed) + if fits { + return nil + } + if freed == nil { + return ErrCacheFull + } + if timeout == nil { + timeout = time.After(cutWait) + } + select { + case <-freed: + case <-timeout: + c.mu.Lock() + r.cut = true + c.cutPending++ + c.mu.Unlock() + return ErrCacheFull + case <-ctx.Done(): + return ctx.Err() + } + } +} + +// settle counts what the fetch left in the repository's size and gives back +// its reservation together, so the bytes are never counted twice or not at +// all. +func (r *reservation) settle(rp *repo, size int64) { + r.c.mu.Lock() + rp.size.Store(size) + r.releaseLocked() + r.c.mu.Unlock() +} + +// release gives back the reservation of a fetch that left nothing behind. +// It may follow settle. +func (r *reservation) release() { + r.c.mu.Lock() + r.releaseLocked() + r.c.mu.Unlock() +} + +func (r *reservation) releaseLocked() { + c := r.c + r.ended = true + n := r.reserved.Swap(0) + if r.cut { + r.cut = false + c.cutPending-- + } else if n == 0 { + return + } + c.reserved -= n + close(c.freed) + c.freed = make(chan struct{}) +} diff --git a/internal/gitcache/budget_test.go b/internal/gitcache/budget_test.go new file mode 100644 index 0000000..8ef58fa --- /dev/null +++ b/internal/gitcache/budget_test.go @@ -0,0 +1,311 @@ +package gitcache + +import ( + "bytes" + "context" + "crypto/rand" + "errors" + "io" + "net/http" + "net/http/httptest" + "net/http/httputil" + "net/url" + "os" + "path/filepath" + "sync" + "testing" + "time" +) + +// cachedRepo adds a repository of the given size to the cache, still in use +// when busy. +func cachedRepo(t *testing.T, tc *testCache, name string, size int64, busy bool) *repo { + t.Helper() + rp := tc.acquire("up/" + name + ".git") + if err := os.MkdirAll(rp.dir, dirPermissions); err != nil { + t.Fatal(err) + } + rp.size.Store(size) + if !busy { + tc.release(rp) + } + return rp +} + +func (tc *testCache) budget() (reserved int64, cutPending int) { + tc.mu.Lock() + defer tc.mu.Unlock() + return tc.reserved, tc.cutPending +} + +func TestCoverEvictsIdleRepositories(t *testing.T) { + tc := newTestCache(t, "", func(o *Options) { o.MaxSize = 100 }) + old := cachedRepo(t, tc, "old", 60, false) + busy := cachedRepo(t, tc, "busy", 30, true) + + res := tc.newReservation() + if err := res.cover(t.Context(), 20); err != nil { + t.Fatal(err) + } + if fileExists(old.dir) { + t.Error("idle repository was not evicted") + } + if !fileExists(busy.dir) { + t.Error("evicted a repository in use") + } + if reserved, _ := tc.budget(); reserved < 20 { + t.Errorf("reserved %d, want at least 20", reserved) + } + res.release() + if reserved, _ := tc.budget(); reserved != 0 { + t.Errorf("reserved %d after release", reserved) + } +} + +func TestCoverCutsOffOnceOnlyRepositoriesInUseAreLeft(t *testing.T) { + tc := newTestCache(t, "", func(o *Options) { o.MaxSize = 100 }) + busy := cachedRepo(t, tc, "busy", 90, true) + + res := tc.newReservation() + if err := res.cover(t.Context(), 20); !errors.Is(err, ErrCacheFull) { + t.Fatalf("cover: %v, want ErrCacheFull", err) + } + if !fileExists(busy.dir) { + t.Error("evicted a repository in use") + } + res.release() + if reserved, cutPending := tc.budget(); reserved != 0 || cutPending != 0 { + t.Errorf("reserved %d, cut off %d after release", reserved, cutPending) + } +} + +// TestCoverKeepsIdleRepositoriesItCannotUse cuts off a fetch that would not +// fit even with every idle repository evicted, so none is. +func TestCoverKeepsIdleRepositoriesItCannotUse(t *testing.T) { + tc := newTestCache(t, "", func(o *Options) { o.MaxSize = 100 }) + idle := cachedRepo(t, tc, "idle", 5, false) + cachedRepo(t, tc, "busy", 90, true) + + res := tc.newReservation() + if err := res.cover(t.Context(), 20); !errors.Is(err, ErrCacheFull) { + t.Fatalf("cover: %v, want ErrCacheFull", err) + } + if !fileExists(idle.dir) { + t.Error("evicted an idle repository without making room") + } + res.release() +} + +// TestCoverWaitsForCutOffFetch runs two fetches that do not fit together. +// Once one is cut off, the other waits for its space instead of failing too. +func TestCoverWaitsForCutOffFetch(t *testing.T) { + tc := newTestCache(t, "", func(o *Options) { o.MaxSize = 100 }) + cachedRepo(t, tc, "busy", 40, true) + + first, second := tc.newReservation(), tc.newReservation() + if err := first.cover(t.Context(), 30); err != nil { + t.Fatal(err) + } + if err := second.cover(t.Context(), 20); err != nil { + t.Fatal(err) + } + if err := first.cover(t.Context(), 40); !errors.Is(err, ErrCacheFull) { + t.Fatalf("first: %v, want ErrCacheFull", err) + } + + done := make(chan error, 1) + go func() { done <- second.cover(context.Background(), 30) }() + select { + case err := <-done: + t.Fatalf("second did not wait for the first to be released: %v", err) + case <-time.After(100 * time.Millisecond): + } + first.release() + if err := <-done; err != nil { + t.Fatalf("second: %v", err) + } + second.release() + if reserved, cutPending := tc.budget(); reserved != 0 || cutPending != 0 { + t.Errorf("reserved %d, cut off %d after release", reserved, cutPending) + } +} + +// TestConcurrentClonesStayWithinMaxSize clones two repositories at once that +// do not fit in MaxSize together. Both are kept in use, so neither can be +// evicted: one clone succeeds, and the other is cut off without being +// marked too large. +func TestConcurrentClonesStayWithinMaxSize(t *testing.T) { + upstream := newFakeUpstream(t) + for _, name := range []string{"a", "b"} { + work := upstream.newRepo(name) + big := make([]byte, 256<<10) + _, _ = rand.Read(big) + if err := os.WriteFile(filepath.Join(work, "big.bin"), big, 0o600); err != nil { + t.Fatal(err) + } + runGit(t, work, "add", "big.bin") + runGit(t, work, "commit", "--quiet", "-m", "big") + runGit(t, work, "push", "--quiet", "origin", "main") + } + size := repoSize(t, upstream, "a") + maxSize := size * 5 / 3 + tc := newTestCache(t, upstream.server.URL, func(o *Options) { o.MaxSize = maxSize }) + for _, name := range []string{"a", "b"} { + defer tc.release(tc.acquire("up/" + name + ".git")) + } + + // Sample what the cache counts while the clones run. + var peak int64 + stop := make(chan struct{}) + sampled := make(chan struct{}) + go func() { + defer close(sampled) + for { + tc.mu.Lock() + total := tc.reserved + for _, rp := range tc.repos { + total += rp.size.Load() + } + tc.mu.Unlock() + peak = max(peak, total) + select { + case <-stop: + return + case <-time.After(100 * time.Microsecond): + } + } + }() + + // Held back, both fetches are under way before either receives a pack. + upstream.delayFetches.Store(int64(200 * time.Millisecond)) + statuses := make(map[string]int) + var mu sync.Mutex + var wg sync.WaitGroup + for _, name := range []string{"a", "b"} { + wg.Go(func() { + resp, err := http.Get(tc.url(name) + "/info/refs?service=git-upload-pack") + if err != nil { + t.Error(err) + return + } + _ = resp.Body.Close() + mu.Lock() + statuses[name] = resp.StatusCode + mu.Unlock() + }) + } + wg.Wait() + close(stop) + <-sampled + + if (statuses["a"] == http.StatusOK) == (statuses["b"] == http.StatusOK) { + t.Fatalf("statuses %v, want one 200 and one 507", statuses) + } + for name, status := range statuses { + if status != http.StatusOK && status != http.StatusInsufficientStorage { + t.Errorf("%s: status %d, want 507", name, status) + } + if tc.isTooLarge("up/" + name + ".git") { + t.Errorf("%s was marked too large", name) + } + } + // What a clone writes beyond the bytes it receives, such as its index, + // is counted only once it is measured. + if slack := size / 4; peak > maxSize+slack { + t.Errorf("cache counted %d, past max_size %d", peak, maxSize) + } + if reserved, cutPending := tc.budget(); reserved != 0 || cutPending != 0 { + t.Errorf("reserved %d, cut off %d once the clones ended", reserved, cutPending) + } + if entries, _ := os.ReadDir(tc.tmpDir()); len(entries) != 0 { + t.Errorf("left %d entries in the temporary directory", len(entries)) + } +} + +// TestCoverAfterReleaseReservesNothing has a relayed read arrive after the +// fetch gave back its reservation, as one from an orphaned git helper would. +func TestCoverAfterReleaseReservesNothing(t *testing.T) { + tc := newTestCache(t, "", func(o *Options) { o.MaxSize = 100 }) + res := tc.newReservation() + if err := res.cover(t.Context(), 10); err != nil { + t.Fatal(err) + } + res.release() + ctx, cancel := context.WithCancel(t.Context()) + cancel() + _ = res.cover(ctx, 20) + if reserved, _ := tc.budget(); reserved != 0 { + t.Errorf("reserved %d after release", reserved) + } +} + +// TestCancelledFetchStopsRelaying cancels a fetch while the upstream is +// midway through sending the pack: the upstream connection is closed, and +// nothing stays reserved when the rest arrives. +func TestCancelledFetchStopsRelaying(t *testing.T) { + upstream := newFakeUpstream(t) + upstream.newRepo("repo") + upstreamURL, err := url.Parse(upstream.server.URL) + if err != nil { + t.Fatal(err) + } + arrived := make(chan struct{}) + release := make(chan struct{}) + result := make(chan string, 1) + forward := httputil.NewSingleHostReverseProxy(upstreamURL) + front := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + body, _ := io.ReadAll(r.Body) + r.Body = io.NopCloser(bytes.NewReader(body)) + if r.Method != http.MethodPost || !bytes.Contains(body, []byte("command=fetch")) { + forward.ServeHTTP(w, r) + return + } + rec := httptest.NewRecorder() + forward.ServeHTTP(rec, r.Clone(context.Background())) + pack := rec.Body.Bytes() + w.Header().Set("Content-Type", rec.Header().Get("Content-Type")) + _, _ = w.Write(pack[:len(pack)/2]) + w.(http.Flusher).Flush() + close(arrived) + select { + case <-r.Context().Done(): + result <- "closed" + case <-release: + _, _ = w.Write(pack[len(pack)/2:]) + w.(http.Flusher).Flush() + result <- "sent" + } + })) + defer front.Close() + defer close(release) + tc := newTestCache(t, front.URL, func(o *Options) { o.MaxSize = 1 << 30 }) + + dir := t.TempDir() + if _, err := tc.run(t.Context(), dir, "init", "--quiet", "--bare"); err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithCancel(t.Context()) + res := tc.newReservation() + done := make(chan error, 1) + go func() { done <- tc.fetch(ctx, dir, front.URL+"/repo", 0, res, nil, branchesAndTags...) }() + <-arrived + waitFor(t, func() bool { reserved, _ := tc.budget(); return reserved > 0 }) + cancel() + if err := <-done; err == nil { + t.Error("cancelled fetch succeeded") + } + res.release() + + select { + case <-result: + case <-time.After(10 * time.Second): + t.Error("upstream connection still open after the fetch was cancelled") + release <- struct{}{} + <-result + } + // Give a relay still running the time to read what the upstream sent. + time.Sleep(200 * time.Millisecond) + if reserved, _ := tc.budget(); reserved != 0 { + t.Errorf("reserved %d after the fetch ended", reserved) + } +} diff --git a/internal/gitcache/cache.go b/internal/gitcache/cache.go new file mode 100644 index 0000000..54c97d0 --- /dev/null +++ b/internal/gitcache/cache.go @@ -0,0 +1,544 @@ +// Package gitcache serves Git repositories read-only over smart HTTP from a +// local cache of bare repositories, refreshed from configured upstreams. +package gitcache + +import ( + "cmp" + "context" + "crypto/sha256" + "encoding/hex" + "errors" + "fmt" + "io/fs" + "log/slog" + "net/http" + "os" + "os/exec" + "path/filepath" + "regexp" + "runtime" + "slices" + "strings" + "sync" + "sync/atomic" + "time" + + "github.com/git-pkgs/proxy/internal/metrics" +) + +const ( + // tmpDirName holds clones in progress and evicted repositories being + // deleted. Upstream names cannot start with a dot, so it cannot clash + // with an upstream's directory, and the name is specific in case + // cache_dir is shared with other data. + tmpDirName = ".gitcache-tmp" + // lockFileName is locked while the cache is open, so a second process + // given the same cache_dir fails to start instead of deleting the first + // one's clones in progress. + lockFileName = ".gitcache-lock" + // usedStampInterval limits how often a repository's last use is written + // to disk. + usedStampInterval = time.Minute + // defaultLowSpeedTime is how many seconds a git transfer may receive + // nothing before it is abandoned. Fetches run with --quiet, so the + // upstream sends nothing while it counts objects; this is far longer. + defaultLowSpeedTime = 600 + ecosystem = "git" + upstreamHashLen = 8 + checkedStamp = "proxy-checked" + usedStamp = "proxy-used" + dirPermissions = 0o750 + lockFilePermissions = 0o600 +) + +// Options configures a Cache. +type Options struct { + CacheDir string + MaxSize int64 + MaxRepoSize int64 + RefreshWait time.Duration + StaleMaxAge time.Duration + // Client makes every upstream request, including those of the git + // processes the cache runs. Redirects are never followed. + Client *http.Client + Logger *slog.Logger + // Upstreams maps each configured upstream's name to its directory in + // CacheDir, as UpstreamDir names it. Only those directories are loaded + // at startup. A directory UpstreamDir would name for one of these names + // at another URL, left by repointing the upstream, is removed. Nothing + // else in CacheDir is touched, so it may hold other data. + Upstreams map[string]string + + // refCheckTimeout, lowSpeedTime, maxRequestBody, maxUploadPacks and + // maxRefListings override their defaults in tests, and refreshWaitOver, + // when set, replaces the RefreshWait timer. + refCheckTimeout time.Duration + refreshWaitOver <-chan time.Time + lowSpeedTime int + maxRequestBody int64 + maxUploadPacks int + maxRefListings int +} + +// Cache is the Git repository cache. internal/handler serves it at /git. +type Cache struct { + opts Options + client *http.Client + logger *slog.Logger + gitPath string + dir string + lock *os.File + relay *relay + fetches chan struct{} + uploadPacks chan struct{} + refListings chan struct{} + refCheckTimeout time.Duration + lowSpeedTime int + maxRequestBody int64 + // foldCase is set where the cache directory ignores case, so keys that + // differ only in case, which name one directory, are one repository. + foldCase bool + + ctx context.Context + cancel context.CancelFunc + // refreshes counts the refreshes running, which Close waits for. + refreshes sync.WaitGroup + + mu sync.Mutex + // closed stops refreshes from starting once Close has begun. + closed bool + repos map[string]*repo + tooLarge map[string]time.Time + // overBudget records that eviction left the cache over MaxSize because + // the rest of it was in use. + overBudget bool + // reserved is the space reservations hold for fetches in progress, and + // cutPending counts those cut off and not yet released. freed is closed + // and replaced whenever a reservation gives back space or one cut off is + // released. + reserved int64 + cutPending int + freed chan struct{} + // failedWants records, by repository key and object ID, wants the + // upstream could not provide. + failedWants map[string]time.Time +} + +// repo is a cached repository, or one being cloned. users, refreshing, +// refused and the map entry itself are guarded by Cache.mu. +type repo struct { + key string + dir string + + users int + refreshing *refreshCall + // refused is the error of the last refresh when the upstream reported + // the repository missing or refused it, until a ref check succeeds. + refused error + // writes serializes git fetches into the repository. + writes chan struct{} + + size atomic.Int64 + lastUsed atomic.Int64 + lastChecked atomic.Int64 + usedWritten atomic.Int64 +} + +var errLocked = errors.New("locked by another process") + +// maxConcurrentFetches caps clones and fetches running at once. Refreshes +// outlive the requests that start them, so without a cap a client could +// start any number and hang up. +const maxConcurrentFetches = 16 + +// uploadPacksPerCPU caps the upload-pack processes building packs at once, +// so a burst of clones cannot run the proxy out of memory. Each uses one +// delta-search thread (servingConfig); twice the CPUs keeps them busy while +// some packs wait on slow clients. +const uploadPacksPerCPU = 2 + +// refListingsPerCPU caps the upload-pack processes listing refs at once, for +// info/refs and ls-refs. They build no pack and so do not wait behind +// clones, but each is still a process. +const refListingsPerCPU = 4 + +// New creates the cache, loading repositories already in CacheDir. +func New(opts Options) (*Cache, error) { + gitPath, err := exec.LookPath("git") + if err != nil { + return nil, fmt.Errorf("upstream.git needs git installed: %w", err) + } + dir, err := filepath.Abs(opts.CacheDir) + if err != nil { + return nil, err + } + if err := os.MkdirAll(dir, dirPermissions); err != nil { + return nil, err + } + lock, err := lockFile(filepath.Join(dir, lockFileName)) + if errors.Is(err, errLocked) { + return nil, fmt.Errorf("git.cache_dir %s is in use by another process; each needs its own", dir) + } + if err != nil { + return nil, fmt.Errorf("locking git.cache_dir %s: %w", dir, err) + } + logger := opts.Logger + if logger == nil { + logger = slog.New(slog.DiscardHandler) + } + // A repository larger than the whole cache would be evicted once + // released and cloned again by the next request. + if opts.MaxSize > 0 && (opts.MaxRepoSize <= 0 || opts.MaxRepoSize > opts.MaxSize) { + opts.MaxRepoSize = opts.MaxSize + } + client := *opts.Client + client.Timeout = 0 + client.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse } + + uploadPacks := uploadPacksPerCPU * runtime.GOMAXPROCS(0) + if opts.maxUploadPacks > 0 { + uploadPacks = opts.maxUploadPacks + } + refListings := refListingsPerCPU * runtime.GOMAXPROCS(0) + if opts.maxRefListings > 0 { + refListings = opts.maxRefListings + } + c := &Cache{ + opts: opts, + client: &client, + logger: logger, + gitPath: gitPath, + dir: dir, + lock: lock, + fetches: make(chan struct{}, maxConcurrentFetches), + uploadPacks: make(chan struct{}, uploadPacks), + refListings: make(chan struct{}, refListings), + refCheckTimeout: defaultRefCheckTimeout, + lowSpeedTime: defaultLowSpeedTime, + maxRequestBody: defaultMaxRequestBody, + repos: make(map[string]*repo), + tooLarge: make(map[string]time.Time), + failedWants: make(map[string]time.Time), + freed: make(chan struct{}), + foldCase: caseInsensitive(dir), + } + if opts.refCheckTimeout > 0 { + c.refCheckTimeout = opts.refCheckTimeout + } + if opts.lowSpeedTime > 0 { + c.lowSpeedTime = opts.lowSpeedTime + } + if opts.maxRequestBody > 0 { + c.maxRequestBody = opts.maxRequestBody + } + if err := c.load(); err != nil { + _ = lock.Close() + return nil, err + } + if c.relay, err = newRelay(c.client, logger); err != nil { + _ = lock.Close() + return nil, fmt.Errorf("starting git relay: %w", err) + } + c.ctx, c.cancel = context.WithCancel(context.Background()) + // Applies a lowered git.max_size straight away. + c.evict() + return c, nil +} + +// Close stops the refreshes in progress and waits for them to finish, so +// none is still writing to the cache when it returns, then stops the relay. +// Fetches by ID run on request goroutines; stop the HTTP server first. +// Closing again does nothing. +func (c *Cache) Close() error { + c.mu.Lock() + if c.closed { + c.mu.Unlock() + return nil + } + c.closed = true + c.mu.Unlock() + c.cancel() + c.refreshes.Wait() + return errors.Join(c.relay.close(), c.lock.Close()) +} + +// UpstreamDir names the top-level cache directory of the upstream called +// name at baseURL. It includes a hash of the URL, so repointing an upstream +// starts a fresh cache rather than serving the old host's repositories. +func UpstreamDir(name, baseURL string) string { + digest := sha256.Sum256([]byte(strings.TrimSuffix(baseURL, "/"))) + return name + "-" + hex.EncodeToString(digest[:])[:upstreamHashLen] +} + +func (c *Cache) tmpDir() string { + return filepath.Join(c.dir, tmpDirName) +} + +// load clears what an earlier run left in the temporary directory and +// registers the repositories already cached. +func (c *Cache) load() error { + if err := os.RemoveAll(c.tmpDir()); err != nil { + return fmt.Errorf("clearing %s: %w", c.tmpDir(), err) + } + if err := os.MkdirAll(c.tmpDir(), dirPermissions); err != nil { + return err + } + c.removeRepointed() + for _, upstreamDir := range c.opts.Upstreams { + root := filepath.Join(c.dir, upstreamDir) + err := filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error { + if err != nil || !d.IsDir() || !strings.HasSuffix(d.Name(), ".git") || path == root { + return err + } + rel, _ := filepath.Rel(c.dir, path) + rp := newRepo(c.repoKey(filepath.ToSlash(rel)), path) + rp.size.Store(dirSize(path)) + rp.lastChecked.Store(stampTime(path, checkedStamp)) + rp.lastUsed.Store(stampTime(path, usedStamp)) + rp.usedWritten.Store(rp.lastUsed.Load()) + c.repos[rp.key] = rp + return filepath.SkipDir + }) + if err != nil && !errors.Is(err, fs.ErrNotExist) { + return err + } + } + return nil +} + +// upstreamDirPattern matches a directory UpstreamDir names, capturing the +// upstream's name. +var upstreamDirPattern = regexp.MustCompile(`^(.+)-[0-9a-f]{8}$`) + +// removeRepointed removes the directories of configured upstreams at URLs +// they no longer have. Each is moved aside first, so nothing can be read +// from it half deleted. Directories of upstreams no longer configured are +// only logged: nothing else says they are the cache's. +func (c *Cache) removeRepointed() { + entries, err := os.ReadDir(c.dir) + if err != nil { + c.logger.Warn("git cache: cannot list the cache directory", "error", err) + return + } + current := make(map[string]bool, len(c.opts.Upstreams)) + for _, upstreamDir := range c.opts.Upstreams { + current[upstreamDir] = true + } + var unconfigured []string + for _, entry := range entries { + name := entry.Name() + match := upstreamDirPattern.FindStringSubmatch(name) + if !entry.IsDir() || match == nil || current[name] { + continue + } + if _, configured := c.opts.Upstreams[match[1]]; !configured { + unconfigured = append(unconfigured, name) + continue + } + trash, err := os.MkdirTemp(c.tmpDir(), "repointed-") + if err == nil { + err = os.Rename(filepath.Join(c.dir, name), filepath.Join(trash, name)) + } + if err != nil { + c.logger.Warn("git cache: failed to remove the cache of a repointed upstream", "directory", name, "error", err) + continue + } + c.logger.Info("git cache: removed the cache of a repointed upstream", "directory", name) + if err := os.RemoveAll(trash); err != nil { + c.logger.Warn("git cache: failed to delete a removed cache", "path", trash, "error", err) + } + } + if len(unconfigured) > 0 { + c.logger.Info("git cache: leaving directories that look like caches of upstreams no longer configured; delete them if they are", + "directories", unconfigured) + } +} + +// acquire returns the repository for key, counting the caller as a user +// until release, so it is not evicted while in use. +func (c *Cache) acquire(key string) *repo { + c.mu.Lock() + defer c.mu.Unlock() + rk := c.repoKey(key) + rp := c.repos[rk] + if rp == nil { + rp = newRepo(rk, filepath.Join(c.dir, filepath.FromSlash(key))) + c.repos[rk] = rp + } + rp.users++ + return rp +} + +// repoKey is the key a repository is tracked under: key itself, or key +// lowercased where the cache directory ignores case. +func (c *Cache) repoKey(key string) string { + if c.foldCase { + return strings.ToLower(key) + } + return key +} + +func (c *Cache) release(rp *repo) { + now := time.Now() + rp.lastUsed.Store(now.UnixNano()) + exists := rp.exists() + if exists && now.Sub(time.Unix(0, rp.usedWritten.Load())) >= usedStampInterval { + rp.usedWritten.Store(now.UnixNano()) + touch(rp.dir, usedStamp, now) + } + + c.mu.Lock() + rp.users-- + idle := rp.users == 0 && c.repos[rp.key] == rp + // Forget repositories that never got cloned, such as ones missing upstream. + if idle && !exists { + delete(c.repos, rp.key) + } + _, tooLarge := c.tooLarge[rp.key] + retry := tooLarge || c.overBudget + c.mu.Unlock() + if idle && exists && retry { + c.evict() + } +} + +func newRepo(key, dir string) *repo { + return &repo{key: key, dir: dir, writes: make(chan struct{}, 1)} +} + +// lockWrites waits for other fetches into the repository to finish. +func (rp *repo) lockWrites(ctx context.Context) (func(), error) { + select { + case rp.writes <- struct{}{}: + return func() { <-rp.writes }, nil + case <-ctx.Done(): + return nil, ctx.Err() + } +} + +func (rp *repo) exists() bool { + _, err := os.Stat(rp.dir) + return err == nil +} + +// evict removes repositories nobody is using: the least recently used until +// the cache fits in MaxSize, and any that could not be refreshed within +// MaxRepoSize, so the next request clones them again with only their +// branches and tags. It runs after every fetch, and when a repository it had +// to skip is released: one too large to refresh, or any while the cache is +// over MaxSize. Fetches also evict as they receive bytes (reservation.cover). +func (c *Cache) evict() { + c.mu.Lock() + removed, _ := c.evictLocked(0) + c.mu.Unlock() + c.removeEvicted(removed) +} + +// evictLocked evicts until the cache, counting reservations, has room for +// extra more bytes, and returns the evicted repositories' directories, to be +// deleted once c.mu is released, and the size left. When evicting every idle +// repository would not make that room, it evicts only as evict does. A +// repository is moved aside under the lock, so a request that comes after it +// clones it again instead of reading it while it is deleted. +func (c *Cache) evictLocked(extra int64) ([]string, int64) { + total := c.reserved + var idleTotal int64 + idle := make([]*repo, 0, len(c.repos)) + for _, rp := range c.repos { + total += rp.size.Load() + if rp.users == 0 { + idle = append(idle, rp) + idleTotal += rp.size.Load() + } + } + if total-idleTotal+extra > c.opts.MaxSize { + extra = 0 + } + slices.SortFunc(idle, func(a, b *repo) int { + return cmp.Compare(a.lastUsed.Load(), b.lastUsed.Load()) + }) + var removed []string + for _, rp := range idle { + _, marked := c.tooLarge[rp.key] + tooLarge := marked && rp.exists() + if !tooLarge && (c.opts.MaxSize <= 0 || total+extra <= c.opts.MaxSize) { + continue + } + trash, err := os.MkdirTemp(c.tmpDir(), "evicted-") + if err == nil { + err = os.Rename(rp.dir, filepath.Join(trash, "repo")) + } + if err != nil && !errors.Is(err, fs.ErrNotExist) { + c.logger.Warn("git cache: failed to evict repository", "repository", rp.key, "error", err) + continue + } + delete(c.repos, rp.key) + total -= rp.size.Load() + removed = append(removed, trash) + reason := "lru" + if tooLarge { + // The clone that replaces it enforces the limit itself. + delete(c.tooLarge, rp.key) + reason = "too_large" + } + metrics.RecordArtifactEvicted(reason, ecosystem) + c.logger.Info("git cache: evicted repository", "repository", rp.key, "size", rp.size.Load(), "reason", reason) + } + c.overBudget = c.opts.MaxSize > 0 && total > c.opts.MaxSize + return removed, total +} + +func (c *Cache) removeEvicted(removed []string) { + for _, trash := range removed { + if err := os.RemoveAll(trash); err != nil { + c.logger.Warn("git cache: failed to delete evicted repository", "path", trash, "error", err) + } + } +} + +func dirSize(dir string) int64 { + var size int64 + _ = filepath.WalkDir(dir, func(_ string, d fs.DirEntry, err error) error { + if err == nil && d.Type().IsRegular() { + if info, err := d.Info(); err == nil { + size += info.Size() + } + } + return nil + }) + return size +} + +// Stamps are empty files whose modification time records an event, so it +// survives restarts. +func stampTime(dir, name string) int64 { + info, err := os.Stat(filepath.Join(dir, name)) + if err != nil { + return 0 + } + return info.ModTime().UnixNano() +} + +func touch(dir, name string, t time.Time) { + path := filepath.Join(dir, name) + if err := os.Chtimes(path, t, t); errors.Is(err, fs.ErrNotExist) { + if f, err := os.Create(path); err == nil { + _ = f.Close() + _ = os.Chtimes(path, t, t) + } + } +} + +// caseInsensitive reports whether the file system holding dir ignores case +// in names, as macOS and Windows do by default. +func caseInsensitive(dir string) bool { + f, err := os.CreateTemp(dir, ".gitcache-case-") + if err != nil { + return false + } + name := f.Name() + _ = f.Close() + defer func() { _ = os.Remove(name) }() + _, err = os.Stat(filepath.Join(dir, strings.ToUpper(filepath.Base(name)))) + return err == nil +} diff --git a/internal/gitcache/cache_test.go b/internal/gitcache/cache_test.go new file mode 100644 index 0000000..2b2e388 --- /dev/null +++ b/internal/gitcache/cache_test.go @@ -0,0 +1,1034 @@ +package gitcache + +import ( + "context" + "crypto/rand" + "errors" + "fmt" + "maps" + "math" + "net/http" + "net/http/httptest" + "net/http/httputil" + "net/url" + "os" + "path/filepath" + "slices" + "strings" + "sync" + "testing" + "time" + + "github.com/git-pkgs/registries/safehttp" +) + +func TestCloneMatchesUpstream(t *testing.T) { + for _, version := range []string{"0", "1", "2"} { + t.Run("protocol v"+version, func(t *testing.T) { + upstream := newFakeUpstream(t) + upstream.newRepo("repo") + tc := newTestCache(t, upstream.server.URL, nil) + + clone := tc.clone(t, "repo.git", "-c", "protocol.version="+version) + + want := runGit(t, "", "ls-remote", "--heads", "--tags", upstream.bare()) + if got := runGit(t, "", "-c", "protocol.version="+version, "ls-remote", "--heads", "--tags", tc.url("repo.git")); got != want { + t.Errorf("ls-remote through the cache:\n%s\nwant:\n%s", got, want) + } + if got, want := runGit(t, clone, "rev-parse", "HEAD"), runGit(t, upstream.bare(), "rev-parse", "main"); got != want { + t.Errorf("HEAD = %s, want %s", got, want) + } + runGit(t, clone, "fsck", "--no-dangling", "--no-progress") + }) + } +} + +func TestUpstreamWithoutProtocolV2(t *testing.T) { + upstream := newFakeUpstream(t) + upstream.v0Only = true + upstream.newRepo("repo") + tc := newTestCache(t, upstream.server.URL, nil) + + clone := tc.clone(t, "repo") + if got, want := runGit(t, clone, "rev-parse", "HEAD"), runGit(t, upstream.bare(), "rev-parse", "main"); got != want { + t.Errorf("HEAD = %s, want %s", got, want) + } +} + +func TestUnchangedRepositoryIsNotFetchedAgain(t *testing.T) { + upstream := newFakeUpstream(t) + upstream.newRepo("repo") + tc := newTestCache(t, upstream.server.URL, nil) + + tc.clone(t, "repo") + fetches := upstream.gitRequests.Load() + tc.clone(t, "repo") + if got := upstream.gitRequests.Load(); got != fetches { + t.Errorf("second clone made %d upstream fetch requests, want none", got-fetches) + } +} + +func TestPushedCommitIsServedOnNextClone(t *testing.T) { + upstream := newFakeUpstream(t) + work := upstream.newRepo("repo") + tc := newTestCache(t, upstream.server.URL, nil) + existing := tc.clone(t, "repo") + + head := upstream.commit(work, "second") + runGit(t, work, "push", "--quiet", "origin", "main") + + if got := runGit(t, tc.clone(t, "repo"), "rev-parse", "HEAD"); got != head { + t.Errorf("clone after push: HEAD = %s, want %s", got, head) + } + runGit(t, existing, "pull", "--quiet", "--ff-only") + if got := runGit(t, existing, "rev-parse", "HEAD"); got != head { + t.Errorf("pull after push: HEAD = %s, want %s", got, head) + } + if got := runGit(t, tc.clone(t, "repo", "--depth=1"), "rev-list", "--count", "HEAD"); got != "1" { + t.Errorf("shallow clone has %s commits, want 1", got) + } +} + +func TestOnlyBranchesAndTagsAreCachedAndPruned(t *testing.T) { + upstream := newFakeUpstream(t) + work := upstream.newRepo("repo") + runGit(t, work, "push", "--quiet", "origin", "main:refs/changes/01/1/1", "main:refs/heads/gone", "main:refs/tags/gone") + tc := newTestCache(t, upstream.server.URL, nil) + tc.clone(t, "repo") + + refs := tc.cachedRefs(t) + if strings.Contains(refs, "refs/changes/") { + t.Errorf("cached refs/changes:\n%s", refs) + } + if !strings.Contains(refs, "refs/heads/gone") || !strings.Contains(refs, "refs/tags/gone") { + t.Fatalf("branch and tag not cached:\n%s", refs) + } + + runGit(t, work, "push", "--quiet", "origin", ":refs/heads/gone", ":refs/tags/gone") + tc.clone(t, "repo") + if refs := tc.cachedRefs(t); strings.Contains(refs, "gone") { + t.Errorf("deleted branch or tag still cached:\n%s", refs) + } + + // Gerrit advertises a ref per patch set, so asking for every ref would + // list hundreds of thousands for a large repository. + bodies := upstream.lsRefsBodies() + if len(bodies) == 0 { + t.Fatal("no ls-refs request reached the upstream") + } + for _, body := range bodies { + if !strings.Contains(body, "ref-prefix refs/heads/") || !strings.Contains(body, "ref-prefix refs/tags/") { + t.Errorf("ls-refs asked for every ref, want branches and tags only:\n%q", body) + } + } +} + +func TestDefaultBranchChangeIsFollowed(t *testing.T) { + upstream := newFakeUpstream(t) + work := upstream.newRepo("repo") + tc := newTestCache(t, upstream.server.URL, nil) + tc.clone(t, "repo") + + runGit(t, work, "checkout", "--quiet", "-b", "trunk") + head := upstream.commit(work, "on trunk") + runGit(t, work, "push", "--quiet", "origin", "trunk") + runGit(t, upstream.bare(), "symbolic-ref", "HEAD", "refs/heads/trunk") + + clone := tc.clone(t, "repo") + if got := runGit(t, clone, "rev-parse", "HEAD"); got != head { + t.Errorf("HEAD = %s, want trunk's %s", got, head) + } +} + +func TestConcurrentColdClonesShareOneFetch(t *testing.T) { + upstream := newFakeUpstream(t) + upstream.newRepo("repo") + tc := newTestCache(t, upstream.server.URL, nil) + + release := upstream.holdRequests() + var wg sync.WaitGroup + for range 8 { + wg.Go(func() { + dir := filepath.Join(t.TempDir(), "clone") + if out, err := tryGit(t, "", "clone", "--quiet", tc.url("repo"), dir); err != nil { + t.Errorf("clone: %v\n%s", err, out) + } + }) + } + time.Sleep(200 * time.Millisecond) + release() + wg.Wait() + + if got := upstream.gitSessions.Load(); got != 1 { + t.Errorf("upstream saw %d fetches, want 1", got) + } +} + +func TestMissingRepositoryLeavesNothingBehind(t *testing.T) { + upstream := newFakeUpstream(t) + tc := newTestCache(t, upstream.server.URL, nil) + + resp, err := http.Get(tc.url("missing") + "/info/refs?service=git-upload-pack") + if err != nil { + t.Fatal(err) + } + _ = resp.Body.Close() + if resp.StatusCode != http.StatusNotFound { + t.Errorf("status %d, want 404", resp.StatusCode) + } + waitForRepos(t, tc.Cache, 0) + if _, err := os.Stat(filepath.Join(tc.dir, "up", "missing.git")); !os.IsNotExist(err) { + t.Errorf("repository directory left behind: %v", err) + } +} + +func TestStaleCopyServedOnlyWithinStaleMaxAge(t *testing.T) { + upstream := newFakeUpstream(t) + upstream.newRepo("repo") + tc := newTestCache(t, upstream.server.URL, nil) + tc.clone(t, "repo") + + upstream.status.Store(http.StatusServiceUnavailable) + tc.clone(t, "repo") + + waitIdle(t, tc.Cache) + rp := tc.acquire("up/repo.git") + rp.lastChecked.Store(time.Now().Add(-2 * time.Hour).UnixNano()) + tc.release(rp) + if out, err := tryGit(t, "", "ls-remote", tc.url("repo")); err == nil { + t.Errorf("served a copy older than stale_max_age:\n%s", out) + } +} + +func TestRefusedRefreshIsNotServedStale(t *testing.T) { + for _, status := range []int{http.StatusUnauthorized, http.StatusForbidden, http.StatusNotFound, http.StatusMovedPermanently} { + t.Run(fmt.Sprint(status), func(t *testing.T) { + upstream := newFakeUpstream(t) + upstream.newRepo("repo") + tc := newTestCache(t, upstream.server.URL, nil) + tc.clone(t, "repo") + + upstream.status.Store(int32(status)) + if out, err := tryGit(t, "", "ls-remote", tc.url("repo")); err == nil { + t.Errorf("served the cached copy after status %d:\n%s", status, out) + } + }) + } +} + +func TestSlowUpstreamServesCachedCopyAfterRefreshWait(t *testing.T) { + upstream := newFakeUpstream(t) + work := upstream.newRepo("repo") + tc := newTestCache(t, upstream.server.URL, func(o *Options) { o.RefreshWait = 100 * time.Millisecond }) + old := runGit(t, tc.clone(t, "repo"), "rev-parse", "HEAD") + head := upstream.commit(work, "second") + runGit(t, work, "push", "--quiet", "origin", "main") + + release := upstream.holdRequests() + defer release() + if got := runGit(t, tc.clone(t, "repo"), "rev-parse", "HEAD"); got != old { + t.Errorf("HEAD = %s, want the cached %s", got, old) + } + release() + waitFor(t, func() bool { return strings.Contains(tc.cachedRefs(t), head) }) +} + +// TestSlowFetchAfterPushIsWaitedFor has the upstream answer the ref check at +// once and the fetch after a push still run when RefreshWait is over: a +// clone still gets the pushed commit. +func TestSlowFetchAfterPushIsWaitedFor(t *testing.T) { + upstream := newFakeUpstream(t) + work := upstream.newRepo("repo") + waitOver := make(chan time.Time) + tc := newTestCache(t, upstream.server.URL, func(o *Options) { o.refreshWaitOver = waitOver }) + tc.clone(t, "repo") + head := upstream.commit(work, "second") + runGit(t, work, "push", "--quiet", "origin", "main") + + arrived, release := upstream.holdFetches() + defer release() + dir := filepath.Join(t.TempDir(), "clone") + cloned := make(chan error, 1) + go func() { + out, err := tryGit(t, "", "clone", "--quiet", tc.url("repo"), dir) + if err != nil { + err = fmt.Errorf("%w\n%s", err, out) + } + cloned <- err + }() + // The fetch starts only after the check found the push. + select { + case <-arrived: + case err := <-cloned: + t.Fatalf("clone finished before the fetch started: %v", err) + case <-time.After(30 * time.Second): + t.Fatal("the fetch after the push never reached the upstream") + } + close(waitOver) + release() + if err := <-cloned; err != nil { + t.Fatal(err) + } + if got := runGit(t, dir, "rev-parse", "HEAD"); got != head { + t.Errorf("HEAD = %s, want the pushed %s", got, head) + } +} + +// TestStalledFetchAfterPushServesCachedCopy has the fetch after a push +// stall: once it is abandoned, the clone gets the cached copy. +func TestStalledFetchAfterPushServesCachedCopy(t *testing.T) { + upstream := newFakeUpstream(t) + work := upstream.newRepo("repo") + tc := newTestCache(t, upstream.server.URL, func(o *Options) { + o.RefreshWait = 100 * time.Millisecond + o.lowSpeedTime = 1 + }) + old := runGit(t, tc.clone(t, "repo"), "rev-parse", "HEAD") + upstream.commit(work, "second") + runGit(t, work, "push", "--quiet", "origin", "main") + + upstream.stallFetches.Store(true) + if got := runGit(t, tc.clone(t, "repo"), "rev-parse", "HEAD"); got != old { + t.Errorf("HEAD = %s, want the cached %s", got, old) + } +} + +func TestUpstreamCredentialsReachEveryUpstreamRequest(t *testing.T) { + upstream := newFakeUpstream(t) + upstream.requireAuth = "Bearer secret" + upstream.newRepo("repo") + client := &http.Client{Transport: headerTransport{"Authorization", "Bearer secret"}} + tc := newTestCache(t, upstream.server.URL, func(o *Options) { o.Client = client }) + + tc.clone(t, "repo") + if got := upstream.unauthed.Load(); got != 0 { + t.Errorf("%d upstream requests lacked credentials", got) + } + if upstream.gitRequests.Load() == 0 { + t.Error("no fetch went through the relay") + } +} + +type headerTransport struct{ name, value string } + +func (h headerTransport) RoundTrip(r *http.Request) (*http.Response, error) { + r = r.Clone(r.Context()) + r.Header.Set(h.name, h.value) + return http.DefaultTransport.RoundTrip(r) +} + +// TestUpstreamAddressChecksApplyToGit uses a client that refuses loopback +// addresses, as the proxy's does by default. git must not reach the loopback +// upstream around it, whether the ref check or only git's fetch is refused. +func TestUpstreamAddressChecksApplyToGit(t *testing.T) { + blocked := safehttp.New(nil, safehttp.Options{}) + for name, client := range map[string]*http.Client{ + "every request": blocked, + "git's fetch": {Transport: gitOnlyTransport{blocked.Transport}}, + } { + t.Run(name, func(t *testing.T) { + upstream := newFakeUpstream(t) + upstream.newRepo("repo") + tc := newTestCache(t, upstream.server.URL, func(o *Options) { o.Client = client }) + + if out, err := tryGit(t, "", "ls-remote", tc.url("repo")); err == nil { + t.Fatalf("clone through a blocked upstream succeeded:\n%s", out) + } + if got := upstream.gitRequests.Load(); got != 0 { + t.Errorf("git reached the upstream with %d requests", got) + } + }) + } +} + +// gitOnlyTransport sends the cache's own ref checks with the default +// transport, and git's relayed requests with next. +type gitOnlyTransport struct{ next http.RoundTripper } + +func (g gitOnlyTransport) RoundTrip(r *http.Request) (*http.Response, error) { + if r.UserAgent() == gitUserAgent { + return http.DefaultTransport.RoundTrip(r) + } + return g.next.RoundTrip(r) +} + +// TestRedirectIsNotFollowed redirects the ref check, then only git's fetch. +func TestRedirectIsNotFollowed(t *testing.T) { + for _, redirectRefCheck := range []bool{true, false} { + t.Run(fmt.Sprint("ref check redirected: ", redirectRefCheck), func(t *testing.T) { + target := newFakeUpstream(t) + target.newRepo("repo") + targetURL, _ := url.Parse(target.server.URL) + passThrough := httputil.NewSingleHostReverseProxy(targetURL) + redirect := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.UserAgent() == gitUserAgent && !redirectRefCheck { + passThrough.ServeHTTP(w, r) + return + } + http.Redirect(w, r, target.server.URL+r.URL.RequestURI(), http.StatusFound) + })) + defer redirect.Close() + tc := newTestCache(t, redirect.URL, nil) + + if out, err := tryGit(t, "", "ls-remote", tc.url("repo")); err == nil { + t.Fatalf("followed a redirect:\n%s", out) + } + if got := target.gitRequests.Load(); got != 0 { + t.Errorf("redirect target received %d requests from git", got) + } + }) + } +} + +func TestRepositoryOverMaxRepoSizeIsRefused(t *testing.T) { + upstream := newFakeUpstream(t) + work := upstream.newRepo("repo") + big := make([]byte, 256<<10) + _, _ = rand.Read(big) + if err := os.WriteFile(filepath.Join(work, "big.bin"), big, 0o600); err != nil { + t.Fatal(err) + } + runGit(t, work, "add", "big.bin") + runGit(t, work, "commit", "--quiet", "-m", "big") + runGit(t, work, "push", "--quiet", "origin", "main") + + // max_size caps max_repo_size. + for name, configure := range map[string]func(*Options){ + "max_repo_size": func(o *Options) { o.MaxRepoSize = 64 << 10 }, + "max_size": func(o *Options) { o.MaxSize = 64 << 10 }, + } { + t.Run(name, func(t *testing.T) { + tc := newTestCache(t, upstream.server.URL, configure) + + resp, err := http.Get(tc.url("repo") + "/info/refs?service=git-upload-pack") + if err != nil { + t.Fatal(err) + } + _ = resp.Body.Close() + if resp.StatusCode != http.StatusInsufficientStorage { + t.Errorf("status %d, want 507", resp.StatusCode) + } + waitForRepos(t, tc.Cache, 0) + if entries, _ := os.ReadDir(tc.tmpDir()); len(entries) != 0 { + t.Errorf("left %d entries in the temporary directory", len(entries)) + } + + requests := upstream.requests.Load() + if out, err := tryGit(t, "", "ls-remote", tc.url("repo")); err == nil { + t.Errorf("second attempt succeeded:\n%s", out) + } + if got := upstream.requests.Load(); got != requests { + t.Errorf("second attempt made %d upstream requests, want none", got-requests) + } + }) + } +} + +// TestEvictionRemovesLeastRecentlyUsedIdleRepositories makes the least +// recently used repository one a request is reading, so the next one is +// evicted instead. +func TestEvictionRemovesLeastRecentlyUsedIdleRepositories(t *testing.T) { + upstream := newFakeUpstream(t) + for _, name := range []string{"old", "busy", "new"} { + upstream.newRepo(name) + } + size := repoSize(t, upstream, "new") + tc := newTestCache(t, upstream.server.URL, func(o *Options) { o.MaxSize = 2*size + size/2 }) + + tc.clone(t, "busy") + busy := tc.acquire("up/busy.git") + defer tc.release(busy) + busy.lastUsed.Store(0) + tc.clone(t, "old") + waitFor(t, func() bool { return tc.usersOf("up/old.git") == 0 }) + tc.repo("up/old.git").lastUsed.Store(1) + + // The third clone takes the cache past MaxSize. + tc.clone(t, "new") + waitFor(t, func() bool { return !fileExists(filepath.Join(tc.dir, "up", "old.git")) }) + for _, name := range []string{"busy", "new"} { + if !fileExists(filepath.Join(tc.dir, "up", name+".git")) { + t.Errorf("%s was evicted", name) + } + } + tc.clone(t, "old") +} + +// repoSize is the size a cache gives repository name once cloned. +func repoSize(t *testing.T, upstream *fakeUpstream, name string) int64 { + t.Helper() + probe := newTestCache(t, upstream.server.URL, nil) + probe.clone(t, name) + return probe.repo("up/" + name + ".git").size.Load() +} + +func TestNewLoadsCachedRepositories(t *testing.T) { + upstream := newFakeUpstream(t) + upstream.newRepo("repo") + tc := newTestCache(t, upstream.server.URL, nil) + tc.clone(t, "repo") + if err := os.MkdirAll(filepath.Join(tc.tmpDir(), "clone-leftover"), 0o750); err != nil { + t.Fatal(err) + } + if err := tc.Close(); err != nil { + t.Fatal(err) + } + + reloaded, err := New(Options{ + Upstreams: map[string]string{"up": "up"}, + CacheDir: tc.dir, + StaleMaxAge: time.Hour, + Client: &http.Client{}, + }) + if err != nil { + t.Fatal(err) + } + defer func() { _ = reloaded.Close() }() + + rp := reloaded.repos["up/repo.git"] // nothing else uses reloaded yet + if rp == nil || rp.size.Load() == 0 || rp.lastChecked.Load() == 0 { + t.Fatalf("repository not loaded: %+v", rp) + } + if entries, _ := os.ReadDir(reloaded.tmpDir()); len(entries) != 0 { + t.Errorf("temporary directory not cleared: %v", entries) + } +} + +func waitForRepos(t *testing.T, c *Cache, n int) { + t.Helper() + waitFor(t, func() bool { + c.mu.Lock() + defer c.mu.Unlock() + return len(c.repos) == n + }) +} + +func waitFor(t *testing.T, cond func() bool) { + t.Helper() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + for !cond() { + select { + case <-ctx.Done(): + t.Fatal("condition not met in time") + case <-time.After(20 * time.Millisecond): + } + } +} + +// TestRewoundCacheIsBroughtBackInLine changes the cache behind the upstream's +// back, so it only matches again if the next request refreshes branches and +// tags and prunes what the upstream does not have. +func TestRewoundCacheIsBroughtBackInLine(t *testing.T) { + upstream := newFakeUpstream(t) + work := upstream.newRepo("repo") + upstream.commit(work, "second") + runGit(t, work, "push", "--quiet", "origin", "main") + tc := newTestCache(t, upstream.server.URL, nil) + tc.clone(t, "repo") + + cached := filepath.Join(tc.dir, "up", "repo.git") + runGit(t, cached, "update-ref", "refs/heads/main", "main~1") + runGit(t, cached, "update-ref", "refs/heads/extra", "main") + runGit(t, cached, "tag", "extra", "main") + + want := runGit(t, "", "ls-remote", "--heads", "--tags", upstream.bare()) + if got := runGit(t, "", "ls-remote", "--heads", "--tags", tc.url("repo")); got != want { + t.Errorf("ls-remote through the cache:\n%s\nwant:\n%s", got, want) + } +} + +// TestConcurrentWarmClonesDuringRefresh serves clones from the cache while a +// fetch writes to it. +func TestConcurrentWarmClonesDuringRefresh(t *testing.T) { + upstream := newFakeUpstream(t) + work := upstream.newRepo("repo") + tc := newTestCache(t, upstream.server.URL, func(o *Options) { o.RefreshWait = time.Millisecond }) + old := runGit(t, tc.clone(t, "repo"), "rev-parse", "HEAD") + head := upstream.commit(work, "second") + runGit(t, work, "push", "--quiet", "origin", "main") + + var wg sync.WaitGroup + for range 8 { + wg.Go(func() { + dir := filepath.Join(t.TempDir(), "clone") + if out, err := tryGit(t, "", "clone", "--quiet", tc.url("repo"), dir); err != nil { + t.Errorf("clone: %v\n%s", err, out) + return + } + if got := runGit(t, dir, "rev-parse", "HEAD"); got != old && got != head { + t.Errorf("HEAD = %s, want %s or %s", got, old, head) + } + runGit(t, dir, "fsck", "--no-dangling", "--no-progress") + }) + } + wg.Wait() + waitFor(t, func() bool { return strings.Contains(tc.cachedRefs(t), head) }) +} + +// TestStalledRefCheckFailsInsteadOfHanging has the upstream send headers and +// then nothing, as a broken load balancer might. +func TestStalledRefCheckFailsInsteadOfHanging(t *testing.T) { + stall := make(chan struct{}) + defer close(stall) + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", advertisementType) + w.WriteHeader(http.StatusOK) + _ = http.NewResponseController(w).Flush() + select { + case <-stall: + case <-r.Context().Done(): + } + })) + defer upstream.Close() + tc := newTestCache(t, upstream.URL, func(o *Options) { o.refCheckTimeout = 200 * time.Millisecond }) + + start := time.Now() + if out, err := tryGit(t, "", "ls-remote", tc.url("repo")); err == nil { + t.Fatalf("ls-remote succeeded:\n%s", out) + } + if elapsed := time.Since(start); elapsed > 10*time.Second { + t.Errorf("took %s to fail", elapsed) + } +} + +// TestStalledFetchFailsInsteadOfHanging has the upstream answer the ref check +// but never git's fetch, as a connection that stalls mid-pack would. +func TestStalledFetchFailsInsteadOfHanging(t *testing.T) { + upstream := newFakeUpstream(t) + upstream.newRepo("repo") + upstream.stallFetches.Store(true) + tc := newTestCache(t, upstream.server.URL, func(o *Options) { o.lowSpeedTime = 1 }) + + start := time.Now() + if out, err := tryGit(t, "", "ls-remote", tc.url("repo")); err == nil { + t.Fatalf("ls-remote succeeded:\n%s", out) + } + if elapsed := time.Since(start); elapsed > 20*time.Second { + t.Errorf("took %s to fail", elapsed) + } +} + +// TestFetchEvictsToMaxSize checks eviction runs on its own once a fetch has +// grown the cache past MaxSize. +func TestFetchEvictsToMaxSize(t *testing.T) { + upstream := newFakeUpstream(t) + upstream.newRepo("first") + upstream.newRepo("second") + size := repoSize(t, upstream, "first") + + tc := newTestCache(t, upstream.server.URL, func(o *Options) { o.MaxSize = size + size/2 }) + tc.clone(t, "first") + waitIdle(t, tc.Cache) + tc.clone(t, "second") + waitFor(t, func() bool { return !fileExists(filepath.Join(tc.dir, "up", "first.git")) }) + if !fileExists(filepath.Join(tc.dir, "up", "second.git")) { + t.Error("evicted the repository just fetched") + } +} + +// TestReleaseEvictsWhatEvictionHadToSkip fills the cache past MaxSize while +// every repository is in use, so eviction after the fetch can remove none. +// The first release brings the cache back within MaxSize. +func TestReleaseEvictsWhatEvictionHadToSkip(t *testing.T) { + upstream := newFakeUpstream(t) + upstream.newRepo("first") + upstream.newRepo("second") + size := repoSize(t, upstream, "first") + + tc := newTestCache(t, upstream.server.URL, func(o *Options) { o.MaxSize = size + size/2 }) + first := tc.acquire("up/first.git") + tc.clone(t, "first") + second := tc.acquire("up/second.git") + defer tc.release(second) + tc.clone(t, "second") + waitFor(t, func() bool { + tc.mu.Lock() + defer tc.mu.Unlock() + return tc.overBudget + }) + + tc.release(first) + if fileExists(first.dir) { + t.Error("first is still cached once released") + } + if !fileExists(second.dir) { + t.Error("evicted second while in use") + } + tc.clone(t, "second") +} + +// TestNewRemovesRepointedUpstreams starts a cache whose directory holds an +// upstream's cache at its old URL, and one of an upstream no longer +// configured. Only the first is known to be the cache's to remove. +func TestNewRemovesRepointedUpstreams(t *testing.T) { + dir := t.TempDir() + current := UpstreamDir("up", "https://new.example") + repointed := UpstreamDir("up", "https://old.example") + unconfigured := UpstreamDir("gone", "https://gone.example") + // Named after a configured upstream's name, but another upstream's. + longer := UpstreamDir("up-api", "https://api.example") + for _, name := range []string{current, repointed, unconfigured, longer} { + runGit(t, "", "init", "--quiet", "--bare", filepath.Join(dir, name, "repo.git")) + } + c, err := New(Options{ + CacheDir: dir, + StaleMaxAge: time.Hour, + Client: &http.Client{}, + Upstreams: map[string]string{"up": current}, + }) + if err != nil { + t.Fatal(err) + } + defer func() { _ = c.Close() }() + + for name, want := range map[string]bool{current: true, repointed: false, unconfigured: true, longer: true} { + if got := fileExists(filepath.Join(dir, name)); got != want { + t.Errorf("%s present = %v, want %v", name, got, want) + } + } + if keys := slices.Collect(maps.Keys(c.repos)); len(keys) != 1 || keys[0] != current+"/repo.git" { + t.Errorf("loaded %v, want only %s/repo.git", keys, current) + } +} + +// TestCacheDirSharedWithOtherData points the cache at a directory that also +// holds an artifact store and a database, as git.cache_dir: ./cache would. +func TestCacheDirSharedWithOtherData(t *testing.T) { + dir := t.TempDir() + _ = os.MkdirAll(filepath.Join(dir, "artifacts", "npm"), 0o750) + _ = os.WriteFile(filepath.Join(dir, "artifacts", "npm", "pkg.tgz"), []byte("x"), 0o600) + _ = os.WriteFile(filepath.Join(dir, "proxy.db"), []byte("db"), 0o600) + runGit(t, "", "init", "--quiet", "--bare", filepath.Join(dir, "artifacts", "foo", "bar.git")) + c, err := New(Options{ + CacheDir: dir, + Client: &http.Client{}, + Upstreams: map[string]string{"github": UpstreamDir("github", "https://github.com")}, + }) + if err != nil { + t.Fatal(err) + } + defer func() { _ = c.Close() }() + for _, p := range []string{"artifacts/npm/pkg.tgz", "proxy.db", "artifacts/foo/bar.git"} { + if _, err := os.Stat(filepath.Join(dir, p)); err != nil { + t.Errorf("%s was deleted at startup: %v", p, err) + } + } + if len(c.repos) != 0 { + t.Errorf("loaded %v from outside the upstream directories", slices.Collect(maps.Keys(c.repos))) + } +} + +// TestCloseWaitsForRefreshes closes the cache while a clone is held up +// upstream. When Close returns, the clone must have finished, temporary +// directory included, so nothing is left writing to the cache. +func TestCloseWaitsForRefreshes(t *testing.T) { + upstream := newFakeUpstream(t) + upstream.newRepo("repo") + upstream.stallFetches.Store(true) + tc := newTestCache(t, upstream.server.URL, nil) + clones := func() []string { + names, _ := filepath.Glob(filepath.Join(tc.tmpDir(), "clone-*")) + return names + } + + go func() { _, _ = tryGit(t, "", "ls-remote", tc.url("repo")) }() + waitFor(t, func() bool { return len(clones()) > 0 }) + if err := tc.Close(); err != nil { + t.Fatal(err) + } + if left := clones(); len(left) != 0 { + t.Errorf("Close returned with the clone still running: %v", left) + } + + before := upstream.requests.Load() + if _, err := tc.Open(context.Background(), "up/other.git", upstream.server.URL+"/other", OpenOptions{}); !errors.Is(err, errClosed) { + t.Errorf("Open after Close: %v, want errClosed", err) + } + if got := upstream.requests.Load() - before; got != 0 { + t.Errorf("Open after Close made %d upstream requests", got) + } +} + +// TestCacheDirInUse opens a second cache on a directory one already uses, +// as a second pod on a shared volume would, then again once the first has +// closed. +func TestCacheDirInUse(t *testing.T) { + dir := t.TempDir() + open := func() (*Cache, error) { return New(Options{CacheDir: dir, Client: &http.Client{}}) } + first, err := open() + if err != nil { + t.Fatal(err) + } + if second, err := open(); err == nil { + _ = second.Close() + t.Fatal("a second cache opened on the same directory") + } else if !strings.Contains(err.Error(), "in use by another process") { + t.Errorf("error = %v, want one naming the directory as in use", err) + } + if err := first.Close(); err != nil { + t.Fatal(err) + } + again, err := open() + if err != nil { + t.Fatalf("reopening after Close: %v", err) + } + _ = again.Close() +} + +// TestCloseTwice checks closing again does nothing, as a cleanup that also +// closes the cache may. +func TestCloseTwice(t *testing.T) { + c, err := New(Options{CacheDir: t.TempDir(), Client: &http.Client{}}) + if err != nil { + t.Fatal(err) + } + if err := errors.Join(c.Close(), c.Close()); err != nil { + t.Errorf("closing twice: %v", err) + } +} + +// lsRefs sends a protocol v2 ls-refs request for "repo" straight to +// git-upload-pack, as a client may without asking for info/refs first, and +// returns the status. +func (tc *testCache) lsRefs(t *testing.T) int { + t.Helper() + body := pktLine("command=ls-refs\n") + pktDelim + pktLine("peel\n") + pktFlush + req, err := http.NewRequestWithContext(t.Context(), http.MethodPost, tc.url("repo")+"/git-upload-pack", strings.NewReader(body)) + if err != nil { + t.Fatal(err) + } + req.Header.Set("Content-Type", requestType) + req.Header.Set("Git-Protocol", "version=2") + resp, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatal(err) + } + _ = resp.Body.Close() + return resp.StatusCode +} + +// TestUploadPackChecksCopyPastStaleMaxAge sends upload-pack requests without +// info/refs: a copy not checked within stale_max_age is checked first. +func TestUploadPackChecksCopyPastStaleMaxAge(t *testing.T) { + upstream := newFakeUpstream(t) + upstream.newRepo("repo") + tc := newTestCache(t, upstream.server.URL, nil) + tc.clone(t, "repo") + if status := tc.lsRefs(t); status != http.StatusOK { + t.Fatalf("ls-refs on a fresh copy: status %d", status) + } + + waitIdle(t, tc.Cache) + rp := tc.acquire("up/repo.git") + rp.lastChecked.Store(time.Now().Add(-2 * time.Hour).UnixNano()) + tc.release(rp) + upstream.status.Store(http.StatusNotFound) + if status := tc.lsRefs(t); status == http.StatusOK { + t.Errorf("served a copy older than stale_max_age to ls-refs") + } +} + +// TestUploadPackRefusedAfterUpstreamRefusal has the upstream refuse a +// refresh: upload-pack requests are refused too until a check succeeds. +func TestUploadPackRefusedAfterUpstreamRefusal(t *testing.T) { + upstream := newFakeUpstream(t) + upstream.newRepo("repo") + tc := newTestCache(t, upstream.server.URL, nil) + tc.clone(t, "repo") + + upstream.status.Store(http.StatusForbidden) + if out, err := tryGit(t, "", "ls-remote", tc.url("repo")); err == nil { + t.Fatalf("served the cached copy after 403:\n%s", out) + } + if status := tc.lsRefs(t); status == http.StatusOK { + t.Errorf("ls-refs served after the upstream refused the repository") + } + + upstream.status.Store(0) + tc.clone(t, "repo") + if status := tc.lsRefs(t); status != http.StatusOK { + t.Errorf("ls-refs after a successful check: status %d", status) + } +} + +// TestCloneChecksUpstreamOnce clones with a stale_max_age of 0: the +// upload-pack requests after info/refs do not check the upstream again. +func TestCloneChecksUpstreamOnce(t *testing.T) { + upstream := newFakeUpstream(t) + upstream.newRepo("repo") + tc := newTestCache(t, upstream.server.URL, func(o *Options) { o.StaleMaxAge = 0 }) + tc.clone(t, "repo") + waitIdle(t, tc.Cache) + + checks := func() int32 { return upstream.requests.Load() - upstream.gitRequests.Load() } + before := checks() + resp, err := http.Get(tc.url("repo") + "/info/refs?service=git-upload-pack") + if err != nil { + t.Fatal(err) + } + _ = resp.Body.Close() + perCheck := checks() - before + + before = checks() + tc.clone(t, "repo") + if got := checks() - before; got != perCheck { + t.Errorf("clone made %d upstream check requests, want %d", got, perCheck) + } +} + +// TestInfoRefsRefusedWhileRefusalStands checks that once the upstream +// refused a repository, a later check that runs past RefreshWait, which +// would otherwise serve the cached copy, doesn't advertise its refs. +func TestInfoRefsRefusedWhileRefusalStands(t *testing.T) { + upstream := newFakeUpstream(t) + upstream.newRepo("repo") + tc := newTestCache(t, upstream.server.URL, func(o *Options) { o.RefreshWait = 100 * time.Millisecond }) + tc.clone(t, "repo") + + upstream.status.Store(http.StatusForbidden) + if out, err := tryGit(t, "", "ls-remote", tc.url("repo")); err == nil { + t.Fatalf("served the cached copy after 403:\n%s", out) + } + upstream.status.Store(0) + release := upstream.holdRequests() + defer release() + // Protocol v0 advertises the refs in the info/refs response itself. + if out, err := tryGit(t, "", "-c", "protocol.version=0", "ls-remote", tc.url("repo")); err == nil { + t.Errorf("advertised refs while the refusal stands:\n%s", out) + } +} + +// refuse has the upstream refuse "repo" with a 403 and checks that the +// cached copy is no longer served. +func (tc *testCache) refuse(t *testing.T, upstream *fakeUpstream) { + t.Helper() + upstream.status.Store(http.StatusForbidden) + if out, err := tryGit(t, "", "ls-remote", tc.url("repo")); err == nil { + t.Fatalf("served the cached copy after 403:\n%s", out) + } + upstream.status.Store(0) +} + +// TestUploadPackClearsRefusal has a client that only sends upload-pack +// requests: once the upstream allows the repository again, it is served. +func TestUploadPackClearsRefusal(t *testing.T) { + upstream := newFakeUpstream(t) + upstream.newRepo("repo") + tc := newTestCache(t, upstream.server.URL, nil) + tc.clone(t, "repo") + tc.refuse(t, upstream) + + if status := tc.lsRefs(t); status != http.StatusOK { + t.Errorf("ls-refs after the upstream allowed the repository again: status %d", status) + } +} + +// TestRefCheckClearsRefusal has the upstream list the refs again after a +// refusal but fail the fetch that follows: the check alone clears the +// refusal, and the cached copy is served. +func TestRefCheckClearsRefusal(t *testing.T) { + upstream := newFakeUpstream(t) + work := upstream.newRepo("repo") + tc := newTestCache(t, upstream.server.URL, nil) + tc.clone(t, "repo") + tc.refuse(t, upstream) + + upstream.commit(work, "second") + runGit(t, work, "push", "--quiet", "origin", "main") + upstream.fetchStatus.Store(http.StatusInternalServerError) + if out, err := tryGit(t, "", "ls-remote", tc.url("repo")); err != nil { + t.Errorf("cached copy refused after the upstream listed its refs: %v\n%s", err, out) + } + if status := tc.lsRefs(t); status != http.StatusOK { + t.Errorf("ls-refs after the upstream listed its refs: status %d", status) + } +} + +// TestHugeStaleMaxAgeUploadPackChecksNothing sets stale_max_age near the +// largest duration: upload-pack requests on a fresh copy do not check the +// upstream. +func TestHugeStaleMaxAgeUploadPackChecksNothing(t *testing.T) { + upstream := newFakeUpstream(t) + upstream.newRepo("repo") + tc := newTestCache(t, upstream.server.URL, func(o *Options) { o.StaleMaxAge = math.MaxInt64 - time.Second }) + tc.clone(t, "repo") + waitIdle(t, tc.Cache) + + before := upstream.requests.Load() + if status := tc.lsRefs(t); status != http.StatusOK { + t.Fatalf("ls-refs: status %d", status) + } + waitIdle(t, tc.Cache) + if got := upstream.requests.Load() - before; got != 0 { + t.Errorf("ls-refs made %d upstream requests, want 0", got) + } +} + +// TestFetchRedirectRefusesRepository has the upstream list the refs but +// redirect the fetch that follows: the repository is refused, as when the +// ref listing is redirected. +func TestFetchRedirectRefusesRepository(t *testing.T) { + upstream := newFakeUpstream(t) + work := upstream.newRepo("repo") + tc := newTestCache(t, upstream.server.URL, nil) + tc.clone(t, "repo") + + upstream.commit(work, "second") + runGit(t, work, "push", "--quiet", "origin", "main") + upstream.fetchStatus.Store(http.StatusFound) + if out, err := tryGit(t, "", "ls-remote", tc.url("repo")); err == nil { + t.Errorf("served the cached copy after the fetch was redirected:\n%s", out) + } + if status := tc.lsRefs(t); status == http.StatusOK { + t.Errorf("ls-refs served after the fetch was redirected") + } +} + +// TestCaseOnlyDifferentKeysShareOneRepository checks that, where the file +// system ignores case, keys that differ only in case are one repository, so +// a user of one spelling keeps the directory from being evicted under it. +func TestCaseOnlyDifferentKeysShareOneRepository(t *testing.T) { + if !caseInsensitive(t.TempDir()) { + t.Skip("file system is case-sensitive") + } + upstream := newFakeUpstream(t) + upstream.newRepo("repo") + tc := newTestCache(t, upstream.server.URL, nil) + tc.clone(t, "repo") + waitIdle(t, tc.Cache) + + rp := tc.acquire("up/REPO.git") + defer tc.release(rp) + if other := tc.repo("up/repo.git"); other != rp { + t.Error("up/REPO.git and up/repo.git are separate repositories") + } + tc.mu.Lock() + tc.opts.MaxSize = 1 + tc.mu.Unlock() + tc.evict() + if !rp.exists() { + t.Error("repository in use as up/REPO.git was evicted") + } +} + +// TestFoldCaseKeysShareOneEntry checks key folding on any file system by +// setting foldCase directly. +func TestFoldCaseKeysShareOneEntry(t *testing.T) { + tc := newTestCache(t, newFakeUpstream(t).server.URL, nil) + tc.foldCase = true + + upper := tc.acquire("up/REPO.git") + defer tc.release(upper) + lower := tc.acquire("up/repo.git") + defer tc.release(lower) + if upper != lower { + t.Error("up/REPO.git and up/repo.git are separate repositories") + } + tc.mu.Lock() + n := len(tc.repos) + tc.mu.Unlock() + if n != 1 { + t.Errorf("%d repository entries, want 1", n) + } +} diff --git a/internal/gitcache/git.go b/internal/gitcache/git.go new file mode 100644 index 0000000..0cc2c11 --- /dev/null +++ b/internal/gitcache/git.go @@ -0,0 +1,104 @@ +package gitcache + +import ( + "bytes" + "context" + "fmt" + "os" + "os/exec" + "slices" + "strconv" + "strings" + "time" +) + +const ( + maxStderr = 4 << 10 + gitWaitDelay = 5 * time.Second +) + +// gitConfig applies to every git process the cache runs. +var gitConfig = [][2]string{ + // git would follow a redirect from the relay straight to the network. + {"http.followRedirects", "false"}, + {"protocol.version", "2"}, + // Auto gc stays on, as on any Git server, but runs inside the fetch + // rather than detaching, so no git process outlives the fetch that + // started it, and sizes are measured after it. + {"gc.autoDetach", "false"}, + {"maintenance.autoDetach", "false"}, + {"init.defaultBranch", "main"}, + // Keep every fetched pack as a pack. index-pack writes it to a + // temporary file and moves it into place only once complete, whereas a + // small pack is otherwise unpacked object by object, and a transfer cut + // off at max_repo_size would leave the objects before the cut, such as a + // commit without its tree's blobs. + {"transfer.unpackLimit", "1"}, + // Serve any commit the cache holds when a client asks for it by object + // ID, as the upstream would, including ones a force-push left behind, + // and do not advertise the refs that keep fetched ones. + {"uploadpack.allowAnySHA1InWant", "true"}, + {"uploadpack.hideRefs", wantedPrefix}, + // With http.lowSpeedTime, added per cache, gives up on a transfer that + // receives nothing for that long, so a connection that stalls mid-pack + // cannot hold a refresh for fetchTimeout. + {"http.lowSpeedLimit", "1"}, + // index-pack streams blobs larger than this instead of holding them in + // memory, and pack-objects stores them without delta compression, so a + // large file costs a fetch or a clone little memory. + {"core.bigFileThreshold", "8m"}, +} + +// command builds a git process with an environment of its own: none of the +// proxy's environment is passed on, so no system or user config, credential +// helper, HTTP proxy setting or GIT_ variable applies, and the only transport +// git may use is plain HTTP, which is what the relay speaks. +func (c *Cache) command(ctx context.Context, extraEnv []string, args ...string) *exec.Cmd { + cmd := exec.CommandContext(ctx, c.gitPath, args...) + env := []string{ + "PATH=" + os.Getenv("PATH"), + "HOME=" + c.tmpDir(), + "LC_ALL=C", + "GIT_CONFIG_NOSYSTEM=1", + "GIT_CONFIG_GLOBAL=" + os.DevNull, + "GIT_TERMINAL_PROMPT=0", + "GIT_ALLOW_PROTOCOL=http", + } + config := slices.Concat(gitConfig, [][2]string{{"http.lowSpeedTime", strconv.Itoa(c.lowSpeedTime)}}) + env = append(env, "GIT_CONFIG_COUNT="+strconv.Itoa(len(config))) + for i, kv := range config { + env = append(env, + "GIT_CONFIG_KEY_"+strconv.Itoa(i)+"="+kv[0], + "GIT_CONFIG_VALUE_"+strconv.Itoa(i)+"="+kv[1]) + } + env = append(env, extraEnv...) + cmd.Env = env + cmd.WaitDelay = gitWaitDelay + return cmd +} + +// run runs git in the repository at dir and returns its standard output. +func (c *Cache) run(ctx context.Context, dir string, args ...string) (string, error) { + cmd := c.command(ctx, nil, append([]string{"-C", dir}, args...)...) + var stdout bytes.Buffer + stderr := &limitedBuffer{max: maxStderr} + cmd.Stdout = &stdout + cmd.Stderr = stderr + if err := cmd.Run(); err != nil { + return "", fmt.Errorf("git %s: %w: %s", args[0], err, strings.TrimSpace(stderr.String())) + } + return stdout.String(), nil +} + +// limitedBuffer keeps the first max bytes written to it. +type limitedBuffer struct { + bytes.Buffer + max int +} + +func (b *limitedBuffer) Write(p []byte) (int, error) { + if room := b.max - b.Len(); room > 0 { + b.Buffer.Write(p[:min(len(p), room)]) + } + return len(p), nil +} diff --git a/internal/gitcache/helpers_test.go b/internal/gitcache/helpers_test.go new file mode 100644 index 0000000..8e6c2e5 --- /dev/null +++ b/internal/gitcache/helpers_test.go @@ -0,0 +1,437 @@ +package gitcache + +import ( + "bytes" + "compress/gzip" + "errors" + "io" + "log" + "log/slog" + "net/http" + "net/http/cgi" + "net/http/httptest" + "os" + "os/exec" + "path/filepath" + "strings" + "sync" + "sync/atomic" + "testing" + "time" +) + +// gitEnv isolates the tests' own git commands from the machine's config. +func gitEnv(home string) []string { + return []string{ + "PATH=" + os.Getenv("PATH"), + "HOME=" + home, + "GIT_CONFIG_NOSYSTEM=1", + "GIT_TERMINAL_PROMPT=0", + "GIT_AUTHOR_NAME=test", "GIT_AUTHOR_EMAIL=test@example.com", + "GIT_COMMITTER_NAME=test", "GIT_COMMITTER_EMAIL=test@example.com", + } +} + +func runGit(t *testing.T, dir string, args ...string) string { + t.Helper() + out, err := tryGit(t, dir, args...) + if err != nil { + t.Fatalf("git %s: %v\n%s", strings.Join(args, " "), err, out) + } + return strings.TrimSpace(out) +} + +func tryGit(t *testing.T, dir string, args ...string) (string, error) { + t.Helper() + cmd := exec.Command("git", args...) + cmd.Dir = dir + cmd.Env = gitEnv(t.TempDir()) + out, err := cmd.CombinedOutput() + return string(out), err +} + +// httpBackendPath finds git http-backend, which serves the fake upstreams, +// and skips the test where git is installed without it. +func httpBackendPath(t *testing.T) string { + t.Helper() + dir := runGit(t, "", "--exec-path") + for _, name := range []string{"git-http-backend", "git-http-backend.exe"} { + if path := filepath.Join(dir, name); fileExists(path) { + return path + } + } + t.Skip("git http-backend is not installed") + return "" +} + +func fileExists(path string) bool { + _, err := os.Stat(path) + return err == nil +} + +// fakeUpstream serves bare repositories under root with git http-backend. +type fakeUpstream struct { + t *testing.T + root string + server *httptest.Server + + // status, when set, is returned instead of serving the request, and + // fetchStatus instead of serving git's own upload-pack requests. + status atomic.Int32 + fetchStatus atomic.Int32 + // requireAuth, when set, is the Authorization every request must carry. + requireAuth string + // v0Only drops Git-Protocol, so only protocol v0 is spoken. + v0Only bool + // hold, when set, blocks requests until it is closed. + holdMu sync.Mutex + hold chan struct{} + + requests atomic.Int32 + // gitRequests counts requests from git processes, which reach the + // upstream through the relay, and gitSessions the fetches they make. + gitRequests atomic.Int32 + gitSessions atomic.Int32 + unauthed atomic.Int32 + + // stallFetches makes git's own upload-pack requests hang, and + // delayFetches holds them for that long. + stallFetches atomic.Bool + delayFetches atomic.Int64 + // fetchHold, while set, holds git's own upload-pack requests until it + // is closed; fetchArrived is closed when the first one arrives. + fetchHold chan struct{} + fetchArrived chan struct{} + fetchOnce *sync.Once + + bodiesMu sync.Mutex + bodies []string +} + +// recordBody keeps the decoded body of a POST. It also gives the request a +// Content-Length, since net/http/cgi refuses chunked bodies, which git sends +// once a request outgrows http.postBuffer. +func (u *fakeUpstream) recordBody(r *http.Request) { + raw, err := io.ReadAll(r.Body) + if err != nil { + u.t.Errorf("reading request body: %v", err) + } + r.Body = io.NopCloser(bytes.NewReader(raw)) + r.ContentLength = int64(len(raw)) + r.TransferEncoding = nil + decoded := raw + if r.Header.Get("Content-Encoding") == "gzip" { + if zr, err := gzip.NewReader(bytes.NewReader(raw)); err == nil { + decoded, _ = io.ReadAll(zr) + } + } + u.bodiesMu.Lock() + u.bodies = append(u.bodies, string(decoded)) + u.bodiesMu.Unlock() +} + +// lsRefsBodies returns the ls-refs requests the upstream received. +func (u *fakeUpstream) lsRefsBodies() []string { + u.bodiesMu.Lock() + defer u.bodiesMu.Unlock() + var out []string + for _, body := range u.bodies { + if strings.Contains(body, "command=ls-refs") { + out = append(out, body) + } + } + return out +} + +func newFakeUpstream(t *testing.T) *fakeUpstream { + t.Helper() + u := &fakeUpstream{t: t, root: t.TempDir()} + backend := &cgi.Handler{ + Path: httpBackendPath(t), + Stderr: io.Discard, + Logger: log.New(io.Discard, "", 0), + Env: append(gitEnv(t.TempDir()), + "GIT_PROJECT_ROOT="+u.root, + "GIT_HTTP_EXPORT_ALL=1"), + } + u.server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + u.requests.Add(1) + if r.UserAgent() != gitUserAgent { + u.gitRequests.Add(1) + if r.Method == http.MethodGet { + u.gitSessions.Add(1) + } + } + u.holdMu.Lock() + hold := u.hold + u.holdMu.Unlock() + if hold != nil { + <-hold + } + if status := u.status.Load(); status != 0 { + http.Error(w, "unavailable", int(status)) + return + } + if u.requireAuth != "" && r.Header.Get("Authorization") != u.requireAuth { + u.unauthed.Add(1) + http.Error(w, "unauthorized", http.StatusUnauthorized) + return + } + if u.v0Only { + r.Header.Del("Git-Protocol") + } + if r.UserAgent() != gitUserAgent && r.Method == http.MethodPost && u.interceptFetch(w, r) { + return + } + if r.Method == http.MethodPost { + u.recordBody(r) + } + backend.ServeHTTP(w, r) + })) + t.Cleanup(u.server.Close) + return u +} + +// interceptFetch applies the fetch knobs to one of git's own upload-pack +// requests, and reports whether it answered the request. +func (u *fakeUpstream) interceptFetch(w http.ResponseWriter, r *http.Request) bool { + u.holdMu.Lock() + fetchHold, fetchArrived, fetchOnce := u.fetchHold, u.fetchArrived, u.fetchOnce + u.holdMu.Unlock() + if fetchHold != nil { + fetchOnce.Do(func() { close(fetchArrived) }) + <-fetchHold + } + if delay := u.delayFetches.Load(); delay > 0 { + time.Sleep(time.Duration(delay)) + } + if u.stallFetches.Load() { + // The server notices the client leaving only once the body is read. + _, _ = io.Copy(io.Discard, r.Body) + <-r.Context().Done() + return true + } + if status := u.fetchStatus.Load(); status != 0 { + w.Header().Set("Location", u.server.URL+"/elsewhere") + http.Error(w, "unavailable", int(status)) + return true + } + return false +} + +// holdFetches holds git's own upload-pack requests until release is called. +// arrived is closed when the first one reaches the upstream. +func (u *fakeUpstream) holdFetches() (arrived <-chan struct{}, release func()) { + u.holdMu.Lock() + defer u.holdMu.Unlock() + hold, first := make(chan struct{}), make(chan struct{}) + u.fetchHold, u.fetchArrived, u.fetchOnce = hold, first, &sync.Once{} + var once sync.Once + return first, func() { + once.Do(func() { + u.holdMu.Lock() + u.fetchHold = nil + u.holdMu.Unlock() + close(hold) + }) + } +} + +func (u *fakeUpstream) holdRequests() func() { + u.holdMu.Lock() + defer u.holdMu.Unlock() + hold := make(chan struct{}) + u.hold = hold + var once sync.Once + return func() { + once.Do(func() { + u.holdMu.Lock() + u.hold = nil + u.holdMu.Unlock() + close(hold) + }) + } +} + +// newRepo creates {name}.git upstream with one commit on main and a tag, and +// returns a working clone to commit and push from. +func (u *fakeUpstream) newRepo(name string) string { + u.t.Helper() + bare := filepath.Join(u.root, name+".git") + runGit(u.t, "", "init", "--quiet", "--bare", "--initial-branch=main", bare) + work := u.t.TempDir() + runGit(u.t, "", "clone", "--quiet", bare, work) + runGit(u.t, work, "checkout", "--quiet", "-b", "main") + u.commit(work, "first") + runGit(u.t, work, "tag", "-a", "-m", "v1", "v1") + runGit(u.t, work, "push", "--quiet", "origin", "main", "v1") + return work +} + +func (u *fakeUpstream) commit(work, msg string) string { + u.t.Helper() + if err := os.WriteFile(filepath.Join(work, "file.txt"), []byte(msg+"\n"), 0o600); err != nil { + u.t.Fatal(err) + } + runGit(u.t, work, "add", "file.txt") + runGit(u.t, work, "commit", "--quiet", "-m", msg) + return runGit(u.t, work, "rev-parse", "HEAD") +} + +// waitIdle waits until no request or refresh is using a repository, so a +// test can inspect or change the cache without racing a request finishing. +func waitIdle(t *testing.T, c *Cache) { + t.Helper() + waitFor(t, func() bool { + c.mu.Lock() + defer c.mu.Unlock() + for _, rp := range c.repos { + if rp.users > 0 { + return false + } + } + return true + }) +} + +// bare is the upstream repository named "repo". +// repo returns the cache's entry for key, reading the map under the lock. +func (tc *testCache) repo(key string) *repo { + tc.mu.Lock() + defer tc.mu.Unlock() + return tc.repos[key] +} + +// usersOf is the number of requests and refreshes using the repository. +func (tc *testCache) usersOf(key string) int { + tc.mu.Lock() + defer tc.mu.Unlock() + return tc.repos[key].users +} + +func (u *fakeUpstream) bare() string { + return filepath.Join(u.root, "repo.git") +} + +type testCache struct { + *Cache + server *httptest.Server + logs *lockedBuffer +} + +func newTestCache(t *testing.T, upstreamURL string, configure func(*Options)) *testCache { + t.Helper() + // The cache's log is shown when the test fails. + logs := &lockedBuffer{} + t.Cleanup(func() { + if t.Failed() { + t.Logf("git cache log:\n%s", logs.String()) + } + }) + opts := Options{ + Upstreams: map[string]string{"up": "up"}, + CacheDir: t.TempDir(), + RefreshWait: 5 * time.Second, + StaleMaxAge: time.Hour, + Client: &http.Client{}, + Logger: slog.New(slog.NewTextHandler(logs, &slog.HandlerOptions{Level: slog.LevelDebug})), + } + if configure != nil { + configure(&opts) + } + c, err := New(opts) + if err != nil { + t.Fatalf("New: %v", err) + } + server := httptest.NewServer(testFront(c, upstreamURL, true)) + t.Cleanup(func() { + server.Close() + _ = c.Close() + }) + return &testCache{Cache: c, server: server, logs: logs} +} + +// testFront serves /git/up/{repo}/info/refs and git-upload-pack from c, as +// internal/handler does once it has validated the request, with repo +// fetched from upstreamURL/{repo}. fetchWants is OpenOptions.FetchWants. +func testFront(c *Cache, upstreamURL string, fetchWants bool) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + path := strings.TrimPrefix(r.URL.Path, "/git/up/") + repo, infoRefs := strings.CutSuffix(path, "/info/refs") + if !infoRefs { + var ok bool + if repo, ok = strings.CutSuffix(path, "/git-upload-pack"); !ok || r.Method != http.MethodPost { + http.Error(w, "not served", http.StatusForbidden) + return + } + } else if r.URL.RawQuery != "service=git-upload-pack" { + http.Error(w, "not served", http.StatusForbidden) + return + } + var req *Request + if !infoRefs { + var err error + if req, err = c.ReadRequest(r); err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + defer req.Close() + } + lease, err := c.Open(r.Context(), "up/"+strings.TrimSuffix(repo, ".git")+".git", upstreamURL+"/"+repo, + OpenOptions{Refresh: infoRefs, FetchWants: fetchWants}) + switch { + case errors.Is(err, ErrNotFound): + http.Error(w, err.Error(), http.StatusNotFound) + return + case errors.Is(err, ErrTooLarge), errors.Is(err, ErrCacheFull): + http.Error(w, err.Error(), http.StatusInsufficientStorage) + return + case err != nil: + http.Error(w, err.Error(), http.StatusBadGateway) + return + } + defer lease.Release() + if infoRefs { + lease.ServeInfoRefs(w, r) + } else { + lease.ServeUploadPack(w, r, req) + } + }) +} + +func (tc *testCache) url(repo string) string { + return tc.server.URL + "/git/up/" + repo +} + +// clone clones repo through the cache with the given protocol version and +// returns the working copy. +func (tc *testCache) clone(t *testing.T, repo string, args ...string) string { + t.Helper() + dir := filepath.Join(t.TempDir(), "clone") + runGit(t, "", append(append([]string{"clone", "--quiet"}, args...), tc.url(repo), dir)...) + return dir +} + +// cachedRefs lists the refs of the cached copy of "repo". +func (tc *testCache) cachedRefs(t *testing.T) string { + t.Helper() + return runGit(t, filepath.Join(tc.dir, "up", "repo.git"), "for-each-ref", "--format=%(objectname) %(refname)") +} + +// lockedBuffer is a bytes.Buffer safe for concurrent writers. +type lockedBuffer struct { + mu sync.Mutex + buf bytes.Buffer +} + +func (b *lockedBuffer) Write(p []byte) (int, error) { + b.mu.Lock() + defer b.mu.Unlock() + return b.buf.Write(p) +} + +func (b *lockedBuffer) String() string { + b.mu.Lock() + defer b.mu.Unlock() + return b.buf.String() +} diff --git a/internal/gitcache/lock_unix.go b/internal/gitcache/lock_unix.go new file mode 100644 index 0000000..215027a --- /dev/null +++ b/internal/gitcache/lock_unix.go @@ -0,0 +1,24 @@ +//go:build !windows + +package gitcache + +import ( + "errors" + "os" + "syscall" +) + +func lockFile(path string) (*os.File, error) { + f, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE, lockFilePermissions) + if err != nil { + return nil, err + } + if err := syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB); err != nil { + _ = f.Close() + if errors.Is(err, syscall.EWOULDBLOCK) { + return nil, errLocked + } + return nil, err + } + return f, nil +} diff --git a/internal/gitcache/lock_windows.go b/internal/gitcache/lock_windows.go new file mode 100644 index 0000000..99f46d5 --- /dev/null +++ b/internal/gitcache/lock_windows.go @@ -0,0 +1,27 @@ +package gitcache + +import ( + "errors" + "os" + "syscall" +) + +const errorSharingViolation syscall.Errno = 32 + +// lockFile opens path with no sharing, so no other handle can open it while +// this one is open. +func lockFile(path string) (*os.File, error) { + name, err := syscall.UTF16PtrFromString(path) + if err != nil { + return nil, err + } + h, err := syscall.CreateFile(name, syscall.GENERIC_READ|syscall.GENERIC_WRITE, 0, nil, + syscall.OPEN_ALWAYS, syscall.FILE_ATTRIBUTE_NORMAL, 0) + if errors.Is(err, errorSharingViolation) { + return nil, errLocked + } + if err != nil { + return nil, err + } + return os.NewFile(uintptr(h), path), nil +} diff --git a/internal/gitcache/mirror.go b/internal/gitcache/mirror.go new file mode 100644 index 0000000..6e45d43 --- /dev/null +++ b/internal/gitcache/mirror.go @@ -0,0 +1,253 @@ +package gitcache + +import ( + "context" + "errors" + "fmt" + "os/exec" + "slices" + "strings" + "time" +) + +// MirrorResult is what Mirror did. +type MirrorResult struct { + // Cached reports that the repository, and the commit if a version was + // given, were cached already. + Cached bool + // Bytes is how much the cached repository grew. + Bytes int64 + // Commit is the commit the version names, empty without a version. + Commit string + // Submodules are the submodules Commit records, sorted by path. + Submodules []Submodule +} + +// Submodule is a submodule a commit records: its path, the URL .gitmodules +// gives for it, which may be relative to the repository's, and the commit +// the gitlink pins. +type Submodule struct { + Path, URL, Commit string +} + +// Mirror brings the repository cached under key up to date with repoURL, +// cloning it if needed, and waits for that to finish. version, if given, is +// a full commit ID or a tag. A commit is made sure to be cached: one on no +// branch or tag is fetched by ID when fetchWants allows it (see +// OpenOptions.FetchWants), and is kept as long as a commit a client fetched +// by ID. A tag is cached with the repository's tags. +func (c *Cache) Mirror(ctx context.Context, key, repoURL, version string, fetchWants bool) (MirrorResult, error) { + if lower := strings.ToLower(version); isObjectID(lower) { + version = lower + } + tag := version != "" && !isObjectID(version) + if tag { + if err := c.checkTagName(ctx, version); err != nil { + return MirrorResult{}, err + } + } + lease, err := c.Open(ctx, key, repoURL, OpenOptions{FetchWants: fetchWants, NoCheck: true}) + if err != nil { + return MirrorResult{}, err + } + defer lease.Release() + rp := lease.repo + cached := lease.hit + before := int64(0) + var refreshErr error + // Open cloned a repository that wasn't cached; one that was is + // refreshed here, waiting for the fetch a client would not wait for. + if cached { + before = rp.size.Load() + refresh := c.startRefresh(rp, repoURL) + select { + case <-refresh.done: + refreshErr = refresh.err + case <-ctx.Done(): + return MirrorResult{}, ctx.Err() + } + } + + // A refresh past max_repo_size gets the repository dropped once it is + // released, commit and all. + if errors.Is(refreshErr, ErrTooLarge) { + return MirrorResult{}, refreshErr + } + commit := version + switch { + case tag: + if commit, err = c.resolveTag(ctx, rp.dir, version); err != nil { + if refreshErr != nil { + // The tag may be one the failed refresh would have brought. + return MirrorResult{}, refreshErr + } + if errors.Is(err, ErrNotFound) && strings.Trim(strings.ToLower(version), "0123456789abcdef") == "" { + // Likely an abbreviated commit ID. + return MirrorResult{}, fmt.Errorf("%s is not a full commit ID or tag: %w", version, ErrNotFound) + } + return MirrorResult{}, err + } + if refreshErr != nil { + // Tags can move; this is where it pointed when last fetched. + c.logger.Warn("git cache: refresh failed, mirroring the cached tag", "repository", key, "tag", version, "commit", commit, "error", refreshErr) + } + case version != "": + if err := c.ensureCommit(ctx, rp, repoURL, commit, fetchWants); err != nil { + return MirrorResult{}, err + } + } + // A refresh that failed leaves the commit cached all the same. + if refreshErr != nil && version == "" { + return MirrorResult{}, refreshErr + } + var submodules []Submodule + if commit != "" { + if submodules, err = c.submodules(ctx, key, rp.dir, commit); err != nil { + return MirrorResult{}, err + } + } + grown := max(rp.size.Load()-before, 0) + return MirrorResult{Cached: cached && grown == 0, Bytes: grown, Commit: commit, Submodules: submodules}, nil +} + +// checkTagName refuses a version that is no valid tag name, such as one +// with .. or a revision suffix like ^{tree}. +func (c *Cache) checkTagName(ctx context.Context, name string) error { + if err := c.command(ctx, nil, "check-ref-format", "refs/tags/"+name).Run(); err != nil { + return fmt.Errorf("%q is neither a full commit ID nor a tag name", name) + } + return nil +} + +// resolveTag returns the commit tag points at. +func (c *Cache) resolveTag(ctx context.Context, dir, tag string) (string, error) { + out, err := c.command(ctx, nil, "-C", dir, "rev-parse", "--verify", "--quiet", "--end-of-options", "refs/tags/"+tag+"^{commit}").Output() + var exit *exec.ExitError + if errors.As(err, &exit) && exit.ExitCode() == 1 { + return "", fmt.Errorf("tag %s: %w", tag, ErrNotFound) + } + if err != nil { + return "", fmt.Errorf("resolving tag %s: %w", tag, err) + } + return strings.TrimSpace(string(out)), nil +} + +// submodules lists the submodules commit records: its gitlinks that +// .gitmodules names a URL for. +func (c *Cache) submodules(ctx context.Context, key, dir, commit string) ([]Submodule, error) { + err := c.command(ctx, nil, "-C", dir, "rev-parse", "--verify", "--quiet", "--end-of-options", commit+":.gitmodules").Run() + var exit *exec.ExitError + if errors.As(err, &exit) && exit.ExitCode() == 1 && ctx.Err() == nil { + return nil, nil + } + if err != nil { + if ctx.Err() != nil { + return nil, ctx.Err() + } + return nil, fmt.Errorf("looking for .gitmodules: %w", err) + } + // --list rather than --get-regexp, which fails when nothing matches. + out, err := c.run(ctx, dir, "config", "-z", "--blob", commit+":.gitmodules", "--list") + if err != nil { + if ctx.Err() != nil { + return nil, ctx.Err() + } + // The commit is cached; a .gitmodules git can't read only loses + // its submodules. + c.logger.Warn("git cache: cannot read .gitmodules, skipping submodules", "repository", key, "commit", commit, "error", err) + return nil, nil + } + paths, urls := map[string]string{}, map[string]string{} + for entry := range strings.SplitSeq(out, "\x00") { + key, value, ok := strings.Cut(entry, "\n") + section, ok2 := strings.CutPrefix(key, "submodule.") + name, field, dotted := strings.CutLast(section, ".") + if !ok || !ok2 || !dotted { + continue + } + switch field { + case "path": + paths[value] = name + case "url": + urls[name] = value + } + } + var pathspecs []string + for path, name := range paths { + if path != "" && urls[name] != "" { + pathspecs = append(pathspecs, path) + } + } + if len(pathspecs) == 0 { + return nil, nil + } + args := append([]string{"--literal-pathspecs", "ls-tree", "-z", "--full-tree", commit, "--"}, pathspecs...) + tree, err := c.run(ctx, dir, args...) + if err != nil { + return nil, err + } + var submodules []Submodule + for entry := range strings.SplitSeq(tree, "\x00") { + meta, path, ok := strings.Cut(entry, "\t") + fields := strings.Fields(meta) + if !ok || len(fields) != 3 || fields[0] != "160000" { + continue + } + if url := urls[paths[path]]; url != "" && isObjectID(fields[2]) { + submodules = append(submodules, Submodule{Path: path, URL: url, Commit: fields[2]}) + } + } + slices.SortFunc(submodules, func(a, b Submodule) int { return strings.Compare(a.Path, b.Path) }) + return submodules, nil +} + +// ensureCommit makes sure the repository has commit, fetching it by ID when +// it doesn't and fetchWants allows it. A commit on no branch or tag that is +// cached already gets a new wanted ref, so it is kept for wantedMaxAge from +// this run on. +func (c *Cache) ensureCommit(ctx context.Context, rp *repo, repoURL, commit string, fetchWants bool) error { + missing, err := c.missingObjects(ctx, rp.dir, []string{commit}) + if err != nil { + return err + } + if len(missing) == 0 { + return c.renewWanted(ctx, rp, commit) + } + if !fetchWants { + return fmt.Errorf("commit %s: %w", commit, ErrNotFound) + } + if err := c.fetchMissingWants(ctx, rp, repoURL, missing); err != nil { + if ctx.Err() != nil || errors.Is(err, ErrTooLarge) || errors.Is(err, ErrCacheFull) || errors.Is(err, errUpstreamUnanswered) { + return err + } + // The upstream refuses a commit it doesn't have. + return fmt.Errorf("commit %s: %w: %w", commit, ErrNotFound, err) + } + // fetchMissingWants skips a commit that failed moments ago. + if missing, err = c.missingObjects(ctx, rp.dir, missing); err != nil { + return err + } + if len(missing) > 0 { + return fmt.Errorf("commit %s: %w", commit, ErrNotFound) + } + return nil +} + +// renewWanted writes a new wanted ref for commit when no branch or tag +// includes it. +func (c *Cache) renewWanted(ctx context.Context, rp *repo, commit string) error { + unlock, err := rp.lockWrites(ctx) + if err != nil { + return err + } + defer unlock() + unmerged, err := c.unmergedCommits(ctx, rp.dir, []string{commit}) + if err != nil || !unmerged[commit] { + return err + } + cmd := c.command(ctx, nil, "-C", rp.dir, "update-ref", wantedRef(commit, time.Now()), commit) + if out, err := cmd.CombinedOutput(); err != nil { + return fmt.Errorf("renewing wanted ref: %w: %s", err, strings.TrimSpace(string(out))) + } + return nil +} diff --git a/internal/gitcache/mirror_test.go b/internal/gitcache/mirror_test.go new file mode 100644 index 0000000..d016f2a --- /dev/null +++ b/internal/gitcache/mirror_test.go @@ -0,0 +1,415 @@ +package gitcache + +import ( + "context" + "errors" + "net/http" + "os" + "path/filepath" + "slices" + "strconv" + "strings" + "testing" + "time" +) + +func TestMirrorClonesRepository(t *testing.T) { + upstream := newFakeUpstream(t) + upstream.newRepo("repo") + tc := newTestCache(t, upstream.server.URL, nil) + + got, err := tc.Mirror(context.Background(), "up/repo.git", upstream.server.URL+"/repo", "", true) + if err != nil { + t.Fatalf("Mirror: %v", err) + } + if got.Cached || got.Bytes <= 0 { + t.Errorf("first mirror = %+v, want fetched bytes", got) + } + if !strings.Contains(tc.cachedRefs(t), "refs/tags/v1") { + t.Errorf("cached refs %q lack the tag", tc.cachedRefs(t)) + } + + got, err = tc.Mirror(context.Background(), "up/repo.git", upstream.server.URL+"/repo", "", true) + if err != nil || !got.Cached { + t.Errorf("second mirror = %+v, %v, want cached", got, err) + } +} + +func TestMirrorFetchesCommitOnNoBranch(t *testing.T) { + upstream := newFakeUpstream(t) + work := upstream.newRepo("repo") + runGit(t, upstream.bare(), "config", "uploadpack.allowAnySHA1InWant", "true") + sha := upstream.pushPullRequest(work, 1, nil) + tc := newTestCache(t, upstream.server.URL, nil) + + got, err := tc.Mirror(context.Background(), "up/repo.git", upstream.server.URL+"/repo", sha, true) + if err != nil { + t.Fatalf("Mirror: %v", err) + } + if got.Cached { + t.Errorf("mirror = %+v, want fetched", got) + } + if refs := tc.wantedRefs(t); len(refs) != 1 { + t.Errorf("wanted refs %v, want one", refs) + } + + sessions := upstream.gitSessions.Load() + got, err = tc.Mirror(context.Background(), "up/repo.git", upstream.server.URL+"/repo", sha, true) + if err != nil || !got.Cached { + t.Errorf("second mirror = %+v, %v, want cached", got, err) + } + if n := upstream.gitSessions.Load() - sessions; n != 0 { + t.Errorf("second mirror fetched %d times, want none", n) + } +} + +func TestMirrorFindsCommitOnABranch(t *testing.T) { + upstream := newFakeUpstream(t) + work := upstream.newRepo("repo") + sha := upstream.commit(work, "second") + runGit(t, work, "push", "--quiet", "origin", "main") + tc := newTestCache(t, upstream.server.URL, nil) + + got, err := tc.Mirror(context.Background(), "up/repo.git", upstream.server.URL+"/repo", sha, false) + if err != nil || got.Cached { + t.Errorf("mirror = %+v, %v, want fetched", got, err) + } +} + +func TestMirrorDoesNotFetchByIDWhenTurnedOff(t *testing.T) { + upstream := newFakeUpstream(t) + work := upstream.newRepo("repo") + runGit(t, upstream.bare(), "config", "uploadpack.allowAnySHA1InWant", "true") + sha := upstream.pushPullRequest(work, 1, nil) + tc := newTestCache(t, upstream.server.URL, nil) + + _, err := tc.Mirror(context.Background(), "up/repo.git", upstream.server.URL+"/repo", sha, false) + if !errors.Is(err, ErrNotFound) { + t.Errorf("mirror of a commit on no branch with fetching by ID off = %v, want ErrNotFound", err) + } + if refs := tc.wantedRefs(t); len(refs) != 0 { + t.Errorf("wanted refs %v, want none", refs) + } +} + +func TestMirrorReportsMissingCommit(t *testing.T) { + upstream := newFakeUpstream(t) + upstream.newRepo("repo") + tc := newTestCache(t, upstream.server.URL, nil) + + _, err := tc.Mirror(context.Background(), "up/repo.git", upstream.server.URL+"/repo", strings.Repeat("ab", 20), true) + if !errors.Is(err, ErrNotFound) { + t.Errorf("mirror of a commit the upstream lacks = %v, want ErrNotFound", err) + } +} + +func TestMirrorRefusesInvalidCommit(t *testing.T) { + upstream := newFakeUpstream(t) + upstream.newRepo("repo") + tc := newTestCache(t, upstream.server.URL, nil) + + if _, err := tc.Mirror(context.Background(), "up/repo.git", upstream.server.URL+"/repo", "main", true); err == nil { + t.Error("mirrored a branch name as a commit") + } +} + +func TestMirrorCountsRefreshThatFetched(t *testing.T) { + upstream := newFakeUpstream(t) + work := upstream.newRepo("repo") + tc := newTestCache(t, upstream.server.URL, nil) + if _, err := tc.Mirror(context.Background(), "up/repo.git", upstream.server.URL+"/repo", "", true); err != nil { + t.Fatalf("Mirror: %v", err) + } + upstream.commit(work, "second") + runGit(t, work, "push", "--quiet", "origin", "main") + + got, err := tc.Mirror(context.Background(), "up/repo.git", upstream.server.URL+"/repo", "", true) + if err != nil { + t.Fatalf("Mirror: %v", err) + } + if got.Cached || got.Bytes <= 0 { + t.Errorf("mirror after a push = %+v, want fetched bytes", got) + } +} + +// TestMirrorRenewsWantedCommit checks mirroring a commit on no branch again +// makes its 7 days count from that run, not from the first fetch. +func TestMirrorRenewsWantedCommit(t *testing.T) { + upstream := newFakeUpstream(t) + work := upstream.newRepo("repo") + runGit(t, upstream.bare(), "config", "uploadpack.allowAnySHA1InWant", "true") + sha := upstream.pushPullRequest(work, 1, nil) + tc := newTestCache(t, upstream.server.URL, nil) + if _, err := tc.Mirror(context.Background(), "up/repo.git", upstream.server.URL+"/repo", sha, true); err != nil { + t.Fatalf("Mirror: %v", err) + } + cached := filepath.Join(tc.dir, "up", "repo.git") + for _, ref := range tc.wantedRefs(t) { + runGit(t, cached, "update-ref", "-d", ref) + } + old := wantedRef(sha, time.Now().Add(-wantedMaxAge+time.Hour)) + runGit(t, cached, "update-ref", old, sha) + + start := time.Now().Add(-time.Second) + got, err := tc.Mirror(context.Background(), "up/repo.git", upstream.server.URL+"/repo", sha, true) + if err != nil || !got.Cached { + t.Fatalf("second mirror = %+v, %v, want cached", got, err) + } + if !slices.ContainsFunc(tc.wantedRefs(t), func(ref string) bool { + return ref != old && wantedRefTime(t, ref, sha).After(start) + }) { + t.Errorf("wanted refs %v, want one written by the second mirror", tc.wantedRefs(t)) + } +} + +func TestMirrorDoesNotPinCommitOnABranch(t *testing.T) { + upstream := newFakeUpstream(t) + work := upstream.newRepo("repo") + sha := upstream.commit(work, "second") + runGit(t, work, "push", "--quiet", "origin", "main") + tc := newTestCache(t, upstream.server.URL, nil) + for range 2 { + if _, err := tc.Mirror(context.Background(), "up/repo.git", upstream.server.URL+"/repo", sha, true); err != nil { + t.Fatalf("Mirror: %v", err) + } + } + if refs := tc.wantedRefs(t); len(refs) != 0 { + t.Errorf("wanted refs %v, want none for a commit on a branch", refs) + } +} + +func wantedRefTime(t *testing.T, ref, oid string) time.Time { + t.Helper() + created, got, _ := strings.Cut(strings.TrimPrefix(ref, wantedPrefix), "/") + unix, err := strconv.ParseInt(created, 10, 64) + if err != nil || got != oid { + return time.Time{} + } + return time.Unix(unix, 0) +} + +// TestMirrorReportsRefreshTooLarge checks a commit that is cached still +// fails to mirror when the refresh doesn't fit in max_repo_size, since the +// repository is dropped once released. +func TestMirrorReportsRefreshTooLarge(t *testing.T) { + upstream := newFakeUpstream(t) + work := upstream.newRepo("repo") + runGit(t, upstream.bare(), "config", "uploadpack.allowAnySHA1InWant", "true") + pinned := upstream.pushPullRequest(work, 1, randomBytes(100<<10)) + base := repoSize(t, upstream, "repo") + tc := newTestCache(t, upstream.server.URL, func(o *Options) { o.MaxRepoSize = base + 150<<10 }) + if _, err := tc.Mirror(context.Background(), "up/repo.git", upstream.server.URL+"/repo", pinned, true); err != nil { + t.Fatalf("Mirror: %v", err) + } + if err := os.WriteFile(filepath.Join(work, "grown.bin"), randomBytes(80<<10), 0o600); err != nil { + t.Fatal(err) + } + runGit(t, work, "add", "grown.bin") + upstream.commit(work, "grown") + runGit(t, work, "push", "--quiet", "origin", "main") + + _, err := tc.Mirror(context.Background(), "up/repo.git", upstream.server.URL+"/repo", pinned, true) + if !errors.Is(err, ErrTooLarge) { + t.Errorf("mirror with a refresh past max_repo_size = %v, want ErrTooLarge", err) + } +} + +func TestMirrorResolvesTag(t *testing.T) { + upstream := newFakeUpstream(t) + work := upstream.newRepo("repo") + tagged := runGit(t, work, "rev-parse", "v1^{commit}") + tc := newTestCache(t, upstream.server.URL, nil) + + got, err := tc.Mirror(context.Background(), "up/repo.git", upstream.server.URL+"/repo", "v1", true) + if err != nil { + t.Fatalf("Mirror: %v", err) + } + if got.Commit != tagged { + t.Errorf("commit %q, want %s the tag points at", got.Commit, tagged) + } +} + +func TestMirrorReportsMissingTag(t *testing.T) { + upstream := newFakeUpstream(t) + upstream.newRepo("repo") + tc := newTestCache(t, upstream.server.URL, nil) + + for _, version := range []string{"v9", "main"} { + _, err := tc.Mirror(context.Background(), "up/repo.git", upstream.server.URL+"/repo", version, true) + if !errors.Is(err, ErrNotFound) { + t.Errorf("mirror at %q = %v, want ErrNotFound", version, err) + } + } +} + +func TestMirrorRefusesInvalidTag(t *testing.T) { + upstream := newFakeUpstream(t) + upstream.newRepo("repo") + tc := newTestCache(t, upstream.server.URL, nil) + + for _, version := range []string{"a..b", "v1^{tree}", "v1~1", "v 1", "v1:x"} { + _, err := tc.Mirror(context.Background(), "up/repo.git", upstream.server.URL+"/repo", version, true) + if err == nil || errors.Is(err, ErrNotFound) { + t.Errorf("mirror at %q = %v, want an invalid version error", version, err) + } + } +} + +func TestMirrorListsSubmodules(t *testing.T) { + upstream := newFakeUpstream(t) + libWork := upstream.newRepo("lib") + libCommit := runGit(t, libWork, "rev-parse", "HEAD") + work := upstream.newRepo("repo") + gitmodules := "[submodule \"vendor/lib\"]\n\tpath = vendor/lib\n\turl = ../lib.git\n" + + "[submodule \"other\"]\n\tpath = third_party/other\n\turl = https://example.com/other.git\n" + + "[submodule \"colon\"]\n\tpath = :colon\n\turl = ../lib.git\n" + if err := os.WriteFile(filepath.Join(work, ".gitmodules"), []byte(gitmodules), 0o600); err != nil { + t.Fatal(err) + } + otherCommit := strings.Repeat("ab", 20) + runGit(t, work, "add", ".gitmodules") + runGit(t, work, "update-index", "--add", "--cacheinfo", "160000,"+libCommit+",vendor/lib") + runGit(t, work, "update-index", "--add", "--cacheinfo", "160000,"+otherCommit+",third_party/other") + // Git for Windows refuses ':' in paths unless NTFS protection is off. + runGit(t, work, "-c", "core.protectNTFS=false", "update-index", "--add", "--cacheinfo", "160000,"+libCommit+",:colon") + runGit(t, work, "commit", "--quiet", "-m", "submodules") + runGit(t, work, "push", "--quiet", "origin", "main") + commit := runGit(t, work, "rev-parse", "HEAD") + tc := newTestCache(t, upstream.server.URL, nil) + + got, err := tc.Mirror(context.Background(), "up/repo.git", upstream.server.URL+"/repo", commit, true) + if err != nil { + t.Fatalf("Mirror: %v", err) + } + want := []Submodule{ + {Path: ":colon", URL: "../lib.git", Commit: libCommit}, + {Path: "third_party/other", URL: "https://example.com/other.git", Commit: otherCommit}, + {Path: "vendor/lib", URL: "../lib.git", Commit: libCommit}, + } + if !slices.Equal(got.Submodules, want) { + t.Errorf("submodules %+v, want %+v", got.Submodules, want) + } + + // Without a version, nothing names a commit to read submodules from. + got, err = tc.Mirror(context.Background(), "up/repo.git", upstream.server.URL+"/repo", "", true) + if err != nil || len(got.Submodules) != 0 { + t.Errorf("unversioned mirror = %+v, %v, want no submodules", got, err) + } +} + +// TestMirrorWithEmptyGitmodules checks a .gitmodules with no path or url, +// for which git config --get-regexp finds nothing, lists no submodules. +func TestMirrorWithEmptyGitmodules(t *testing.T) { + upstream := newFakeUpstream(t) + work := upstream.newRepo("repo") + for i, content := range []string{"", "[submodule \"x\"]\n\tbranch = main\n"} { + if err := os.WriteFile(filepath.Join(work, ".gitmodules"), []byte(content), 0o600); err != nil { + t.Fatal(err) + } + runGit(t, work, "add", ".gitmodules") + runGit(t, work, "commit", "--quiet", "--allow-empty", "-m", "gitmodules "+strconv.Itoa(i)) + } + runGit(t, work, "push", "--quiet", "origin", "main") + tc := newTestCache(t, upstream.server.URL, nil) + + for _, rev := range []string{"HEAD~1", "HEAD"} { + commit := runGit(t, work, "rev-parse", rev) + got, err := tc.Mirror(context.Background(), "up/repo.git", upstream.server.URL+"/repo", commit, true) + if err != nil || len(got.Submodules) != 0 { + t.Errorf("mirror of %s = %+v, %v, want no submodules", rev, got, err) + } + } +} + +// TestSubmodulesReportsCancel checks a cancelled context is reported, not +// read as a commit without .gitmodules. +func TestSubmodulesReportsCancel(t *testing.T) { + upstream := newFakeUpstream(t) + work := upstream.newRepo("repo") + commit := runGit(t, work, "rev-parse", "HEAD") + ctx, cancel := context.WithCancel(context.Background()) + cancel() + tc := newTestCache(t, upstream.server.URL, nil) + + if _, err := tc.submodules(ctx, "up/repo.git", work, commit); !errors.Is(err, context.Canceled) { + t.Errorf("submodules with a cancelled context = %v, want context.Canceled", err) + } +} + +// TestMirrorSkipsBrokenGitmodules checks a .gitmodules git can't read, one +// with a syntax error or committed as a symlink, lists no submodules and +// logs a warning instead of failing the mirror. +func TestMirrorSkipsBrokenGitmodules(t *testing.T) { + upstream := newFakeUpstream(t) + work := upstream.newRepo("repo") + gitmodules := filepath.Join(work, ".gitmodules") + if err := os.WriteFile(gitmodules, []byte("[submodule \"x\"\n\tpath = x\n"), 0o600); err != nil { + t.Fatal(err) + } + runGit(t, work, "add", ".gitmodules") + runGit(t, work, "commit", "--quiet", "-m", "broken gitmodules") + if err := os.Remove(gitmodules); err != nil { + t.Fatal(err) + } + if err := os.Symlink("../outside/.gitmodules", gitmodules); err != nil { + t.Fatal(err) + } + runGit(t, work, "add", ".gitmodules") + runGit(t, work, "commit", "--quiet", "-m", "symlinked gitmodules") + runGit(t, work, "push", "--quiet", "origin", "main") + tc := newTestCache(t, upstream.server.URL, nil) + + for _, rev := range []string{"HEAD~1", "HEAD"} { + commit := runGit(t, work, "rev-parse", rev) + got, err := tc.Mirror(context.Background(), "up/repo.git", upstream.server.URL+"/repo", commit, true) + if err != nil || len(got.Submodules) != 0 { + t.Errorf("mirror of %s = %+v, %v, want no submodules", rev, got, err) + } + if !strings.Contains(tc.logs.String(), "commit="+commit) { + t.Errorf("no warning naming %s in the log", commit) + } + } +} + +func TestMirrorAcceptsUppercaseCommit(t *testing.T) { + upstream := newFakeUpstream(t) + work := upstream.newRepo("repo") + commit := runGit(t, work, "rev-parse", "HEAD") + tc := newTestCache(t, upstream.server.URL, nil) + + got, err := tc.Mirror(context.Background(), "up/repo.git", upstream.server.URL+"/repo", strings.ToUpper(commit), true) + if err != nil || got.Commit != commit { + t.Errorf("mirror of the uppercase commit ID = %+v, %v, want commit %s", got, err, commit) + } +} + +func TestMirrorExplainsShortCommit(t *testing.T) { + upstream := newFakeUpstream(t) + work := upstream.newRepo("repo") + commit := runGit(t, work, "rev-parse", "HEAD") + tc := newTestCache(t, upstream.server.URL, nil) + + _, err := tc.Mirror(context.Background(), "up/repo.git", upstream.server.URL+"/repo", commit[:12], true) + if !errors.Is(err, ErrNotFound) || !strings.Contains(err.Error(), "full commit ID") { + t.Errorf("mirror of a short commit ID = %v, want ErrNotFound saying it is no full commit ID", err) + } +} + +// TestMirrorWarnsOfStaleTag checks a tag served from the cache when the +// refresh fails is mirrored with a warning, since the tag may have moved. +func TestMirrorWarnsOfStaleTag(t *testing.T) { + upstream := newFakeUpstream(t) + upstream.newRepo("repo") + tc := newTestCache(t, upstream.server.URL, nil) + if _, err := tc.Mirror(context.Background(), "up/repo.git", upstream.server.URL+"/repo", "v1", true); err != nil { + t.Fatalf("Mirror: %v", err) + } + upstream.status.Store(http.StatusServiceUnavailable) + + if _, err := tc.Mirror(context.Background(), "up/repo.git", upstream.server.URL+"/repo", "v1", true); err != nil { + t.Fatalf("mirror of a cached tag with the upstream down: %v", err) + } + if !strings.Contains(tc.logs.String(), "tag=v1") { + t.Errorf("no warning naming the tag in the log:\n%s", tc.logs.String()) + } +} diff --git a/internal/gitcache/pktline.go b/internal/gitcache/pktline.go new file mode 100644 index 0000000..5f6095b --- /dev/null +++ b/internal/gitcache/pktline.go @@ -0,0 +1,65 @@ +package gitcache + +import ( + "bufio" + "fmt" + "io" + "strconv" + "strings" +) + +// pkt-line framing (gitprotocol-common): four hex digits giving the packet +// length including themselves, then the payload. The lengths 0000, 0001 and +// 0002 are the flush, delimiter and response-end packets. +const ( + pktFlush = "0000" + pktDelim = "0001" + pktHeaderLen = 4 + pktMaxLen = 65520 + pktSpecialLast = 2 +) + +type pktKind int + +const ( + pktData pktKind = iota + pktFlushKind + pktDelimKind + pktEndKind +) + +func pktLine(payload string) string { + return fmt.Sprintf("%04x%s", len(payload)+pktHeaderLen, payload) +} + +type pktReader struct { + r *bufio.Reader +} + +func newPktReader(r io.Reader) *pktReader { + return &pktReader{r: bufio.NewReader(r)} +} + +// next returns the next packet. A data packet's payload has its trailing +// newline removed. +func (p *pktReader) next() (pktKind, string, error) { + var header [pktHeaderLen]byte + if _, err := io.ReadFull(p.r, header[:]); err != nil { + return 0, "", err + } + n, err := strconv.ParseUint(string(header[:]), 16, 16) + if err != nil { + return 0, "", fmt.Errorf("invalid pkt-line length %q", header) + } + if n <= pktSpecialLast { + return pktKind(n + 1), "", nil + } + if n < pktHeaderLen || n > pktMaxLen { + return 0, "", fmt.Errorf("invalid pkt-line length %d", n) + } + payload := make([]byte, n-pktHeaderLen) + if _, err := io.ReadFull(p.r, payload); err != nil { + return 0, "", err + } + return pktData, strings.TrimSuffix(string(payload), "\n"), nil +} diff --git a/internal/gitcache/refresh.go b/internal/gitcache/refresh.go new file mode 100644 index 0000000..f467a3d --- /dev/null +++ b/internal/gitcache/refresh.go @@ -0,0 +1,402 @@ +package gitcache + +import ( + "context" + "errors" + "fmt" + "maps" + "os" + "path/filepath" + "strings" + "sync" + "time" + + "github.com/git-pkgs/proxy/internal/metrics" +) + +const ( + // fetchTimeout bounds one refresh, including a cold clone of a large + // repository. + fetchTimeout = time.Hour + // defaultRefCheckTimeout bounds the ref check, so an upstream that + // stalls mid-response does not hold a repository's refresh for + // fetchTimeout. + defaultRefCheckTimeout = 2 * time.Minute + // tooLargeRetryAfter is how long a repository that passed + // git.max_repo_size is left alone before it is tried again. + tooLargeRetryAfter = time.Hour +) + +// errUpstreamUnanswered marks a fetch the upstream never answered, such as +// one during an outage. +var errUpstreamUnanswered = errors.New("upstream did not answer the fetch") + +// errClosed is returned for a refresh asked for once the cache is closing. +var errClosed = errors.New("git cache is closed") + +// refreshCall is a refresh in progress, shared by every request for the +// repository that arrives while it runs. +type refreshCall struct { + done chan struct{} + err error + // checked is closed once the upstream's branches and tags have been + // compared with the cached ones, and fetching then says whether they + // differ, so a fetch follows. + checked chan struct{} + fetching bool + checkedOnce sync.Once +} + +func newRefreshCall() *refreshCall { + return &refreshCall{done: make(chan struct{}), checked: make(chan struct{})} +} + +func (call *refreshCall) markChecked(fetching bool) { + call.checkedOnce.Do(func() { + call.fetching = fetching + close(call.checked) + }) +} + +// ensureFresh brings the repository up to date with its upstream before it is +// served. A repository checked successfully within StaleMaxAge is served +// from the cache if the upstream fails or its check takes longer than +// RefreshWait; the refresh carries on in the background either way. Once the +// check finds new commits, their fetch is waited for, so a clone right after +// a push gets them. One never cloned, or not checked within StaleMaxAge, is +// served only once the refresh succeeds. +func (c *Cache) ensureFresh(ctx context.Context, rp *repo, repoURL string) error { + call := c.startRefresh(rp, repoURL) + checked := time.Unix(0, rp.lastChecked.Load()) + if !rp.exists() || time.Since(checked) > c.opts.StaleMaxAge { + select { + case <-call.done: + return call.err + case <-ctx.Done(): + return ctx.Err() + } + } + + timeout := c.opts.refreshWaitOver + if timeout == nil { + timer := time.NewTimer(c.opts.RefreshWait) + defer timer.Stop() + timeout = timer.C + } + refChecked := call.checked + for { + select { + case <-refChecked: + refChecked = nil + if call.fetching { + timeout = nil + } + case <-call.done: + if call.err != nil && servesStale(call.err) { + c.logger.Warn("git cache: refresh failed, serving cached copy", + "repository", rp.key, "checked", checked, "error", call.err) + return nil + } + return call.err + case <-timeout: + // select picks at random when the check finished just as the + // wait ran out; a check found new commits in time still counts. + select { + case <-refChecked: + refChecked = nil + if call.fetching { + timeout = nil + continue + } + default: + } + c.logger.Info("git cache: upstream check still running, serving cached copy", + "repository", rp.key, "checked", checked) + return nil + case <-ctx.Done(): + return ctx.Err() + } + } +} + +// servesStale reports whether the cached copy may be served after err: not +// when the upstream says the repository is gone or refuses access to it. +func servesStale(err error) bool { + return !errors.Is(err, ErrNotFound) && !errors.Is(err, ErrRefused) +} + +// startRefresh starts a refresh of the repository, or joins the one running. +// The refresh holds a use of the repository until it ends. +func (c *Cache) startRefresh(rp *repo, repoURL string) *refreshCall { + c.mu.Lock() + defer c.mu.Unlock() + if rp.refreshing != nil { + return rp.refreshing + } + call := newRefreshCall() + if c.closed { + call.err = errClosed + close(call.done) + return call + } + rp.refreshing = call + rp.users++ + c.refreshes.Add(1) + go func() { + defer c.refreshes.Done() + ctx, cancel := context.WithTimeout(c.ctx, fetchTimeout) + start := time.Now() + call.err = c.refresh(ctx, rp, repoURL, call.markChecked) + call.markChecked(false) + cancel() + metrics.RecordUpstreamFetch(ecosystem, time.Since(start)) + // A refresh cut short by Close is not an upstream failure. + if call.err != nil && c.ctx.Err() == nil { + metrics.RecordUpstreamError(ecosystem, errorType(call.err), metrics.FailureDetail{URL: repoURL, Err: call.err}) + c.logger.Warn("git cache: refresh failed", "repository", rp.key, "error", call.err) + } + c.mu.Lock() + rp.refreshing = nil + if call.err != nil && !servesStale(call.err) { + rp.refused = call.err + } + c.mu.Unlock() + c.release(rp) + close(call.done) + if call.err == nil { + c.evict() + } + }() + return call +} + +// refresh checks the upstream's branches and tags and fetches if they differ +// from the cached ones, cloning the repository if it is not cached yet. +// checked is called once a cached repository's refs have been compared. +func (c *Cache) refresh(ctx context.Context, rp *repo, repoURL string, checked func(fetching bool)) error { + if c.isTooLarge(rp.key) { + return ErrTooLarge + } + checkCtx, cancel := context.WithTimeout(ctx, c.refCheckTimeout) + remote, err := c.listUpstreamRefs(checkCtx, repoURL) + cancel() + if err != nil { + return err + } + // The upstream lets us read the repository again, even if the fetch + // below fails. + c.mu.Lock() + rp.refused = nil + c.mu.Unlock() + if rp.exists() { + err = c.update(ctx, rp, repoURL, remote, checked) + } else { + err = c.clone(ctx, rp, repoURL, remote) + } + if errors.Is(err, ErrTooLarge) { + c.markTooLarge(rp.key) + } + if err != nil { + return err + } + now := time.Now() + rp.lastChecked.Store(now.UnixNano()) + touch(rp.dir, checkedStamp, now) + return nil +} + +// clone builds the repository in a temporary directory and moves it into +// place, so no request ever reads a partial clone. +func (c *Cache) clone(ctx context.Context, rp *repo, repoURL string, remote remoteRefs) error { + // Released after the temporary clone is removed. + res := c.newReservation() + defer res.release() + tmp, err := os.MkdirTemp(c.tmpDir(), "clone-") + if err != nil { + return err + } + defer func() { _ = os.RemoveAll(tmp) }() + + if _, err := c.run(ctx, tmp, "init", "--quiet", "--bare"); err != nil { + return err + } + if err := c.fetch(ctx, tmp, repoURL, c.opts.MaxRepoSize, res, refreshFlags, branchesAndTags...); err != nil { + return err + } + if err := c.setHead(ctx, tmp, remote, ""); err != nil { + return err + } + size := dirSize(tmp) + if c.opts.MaxRepoSize > 0 && size > c.opts.MaxRepoSize { + return ErrTooLarge + } + if err := os.MkdirAll(filepath.Dir(rp.dir), dirPermissions); err != nil { + return err + } + if err := os.Rename(tmp, rp.dir); err != nil { + return fmt.Errorf("moving clone into place: %w", err) + } + res.settle(rp, size) + c.logger.Info("git cache: cloned repository", "repository", rp.key, "size", size) + return nil +} + +// update fetches when the upstream's branches or tags differ from the cached +// ones, and follows a change of the upstream's default branch. +func (c *Cache) update(ctx context.Context, rp *repo, repoURL string, remote remoteRefs, checked func(fetching bool)) error { + unlock, err := rp.lockWrites(ctx) + if err != nil { + return err + } + defer unlock() + local, wanted, err := c.localRefs(ctx, rp.dir) + if err != nil { + return err + } + fetched := !maps.Equal(local, remote.refs) + checked(fetched) + if fetched { + limit, err := c.fetchLimit(rp) + if err != nil { + return err + } + res := c.newReservation() + err = c.fetch(ctx, rp.dir, repoURL, limit, res, refreshFlags, branchesAndTags...) + res.settle(rp, dirSize(rp.dir)) + if err != nil { + return err + } + } + if err := c.pruneWanted(ctx, rp.dir, wanted, fetched); err != nil { + c.logger.Warn("git cache: pruning wanted refs failed", "repository", rp.key, "error", err) + } + head, _ := c.run(ctx, rp.dir, "symbolic-ref", "--quiet", "HEAD") + return c.setHead(ctx, rp.dir, remote, strings.TrimSpace(head)) +} + +// branchesAndTags are the refspecs of a refresh. A bare clone has none of its +// own, and other refs, such as Gerrit's refs/changes, are left out. +var branchesAndTags = []string{"+refs/heads/*:refs/heads/*", "+refs/tags/*:refs/tags/*"} + +// refreshFlags delete the branches and tags the upstream no longer has, and +// update all refs together, so a client served while a refresh runs never +// sees only some of them moved. +var refreshFlags = []string{"--prune", "--atomic"} + +// fetchLimit returns how many more bytes the repository may take, 0 for no +// limit. +func (c *Cache) fetchLimit(rp *repo) (int64, error) { + if c.opts.MaxRepoSize <= 0 { + return 0, nil + } + limit := c.opts.MaxRepoSize - rp.size.Load() + if limit <= 0 { + return 0, ErrTooLarge + } + return limit, nil +} + +// fetch fetches refspecs from the upstream into the repository at dir, +// through the relay, adding flags to git fetch. limit caps the bytes +// fetched, 0 for no cap, and res holds space within MaxSize for them. +func (c *Cache) fetch(ctx context.Context, dir, repoURL string, limit int64, res *reservation, flags []string, refspecs ...string) error { + select { + case c.fetches <- struct{}{}: + defer func() { <-c.fetches }() + case <-ctx.Done(): + return ctx.Err() + } + + relayURL, route, unregister := c.relay.register(ctx, repoURL, limit, res) + defer unregister() + args := append([]string{"fetch", "--quiet", "--no-write-fetch-head"}, flags...) + _, err := c.run(ctx, dir, append(append(args, relayURL), refspecs...)...) + if err != nil { + // index-pack leaves its temporary pack behind when its input ends + // early. Fetches into a repository run one at a time, so any left + // now are this fetch's. + leftovers, _ := filepath.Glob(filepath.Join(dir, "objects", "pack", "tmp_*")) + for _, path := range leftovers { + _ = os.Remove(path) + } + } + if route.exceeded.Load() { + return ErrTooLarge + } + if route.full.Load() { + return ErrCacheFull + } + if status := route.redirected.Load(); status != 0 { + return upstreamStatusError(int(status)) + } + if err != nil && !route.answered.Load() { + return fmt.Errorf("%w: %w", errUpstreamUnanswered, err) + } + return err +} + +// setHead points HEAD at the upstream's default branch, when the upstream +// names one and it is among the cached branches. +func (c *Cache) setHead(ctx context.Context, dir string, remote remoteRefs, current string) error { + if remote.head == "" || remote.head == current { + return nil + } + if _, ok := remote.refs[remote.head]; !ok { + return nil + } + _, err := c.run(ctx, dir, "symbolic-ref", "HEAD", remote.head) + return err +} + +// localRefs lists the cached branches and tags, and the names of the wanted +// refs. +func (c *Cache) localRefs(ctx context.Context, dir string) (map[string]string, []string, error) { + out, err := c.run(ctx, dir, "for-each-ref", "--format=%(objectname) %(refname)", headsPrefix, tagsPrefix, wantedPrefix) + if err != nil { + return nil, nil, err + } + refs := make(map[string]string) + var wanted []string + for line := range strings.Lines(out) { + oid, name, ok := strings.Cut(strings.TrimSuffix(line, "\n"), " ") + switch { + case !ok: + case strings.HasPrefix(name, wantedPrefix): + wanted = append(wanted, name) + default: + refs[name] = oid + } + } + return refs, wanted, nil +} + +func errorType(err error) string { + switch { + case errors.Is(err, ErrNotFound): + return "not_found" + case errors.Is(err, ErrRefused): + return "refused" + case errors.Is(err, ErrTooLarge): + return "too_large" + case errors.Is(err, ErrCacheFull): + return "cache_full" + } + return "fetch_failed" +} + +func (c *Cache) isTooLarge(key string) bool { + c.mu.Lock() + defer c.mu.Unlock() + since, ok := c.tooLarge[key] + if ok && time.Since(since) >= tooLargeRetryAfter { + delete(c.tooLarge, key) + return false + } + return ok +} + +func (c *Cache) markTooLarge(key string) { + c.mu.Lock() + defer c.mu.Unlock() + c.tooLarge[key] = time.Now() +} diff --git a/internal/gitcache/relay.go b/internal/gitcache/relay.go new file mode 100644 index 0000000..468879c --- /dev/null +++ b/internal/gitcache/relay.go @@ -0,0 +1,205 @@ +package gitcache + +import ( + "context" + "crypto/rand" + "encoding/hex" + "errors" + "io" + "log/slog" + "net" + "net/http" + "strings" + "sync" + "sync/atomic" + "time" +) + +const ( + relayIDBytes = 16 + relayReadHeaderTimeout = 30 * time.Second +) + +// relay is a loopback HTTP server that every git fetch the cache runs goes +// through. git never reaches the network itself: each fetch gets a route to +// one upstream repository, and the relay forwards its requests with the +// proxy's upstream client, so address checks, upstream.auth, the access log +// and the no-redirect rule apply as they do to the proxy's own requests, and +// git never sees a credential. +type relay struct { + client *http.Client + logger *slog.Logger + listener net.Listener + server *http.Server + base string + + mu sync.Mutex + routes map[string]*relayRoute +} + +type relayRoute struct { + repoURL string + // ctx ends when the fetch does. + ctx context.Context + // limit caps the response bytes the route relays, 0 for no cap, and + // budget, when set, holds space within MaxSize for them. exceeded and + // full record which of them stopped the route. + limit int64 + budget *reservation + relayed atomic.Int64 + exceeded atomic.Bool + full atomic.Bool + // answered records that the upstream answered a git-upload-pack + // request, so a failed fetch was not an outage. + answered atomic.Bool + // redirected records the status of a redirect the upstream answered + // with, 0 for none. + redirected atomic.Int32 +} + +func newRelay(client *http.Client, logger *slog.Logger) (*relay, error) { + listener, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + if listener, err = net.Listen("tcp", "[::1]:0"); err != nil { + return nil, err + } + } + rl := &relay{ + client: client, + logger: logger, + listener: listener, + base: "http://" + listener.Addr().String(), + routes: make(map[string]*relayRoute), + } + rl.server = &http.Server{Handler: rl, ReadHeaderTimeout: relayReadHeaderTimeout} + go func() { + if err := rl.server.Serve(listener); err != nil && !errors.Is(err, http.ErrServerClosed) { + logger.Error("git relay stopped", "error", err) + } + }() + return rl, nil +} + +func (rl *relay) close() error { + return rl.server.Close() +} + +// register adds a route to repoURL for a fetch running with ctx and returns +// the URL git fetches from and a function that removes the route and stops +// its requests. +func (rl *relay) register(ctx context.Context, repoURL string, limit int64, budget *reservation) (string, *relayRoute, func()) { + var b [relayIDBytes]byte + _, _ = rand.Read(b[:]) + id := hex.EncodeToString(b[:]) + ctx, cancel := context.WithCancel(ctx) + route := &relayRoute{repoURL: repoURL, ctx: ctx, limit: limit, budget: budget} + + rl.mu.Lock() + rl.routes[id] = route + rl.mu.Unlock() + + return rl.base + "/" + id, route, func() { + rl.mu.Lock() + delete(rl.routes, id) + rl.mu.Unlock() + cancel() + } +} + +func (rl *relay) ServeHTTP(w http.ResponseWriter, r *http.Request) { + id, suffix, _ := strings.Cut(strings.TrimPrefix(r.URL.Path, "/"), "/") + rl.mu.Lock() + route := rl.routes[id] + rl.mu.Unlock() + if route == nil { + http.NotFound(w, r) + return + } + + var target string + switch { + case suffix == "info/refs" && r.Method == http.MethodGet && r.URL.RawQuery == "service=git-upload-pack": + target = route.repoURL + "/info/refs?service=git-upload-pack" + case suffix == "git-upload-pack" && r.Method == http.MethodPost: + target = route.repoURL + "/git-upload-pack" + default: + http.NotFound(w, r) + return + } + + ctx, cancel := context.WithCancel(r.Context()) + defer cancel() + defer context.AfterFunc(route.ctx, cancel)() + out, err := http.NewRequestWithContext(ctx, r.Method, target, r.Body) + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + out.ContentLength = r.ContentLength + for _, name := range []string{"Git-Protocol", "Content-Type", "Content-Encoding", "Accept", "User-Agent"} { + if value := r.Header.Get(name); value != "" { + out.Header.Set(name, value) + } + } + + resp, err := rl.client.Do(out) + if err != nil { + if ctx.Err() == nil { + rl.logger.Warn("git relay: upstream request failed", "upstream", route.repoURL, "error", err) + } + http.Error(w, "upstream request failed", http.StatusBadGateway) + return + } + defer func() { _ = resp.Body.Close() }() + // A redirect passed on would send git to the Location itself. + if resp.StatusCode >= http.StatusMultipleChoices && resp.StatusCode < http.StatusBadRequest { + route.redirected.Store(int32(resp.StatusCode)) + http.Error(w, "upstream redirect not followed", http.StatusBadGateway) + return + } + + if r.Method == http.MethodPost && resp.StatusCode == http.StatusOK { + route.answered.Store(true) + } + if ct := resp.Header.Get("Content-Type"); ct != "" { + w.Header().Set("Content-Type", ct) + } + w.WriteHeader(resp.StatusCode) + if _, err := io.Copy(w, &routeReader{ctx: ctx, r: resp.Body, route: route}); err != nil { + if r.Context().Err() != nil { + // git went away; there is no one to tell. + return + } + if ctx.Err() == nil && !route.exceeded.Load() && !route.full.Load() { + rl.logger.Warn("git relay: copying upstream response", "upstream", route.repoURL, "error", err) + } + // Cut the connection so git fails rather than taking a response + // that ended early for one that is complete. + panic(http.ErrAbortHandler) + } +} + +// routeReader counts relayed bytes against the route's limit and budget. +type routeReader struct { + ctx context.Context + r io.Reader + route *relayRoute +} + +func (rr *routeReader) Read(p []byte) (int, error) { + n, err := rr.r.Read(p) + total := rr.route.relayed.Add(int64(n)) + if rr.route.limit > 0 && total > rr.route.limit { + rr.route.exceeded.Store(true) + return 0, ErrTooLarge + } + if rr.route.budget != nil { + if err := rr.route.budget.cover(rr.ctx, total); err != nil { + if errors.Is(err, ErrCacheFull) { + rr.route.full.Store(true) + } + return 0, err + } + } + return n, err +} diff --git a/internal/gitcache/relay_test.go b/internal/gitcache/relay_test.go new file mode 100644 index 0000000..309e727 --- /dev/null +++ b/internal/gitcache/relay_test.go @@ -0,0 +1,117 @@ +package gitcache + +import ( + "io" + "log/slog" + "net/http" + "net/http/httptest" + "strings" + "sync" + "sync/atomic" + "testing" +) + +func newTestRelay(t *testing.T) *relay { + t.Helper() + rl, err := newRelay(&http.Client{}, slog.New(slog.DiscardHandler)) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = rl.close() }) + return rl +} + +func TestRelayOnlyForwardsFetchRequests(t *testing.T) { + var forwarded atomic.Int32 + upstream := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) { + forwarded.Add(1) + })) + defer upstream.Close() + rl := newTestRelay(t) + base, _, unregister := rl.register(t.Context(), upstream.URL+"/repo", 0, nil) + + refused := []struct{ method, url string }{ + {http.MethodGet, rl.base + "/unknown/info/refs?service=git-upload-pack"}, + {http.MethodGet, base + "/info/refs?service=git-receive-pack"}, + {http.MethodPost, base + "/git-receive-pack"}, + {http.MethodGet, base + "/HEAD"}, + {http.MethodGet, base + "/git-upload-pack"}, + } + for _, r := range refused { + req, _ := http.NewRequest(r.method, r.url, nil) + resp, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatal(err) + } + _ = resp.Body.Close() + if resp.StatusCode != http.StatusNotFound { + t.Errorf("%s %s: status %d, want 404", r.method, r.url, resp.StatusCode) + } + } + if got := forwarded.Load(); got != 0 { + t.Errorf("forwarded %d refused requests", got) + } + + unregister() + resp, err := http.Get(base + "/info/refs?service=git-upload-pack") + if err != nil { + t.Fatal(err) + } + _ = resp.Body.Close() + if resp.StatusCode != http.StatusNotFound || forwarded.Load() != 0 { + t.Errorf("unregistered route: status %d, forwarded %d", resp.StatusCode, forwarded.Load()) + } +} + +// TestRelayStopsAtLimit checks a fetch over git.max_repo_size is cut off +// rather than downloaded in full and thrown away. +func TestRelayStopsAtLimit(t *testing.T) { + const size, limit = 4 << 20, 64 << 10 + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _, _ = io.Copy(io.Discard, r.Body) + _, _ = io.Copy(w, io.LimitReader(zeros{}, size)) + })) + defer upstream.Close() + var logs strings.Builder + var logMu sync.Mutex + rl, err := newRelay(&http.Client{}, slog.New(slog.NewTextHandler(lockedWriter{&logMu, &logs}, nil))) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = rl.close() }) + base, route, unregister := rl.register(t.Context(), upstream.URL+"/repo", limit, nil) + defer unregister() + + resp, err := http.Post(base+"/git-upload-pack", requestType, strings.NewReader(pktFlush)) + if err != nil { + t.Fatal(err) + } + n, err := io.Copy(io.Discard, resp.Body) + _ = resp.Body.Close() + if err == nil { + t.Errorf("read %d bytes without an error", n) + } + if !route.exceeded.Load() || route.relayed.Load() > size/2 { + logMu.Lock() + defer logMu.Unlock() + t.Errorf("exceeded %v after relaying %d of %d bytes; relay log:\n%s", route.exceeded.Load(), route.relayed.Load(), size, logs.String()) + } +} + +type lockedWriter struct { + mu *sync.Mutex + w io.Writer +} + +func (l lockedWriter) Write(p []byte) (int, error) { + l.mu.Lock() + defer l.mu.Unlock() + return l.w.Write(p) +} + +type zeros struct{} + +func (zeros) Read(p []byte) (int, error) { + clear(p) + return len(p), nil +} diff --git a/internal/gitcache/serve.go b/internal/gitcache/serve.go new file mode 100644 index 0000000..5d80938 --- /dev/null +++ b/internal/gitcache/serve.go @@ -0,0 +1,351 @@ +package gitcache + +import ( + "bytes" + "compress/gzip" + "context" + "errors" + "io" + "math" + "net/http" + "os" + "path/filepath" + "regexp" + "slices" + "strings" + "sync/atomic" + "time" +) + +// gitProtocolPattern is what a Git-Protocol header may hold, such as +// "version=2". It is passed to upload-pack in its environment. +var gitProtocolPattern = regexp.MustCompile(`^[A-Za-z0-9=:._-]*$`) + +var errInvalidKey = errors.New("invalid repository key") + +// Lease is a use of a cached repository. The repository is not evicted +// until the lease is released. +type Lease struct { + cache *Cache + repo *repo + repoURL string + hit bool + fetchWants bool +} + +// OpenOptions says what Open does besides returning the repository. +type OpenOptions struct { + // Refresh brings a cached repository up to date with the upstream first, + // or leaves it as it is when the upstream fails or is slow and the copy + // is recent enough (see Options). + Refresh bool + // FetchWants lets ServeUploadPack fetch commits a client asks for by ID + // that the cache lacks. Leave it off where a fetch by ID could reach + // commits the client may not read through this repository, such as + // GitHub forks with credentials configured. + FetchWants bool + // NoCheck leaves a cached repository as it is, for a caller that + // refreshes it itself. Otherwise a cached repository is refused when the + // last refresh found it gone or refused upstream, and refreshed first + // when it was not checked within StaleMaxAge. + NoCheck bool +} + +// Open returns a lease on the repository cached under key, a relative path +// such as github-1a2b3c4d/acme/widgets.git, whose upstream is repoURL. A +// repository not cached yet is cloned first. +func (c *Cache) Open(ctx context.Context, key, repoURL string, opts OpenOptions) (*Lease, error) { + if !strings.HasSuffix(key, ".git") || !filepath.IsLocal(filepath.FromSlash(key)) { + return nil, errInvalidKey + } + rp := c.acquire(key) + hit := rp.exists() + var err error + switch { + case opts.Refresh || !hit: + err = c.ensureFresh(ctx, rp, repoURL) + if err == nil && hit && !opts.NoCheck { + // A refresh still running or failed serves the cached copy, + // but not one the upstream refused since and no check has + // cleared. + err = c.refusal(rp) + } + case !opts.NoCheck: + err = c.checkServable(ctx, rp, repoURL) + } + if err != nil { + c.release(rp) + return nil, err + } + return &Lease{cache: c, repo: rp, repoURL: repoURL, hit: hit, fetchWants: opts.FetchWants}, nil +} + +// uploadPackGrace is how long past StaleMaxAge a copy is still served +// without a check to the upload-pack requests that follow a client's +// info/refs, so a clone checks the upstream once. +const uploadPackGrace = time.Minute + +// checkServable refreshes a cached repository first when the last refresh +// found it gone or refused upstream, or it was not checked recently, and +// refuses it while that refusal stands. +func (c *Cache) checkServable(ctx context.Context, rp *repo, repoURL string) error { + // The sum saturates rather than overflow for a huge StaleMaxAge. + maxAge := c.opts.StaleMaxAge + uploadPackGrace + if maxAge < c.opts.StaleMaxAge { + maxAge = math.MaxInt64 + } + if c.refusal(rp) == nil && time.Since(time.Unix(0, rp.lastChecked.Load())) <= maxAge { + return nil + } + if err := c.ensureFresh(ctx, rp, repoURL); err != nil { + return err + } + return c.refusal(rp) +} + +// refusal returns the error of the last refresh that found the repository +// gone or refused upstream, until a ref check succeeds. +func (c *Cache) refusal(rp *repo) error { + c.mu.Lock() + defer c.mu.Unlock() + return rp.refused +} + +// Hit reports whether the repository was already cached when it was opened. +func (l *Lease) Hit() bool { + return l.hit +} + +// Release ends the lease. +func (l *Lease) Release() { + l.cache.release(l.repo) +} + +// ServeInfoRefs answers GET info/refs?service=git-upload-pack. +func (l *Lease) ServeInfoRefs(w http.ResponseWriter, r *http.Request) { + c := l.cache + if !takeSlot(r.Context(), c.refListings) { + return + } + defer func() { <-c.refListings }() + protocol := gitProtocol(r) + setNoCache(w) + w.Header().Set("Content-Type", advertisementType) + // Protocol v2 starts with its version line; earlier versions with the + // service name. + if !isProtocolV2(protocol) { + _, _ = io.WriteString(w, pktLine("# service=git-upload-pack\n")+pktFlush) + } + c.uploadPack(w, r, l.repo, protocol, nil, "--advertise-refs") +} + +// ServeUploadPack answers POST git-upload-pack with req, the request's body +// as ReadRequest read it. With OpenOptions.FetchWants, commits the request +// wants that the cache lacks are fetched from the upstream first. +func (l *Lease) ServeUploadPack(w http.ResponseWriter, r *http.Request, req *Request) { + c := l.cache + body := req.reader() + if req.gzip { + gz, err := gzip.NewReader(body) + if err != nil { + http.Error(w, "invalid gzip body", http.StatusBadRequest) + return + } + defer func() { _ = gz.Close() }() + // A gzip stream of any length can decode to almost nothing. + decoded := &bodyLimit{r: gz, remaining: c.maxRequestBody} + defer func() { + if decoded.exceeded.Load() { + c.logger.Warn("git cache: request body passed the limit", + "repository", l.repo.key, "limit", c.maxRequestBody) + } + }() + body = decoded + } + if l.fetchWants { + var wants []string + wants, body = readWants(body) + if err := c.fetchMissingWants(r.Context(), l.repo, l.repoURL, wants); err != nil && r.Context().Err() == nil { + // upload-pack reports the missing objects to the client. + c.logger.Warn("git cache: fetching wanted objects failed", "repository", l.repo.key, "error", err) + } + } + var command string + command, body = requestCommand(body) + // ls-refs builds no pack, so it waits for a ref listing slot rather than + // behind clones. + slots := c.uploadPacks + if command == "ls-refs" { + slots = c.refListings + } + if !takeSlot(r.Context(), slots) { + return + } + defer func() { <-slots }() + setNoCache(w) + w.Header().Set("Content-Type", resultType) + c.uploadPack(w, r, l.repo, gitProtocol(r), body) +} + +// takeSlot takes a slot from slots, or reports false once ctx is done. +func takeSlot(ctx context.Context, slots chan struct{}) bool { + select { + case slots <- struct{}{}: + return true + case <-ctx.Done(): + return false + } +} + +// requestCommand returns the protocol v2 command an upload-pack request +// starts with, such as "fetch", or "" for an earlier protocol, with a reader +// that replays the whole body. +func requestCommand(body io.Reader) (string, io.Reader) { + var consumed bytes.Buffer + _, line, _ := newPktReader(io.TeeReader(body, &consumed)).next() + command, ok := strings.CutPrefix(line, "command=") + if !ok { + command = "" + } + return command, io.MultiReader(&consumed, body) +} + +// servingConfig gives each pack-objects that upload-pack runs one +// delta-search thread with a bounded window, where git defaults to a thread +// per CPU and no bound. +var servingConfig = []string{"-c", "pack.threads=1", "-c", "pack.windowMemory=64m"} + +// uploadPack runs git upload-pack on the cached repository in stateless mode, +// the way git http-backend does. +func (c *Cache) uploadPack(w http.ResponseWriter, r *http.Request, rp *repo, protocol string, stdin io.Reader, args ...string) { + var env []string + if protocol != "" { + env = append(env, "GIT_PROTOCOL="+protocol) + } + args = slices.Concat(servingConfig, []string{"upload-pack", "--stateless-rpc"}, args, []string{rp.dir}) + cmd := c.command(r.Context(), env, args...) + cmd.Stdin = stdin + cmd.Stdout = w + stderr := &limitedBuffer{max: maxStderr} + cmd.Stderr = stderr + if err := cmd.Run(); err != nil && r.Context().Err() == nil { + c.logger.Warn("git cache: upload-pack failed", + "repository", rp.key, "error", err, "stderr", strings.TrimSpace(stderr.String())) + } +} + +// defaultMaxRequestBody bounds an upload-pack request far above any real +// negotiation, so a small gzip body cannot feed upload-pack for as long as +// the request may run. +const defaultMaxRequestBody = 100 << 20 + +// maxMemoryRequest is the most of a request body kept in memory; the rest of +// a larger one goes to a temporary file. +const maxMemoryRequest = 1 << 20 + +// ErrRequestTooLarge is returned by ReadRequest for a body past the limit. +var ErrRequestTooLarge = errors.New("request body too large") + +// Request is the body of a POST git-upload-pack request, read in full +// before anything is started for it. Stateless requests are complete once +// sent, so a client that sends one slowly, or not at all, holds no +// upload-pack process and is bound by the server's read timeout. +type Request struct { + gzip bool + data []byte + file *os.File +} + +// ReadRequest reads the body of a POST git-upload-pack request, still +// encoded. A body past the limit fails with ErrRequestTooLarge. Close the +// request once it is served. +func (c *Cache) ReadRequest(r *http.Request) (*Request, error) { + req := &Request{gzip: r.Header.Get("Content-Encoding") == "gzip"} + body := &bodyLimit{r: r.Body, remaining: c.maxRequestBody} + var buf bytes.Buffer + if _, err := buf.ReadFrom(io.LimitReader(body, maxMemoryRequest)); err != nil { + return nil, err + } + if buf.Len() < maxMemoryRequest { + req.data = buf.Bytes() + return req, nil + } + file, err := os.CreateTemp(c.tmpDir(), "git-upload-pack-*") + if err != nil { + return nil, err + } + req.file = file + if _, err := buf.WriteTo(file); err != nil { + req.Close() + return nil, err + } + if _, err := io.Copy(file, body); err != nil { + req.Close() + return nil, err + } + return req, nil +} + +// Close removes any temporary file holding the request. +func (req *Request) Close() { + if req.file != nil { + _ = req.file.Close() + _ = os.Remove(req.file.Name()) + } +} + +func (req *Request) reader() io.Reader { + if req.file != nil { + return io.NewSectionReader(req.file, 0, 1<<63-1) + } + return bytes.NewReader(req.data) +} + +// bodyLimit fails reads past remaining bytes, where io.LimitReader would end +// the body quietly and leave upload-pack a request cut short. +type bodyLimit struct { + r io.Reader + remaining int64 + exceeded atomic.Bool +} + +func (b *bodyLimit) Read(p []byte) (int, error) { + if b.exceeded.Load() { + return 0, ErrRequestTooLarge + } + // One byte past the limit tells a longer body from one that ends at it. + if int64(len(p)) > b.remaining+1 { + p = p[:b.remaining+1] + } + n, err := b.r.Read(p) + if int64(n) <= b.remaining { + b.remaining -= int64(n) + return n, err + } + n = int(b.remaining) + b.remaining = 0 + b.exceeded.Store(true) + return n, ErrRequestTooLarge +} + +func gitProtocol(r *http.Request) string { + if protocol := r.Header.Get("Git-Protocol"); gitProtocolPattern.MatchString(protocol) { + return protocol + } + return "" +} + +func isProtocolV2(protocol string) bool { + for field := range strings.SplitSeq(protocol, ":") { + if field == "version=2" { + return true + } + } + return false +} + +func setNoCache(w http.ResponseWriter) { + w.Header().Set("Expires", "Fri, 01 Jan 1980 00:00:00 GMT") + w.Header().Set("Pragma", "no-cache") + w.Header().Set("Cache-Control", "no-cache, max-age=0, must-revalidate") +} diff --git a/internal/gitcache/serve_test.go b/internal/gitcache/serve_test.go new file mode 100644 index 0000000..ca53e40 --- /dev/null +++ b/internal/gitcache/serve_test.go @@ -0,0 +1,431 @@ +package gitcache + +import ( + "bytes" + "compress/gzip" + "errors" + "fmt" + "io" + "net/http" + "os" + "os/exec" + "path/filepath" + "slices" + "strings" + "sync" + "testing" + "time" +) + +// TestRequestBodies sends the bodies git sends for large requests: gzipped, +// or chunked once one outgrows http.postBuffer. +func TestRequestBodies(t *testing.T) { + upstream := newFakeUpstream(t) + upstream.newRepo("repo") + tc := newTestCache(t, upstream.server.URL, nil) + tc.clone(t, "repo") + + lsRefs := pktLine("command=ls-refs\n") + pktDelim + pktLine("ref-prefix refs/heads/\n") + pktFlush + var gzipped bytes.Buffer + gz := gzip.NewWriter(&gzipped) + _, _ = io.WriteString(gz, lsRefs) + _ = gz.Close() + for _, tt := range []struct { + name string + body io.Reader + encoding string + }{ + // A reader of unknown length is sent chunked. + {"chunked", io.MultiReader(strings.NewReader(lsRefs)), ""}, + {"gzip", &gzipped, "gzip"}, + } { + req, _ := http.NewRequest(http.MethodPost, tc.url("repo")+"/git-upload-pack", tt.body) + req.Header.Set("Content-Type", requestType) + req.Header.Set("Git-Protocol", "version=2") + if tt.encoding != "" { + req.Header.Set("Content-Encoding", tt.encoding) + } + resp, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatal(err) + } + out, _ := io.ReadAll(resp.Body) + _ = resp.Body.Close() + if resp.StatusCode != http.StatusOK || !strings.Contains(string(out), "refs/heads/main") { + t.Errorf("%s: status %d, body %q", tt.name, resp.StatusCode, out) + } + } +} + +// TestRequestBodyLimit refuses a request past the limit, before or after +// gzip, including one that is small compressed. +func TestRequestBodyLimit(t *testing.T) { + const limit = 4096 + upstream := newFakeUpstream(t) + upstream.newRepo("repo") + tc := newTestCache(t, upstream.server.URL, func(o *Options) { o.maxRequestBody = limit }) + tc.clone(t, "repo") + + lsRefs := func(prefixes int) string { + return pktLine("command=ls-refs\n") + pktDelim + + strings.Repeat(pktLine("ref-prefix refs/heads/\n"), prefixes) + pktFlush + } + gzipped := func(body string) *bytes.Buffer { + var buf bytes.Buffer + gz := gzip.NewWriter(&buf) + _, _ = io.WriteString(gz, body) + _ = gz.Close() + return &buf + } + small, large := lsRefs(10), lsRefs(200) + if len(small) > limit || len(large) <= limit { + t.Fatalf("bodies of %d and %d bytes do not straddle the limit", len(small), len(large)) + } + compressed := gzipped(large) + if compressed.Len() > limit { + t.Fatalf("compressed body is %d bytes, over the limit", compressed.Len()) + } + // Empty gzip members before a small body: long on the wire, short decoded. + var padded bytes.Buffer + for empty := gzipped(""); padded.Len() <= limit; { + padded.Write(empty.Bytes()) + } + padded.Write(gzipped(small).Bytes()) + for _, tt := range []struct { + name string + body io.Reader + encoding string + served bool + }{ + {"small", strings.NewReader(small), "", true}, + {"small gzip", gzipped(small), "gzip", true}, + {"large", strings.NewReader(large), "", false}, + {"large gzip", compressed, "gzip", false}, + {"padded gzip", &padded, "gzip", false}, + } { + req, _ := http.NewRequest(http.MethodPost, tc.url("repo")+"/git-upload-pack", tt.body) + req.Header.Set("Content-Type", requestType) + req.Header.Set("Git-Protocol", "version=2") + if tt.encoding != "" { + req.Header.Set("Content-Encoding", tt.encoding) + } + resp, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatal(err) + } + out, _ := io.ReadAll(resp.Body) + _ = resp.Body.Close() + if served := strings.Contains(string(out), "refs/heads/main"); served != tt.served { + t.Errorf("%s: served %t, want %t (status %d, body %q)", tt.name, served, tt.served, resp.StatusCode, out) + } + } +} + +// TestUploadPackSlots holds the only upload-pack slot: a clone waits for it, +// while listing refs, which builds no pack, does not. +func TestUploadPackSlots(t *testing.T) { + upstream := newFakeUpstream(t) + upstream.newRepo("repo") + tc := newTestCache(t, upstream.server.URL, func(o *Options) { o.maxUploadPacks = 1 }) + tc.clone(t, "repo") + + start := func(args ...string) <-chan error { + done := make(chan error, 1) + go func() { + out, err := tryGit(t, "", args...) + if err != nil { + err = fmt.Errorf("%w\n%s", err, out) + } + done <- err + }() + return done + } + + tc.uploadPacks <- struct{}{} + held := true + release := func() { + if held { + held = false + <-tc.uploadPacks + } + } + // A failure while the slot is held must free it for the cache to close. + defer release() + select { + case err := <-start("-c", "protocol.version=2", "ls-remote", tc.url("repo")): + if err != nil { + t.Fatalf("ls-remote: %v", err) + } + case <-time.After(10 * time.Second): + t.Fatal("ls-remote waited for the slot") + } + clone := start("clone", "--quiet", tc.url("repo"), filepath.Join(t.TempDir(), "clone")) + select { + case err := <-clone: + t.Fatalf("clone finished while the slot was held: %v", err) + case <-time.After(time.Second): + } + release() + if err := <-clone; err != nil { + t.Errorf("clone: %v", err) + } +} + +// TestRefListingSlots holds the only slot for listing refs: info/refs and +// ls-refs wait for it. +func TestRefListingSlots(t *testing.T) { + upstream := newFakeUpstream(t) + upstream.newRepo("repo") + tc := newTestCache(t, upstream.server.URL, func(o *Options) { o.maxRefListings = 1 }) + tc.clone(t, "repo") + + post := func(body string) <-chan error { + done := make(chan error, 1) + go func() { + req, _ := http.NewRequest(http.MethodPost, tc.url("repo")+"/git-upload-pack", strings.NewReader(body)) + req.Header.Set("Content-Type", requestType) + req.Header.Set("Git-Protocol", "version=2") + resp, err := http.DefaultClient.Do(req) + if err != nil { + done <- err + return + } + out, _ := io.ReadAll(resp.Body) + _ = resp.Body.Close() + if !strings.Contains(string(out), "refs/heads/main") { + err = fmt.Errorf("status %d, body %q", resp.StatusCode, out) + } + done <- err + }() + return done + } + get := func() <-chan error { + done := make(chan error, 1) + go func() { + resp, err := http.Get(tc.url("repo") + "/info/refs?service=git-upload-pack") + if err != nil { + done <- err + return + } + out, _ := io.ReadAll(resp.Body) + _ = resp.Body.Close() + if !strings.Contains(string(out), "refs/heads/main") { + err = fmt.Errorf("status %d, body %q", resp.StatusCode, out) + } + done <- err + }() + return done + } + + tc.refListings <- struct{}{} + held := true + release := func() { + if held { + held = false + <-tc.refListings + } + } + defer release() + lsRefs := post(pktLine("command=ls-refs\n") + pktDelim + pktLine("ref-prefix refs/heads/\n") + pktFlush) + infoRefs := get() + select { + case err := <-lsRefs: + t.Fatalf("ls-refs finished while the slot was held: %v", err) + case err := <-infoRefs: + t.Fatalf("info/refs finished while the slot was held: %v", err) + case <-time.After(time.Second): + } + release() + for name, done := range map[string]<-chan error{"ls-refs": lsRefs, "info/refs": infoRefs} { + if err := <-done; err != nil { + t.Errorf("%s: %v", name, err) + } + } +} + +// TestReadRequest reads bodies kept in memory and, past maxMemoryRequest, in +// a temporary file removed on Close. +func TestReadRequest(t *testing.T) { + c := &Cache{dir: t.TempDir(), maxRequestBody: 4 << 20} + if err := os.Mkdir(c.tmpDir(), dirPermissions); err != nil { + t.Fatal(err) + } + for _, size := range []int{0, 100, maxMemoryRequest, 3 << 20} { + body := strings.Repeat("x", size) + r, _ := http.NewRequest(http.MethodPost, "/", strings.NewReader(body)) + req, err := c.ReadRequest(r) + if err != nil { + t.Fatalf("%d bytes: %v", size, err) + } + if got, _ := io.ReadAll(req.reader()); string(got) != body { + t.Errorf("%d bytes: read back %d", size, len(got)) + } + req.Close() + if req.file != nil { + if _, err := os.Stat(req.file.Name()); !errors.Is(err, os.ErrNotExist) { + t.Errorf("%d bytes: temporary file left: %v", size, err) + } + } + } + r, _ := http.NewRequest(http.MethodPost, "/", strings.NewReader(strings.Repeat("x", 5<<20))) + if _, err := c.ReadRequest(r); !errors.Is(err, ErrRequestTooLarge) { + t.Errorf("body past the limit: %v, want ErrRequestTooLarge", err) + } +} + +func TestRequestCommand(t *testing.T) { + for _, tt := range []struct{ body, want string }{ + {pktLine("command=ls-refs\n") + pktDelim + pktFlush, "ls-refs"}, + {pktLine("command=fetch\n") + pktDelim + pktLine("done\n") + pktFlush, "fetch"}, + {pktLine("want "+strings.Repeat("a", 40)+"\n") + pktFlush, ""}, + {"", ""}, + } { + command, body := requestCommand(strings.NewReader(tt.body)) + replayed, _ := io.ReadAll(body) + if command != tt.want || string(replayed) != tt.body { + t.Errorf("requestCommand(%q) = %q, %q; want %q and the whole body", tt.body, command, replayed, tt.want) + } + } +} + +// TestCloneWithChunkedRequests clones a repository with enough refs that +// git's requests, to the cache and from the cache to the upstream, outgrow +// http.postBuffer and are sent chunked. +func TestCloneWithChunkedRequests(t *testing.T) { + const tags = 2000 + upstream := newFakeUpstream(t) + work := upstream.newRepo("repo") + var stream strings.Builder + for i := 1; i <= tags; i++ { + fmt.Fprintf(&stream, "commit refs/heads/main\nmark :%d\ncommitter test %d +0000\ndata 1\n\n", i, i) + if i == 1 { + stream.WriteString("from refs/heads/main^0\n") + } + fmt.Fprintf(&stream, "reset refs/tags/t%d\nfrom :%d\n\n", i, i) + } + importer := exec.Command("git", "fast-import", "--quiet") + importer.Dir, importer.Env, importer.Stdin = work, gitEnv(t.TempDir()), strings.NewReader(stream.String()) + if out, err := importer.CombinedOutput(); err != nil { + t.Fatalf("git fast-import: %v\n%s", err, out) + } + runGit(t, work, "push", "--quiet", "origin", "main", "--tags") + tc := newTestCache(t, upstream.server.URL, nil) + + // One want per tag is about 100KB, past a postBuffer just above git's + // minimum. + clone := tc.clone(t, "repo", "-c", "http.postBuffer=66000") + if got := strings.Count(runGit(t, clone, "tag", "--list"), "\n") + 1; got != tags+1 { + t.Errorf("cloned %d tags, want %d", got, tags+1) + } +} + +func TestParseV0Advertisement(t *testing.T) { + oid := strings.Repeat("a", 40) + peeled := strings.Repeat("b", 40) + adv := pktLine(oid+" HEAD\x00multi_ack symref=HEAD:refs/heads/trunk agent=git/2\n") + + pktLine(oid+" refs/heads/trunk\n") + + pktLine(oid+" refs/tags/v1\n") + + pktLine(peeled+" refs/tags/v1^{}\n") + + pktLine(oid+" refs/changes/01/1/1\n") + + pktLine(oid+" refs/pull/1/head\n") + + pktFlush + pkts := newPktReader(strings.NewReader(adv)) + kind, line, err := pkts.next() + if err != nil { + t.Fatal(err) + } + remote, err := parseV0Advertisement(pkts, kind, line) + if err != nil { + t.Fatal(err) + } + if remote.head != "refs/heads/trunk" { + t.Errorf("head = %q", remote.head) + } + want := map[string]string{"refs/heads/trunk": oid, "refs/tags/v1": oid} + if len(remote.refs) != len(want) || remote.refs["refs/heads/trunk"] != oid || remote.refs["refs/tags/v1"] != oid { + t.Errorf("refs = %v, want %v", remote.refs, want) + } +} + +// TestCommitOnNoBranchIsFetchedByID does what actions/checkout does: fetch +// one commit by object ID, here a pull request head that is on no branch. +func TestCommitOnNoBranchIsFetchedByID(t *testing.T) { + for _, version := range []string{"0", "2"} { + t.Run("protocol v"+version, func(t *testing.T) { + upstream := newFakeUpstream(t) + work := upstream.newRepo("repo") + runGit(t, upstream.bare(), "config", "uploadpack.allowAnySHA1InWant", "true") + runGit(t, work, "checkout", "--quiet", "-b", "pr") + sha := upstream.commit(work, "pull request") + runGit(t, work, "push", "--quiet", "origin", "pr:refs/pull/1/head") + tc := newTestCache(t, upstream.server.URL, nil) + tc.clone(t, "repo") + sessions := upstream.gitSessions.Load() + + var wg sync.WaitGroup + for range 4 { + wg.Go(func() { + dir := t.TempDir() + runGit(t, dir, "init", "--quiet") + if out, err := tryGit(t, dir, "-c", "protocol.version="+version, "fetch", "--quiet", "--depth=1", tc.url("repo"), sha); err != nil { + t.Errorf("fetch by ID: %v\n%s", err, out) + return + } + if got := runGit(t, dir, "rev-parse", "FETCH_HEAD"); got != sha { + t.Errorf("FETCH_HEAD = %s, want %s", got, sha) + } + }) + } + wg.Wait() + if got := upstream.gitSessions.Load() - sessions; got != 1 { + t.Errorf("upstream saw %d fetches for the commit, want 1", got) + } + if refs := runGit(t, "", "ls-remote", tc.url("repo")); strings.Contains(refs, wantedPrefix) { + t.Errorf("advertised %s refs:\n%s", wantedPrefix, refs) + } + + // A refresh that prunes branches keeps the commit. + runGit(t, work, "push", "--quiet", "origin", "main:refs/heads/new") + tc.clone(t, "repo") + if refs := tc.cachedRefs(t); !strings.Contains(refs, wantedPrefix) || !strings.Contains(refs, "/"+sha) { + t.Errorf("refresh dropped the fetched commit:\n%s", refs) + } + }) + } +} + +func TestReadWants(t *testing.T) { + a, b := strings.Repeat("a", 40), strings.Repeat("b", 40) + tests := map[string]struct { + body string + want []string + }{ + "v0": { + pktLine("want "+a+" multi_ack side-band-64k\n") + pktLine("want "+b+"\n") + pktLine("deepen 1\n") + pktFlush + pktLine("have "+a+"\n") + pktFlush, + []string{a, b}, + }, + "v2 fetch": { + pktLine("command=fetch\n") + pktLine("agent=git/2\n") + pktDelim + pktLine("thin-pack\n") + pktLine("want "+a+"\n") + pktLine("have "+b+"\n") + pktLine("want "+b+"\n") + pktLine("done\n") + pktFlush, + []string{a, b}, + }, + "v2 ls-refs": { + pktLine("command=ls-refs\n") + pktDelim + pktLine("want "+a+"\n") + pktFlush, + nil, + }, + "not an object ID": { + pktLine("want HEAD\n") + pktFlush, + nil, + }, + } + for name, tt := range tests { + t.Run(name, func(t *testing.T) { + wants, replay := readWants(strings.NewReader(tt.body)) + if !slices.Equal(wants, tt.want) { + t.Errorf("wants = %v, want %v", wants, tt.want) + } + if got, _ := io.ReadAll(replay); string(got) != tt.body { + t.Errorf("replayed %q, want the whole body", got) + } + }) + } +} diff --git a/internal/gitcache/upstream.go b/internal/gitcache/upstream.go new file mode 100644 index 0000000..46a2667 --- /dev/null +++ b/internal/gitcache/upstream.go @@ -0,0 +1,214 @@ +package gitcache + +import ( + "context" + "errors" + "fmt" + "io" + "net/http" + "strings" +) + +const ( + advertisementType = "application/x-git-upload-pack-advertisement" + requestType = "application/x-git-upload-pack-request" + resultType = "application/x-git-upload-pack-result" + // Some servers only speak the smart protocol to clients that look like git. + gitUserAgent = "git/2 (git-pkgs-proxy)" + // maxRefsResponse bounds a ref listing; branches and tags of even large + // repositories take a few megabytes. + maxRefsResponse = 64 << 20 + + headsPrefix = "refs/heads/" + tagsPrefix = "refs/tags/" +) + +var ( + // ErrNotFound is returned when the upstream has no such repository. + ErrNotFound = errors.New("repository not found upstream") + // ErrRefused covers authentication failures and redirects. The cached + // copy is not served after one, since the upstream may have withdrawn + // access to it. + ErrRefused = errors.New("upstream refused the request") + // ErrTooLarge is returned for a repository larger than git.max_repo_size, + // or than git.max_size where that is smaller. + ErrTooLarge = errors.New("repository is larger than git.max_repo_size or git.max_size") + // ErrCacheFull is returned for a fetch cut off because repositories in + // use take what git.max_size leaves. + ErrCacheFull = errors.New("git cache is full") +) + +// remoteRefs is what a repository advertises: its branch and tag tips, and +// the branch HEAD points at. +type remoteRefs struct { + refs map[string]string + head string +} + +// listUpstreamRefs asks the upstream for its branches, tags and HEAD. With +// protocol v2 the server filters by prefix, which matters for Gerrit, where +// every patch set is a ref. Servers without v2 send every ref, and the rest +// are dropped here. +func (c *Cache) listUpstreamRefs(ctx context.Context, repoURL string) (remoteRefs, error) { + resp, err := c.upstreamRequest(ctx, http.MethodGet, repoURL+"/info/refs?service=git-upload-pack", "") + if err != nil { + return remoteRefs{}, err + } + defer func() { _ = resp.Body.Close() }() + if ct := resp.Header.Get("Content-Type"); !strings.HasPrefix(ct, advertisementType) { + return remoteRefs{}, fmt.Errorf("upstream did not answer as a smart HTTP Git server (content type %q)", ct) + } + + pkts := newPktReader(io.LimitReader(resp.Body, maxRefsResponse)) + kind, line, err := pkts.next() + if err == nil && kind == pktData && strings.HasPrefix(line, "# service=") { + if kind, _, err = pkts.next(); err == nil && kind != pktFlushKind { + err = errors.New("no flush after the service line") + } + if err == nil { + kind, line, err = pkts.next() + } + } + if err != nil { + return remoteRefs{}, fmt.Errorf("reading ref advertisement: %w", err) + } + + if kind == pktData && line == "version 2" { + return c.lsRefs(ctx, repoURL) + } + if kind == pktData && line == "version 1" { + if kind, line, err = pkts.next(); err != nil { + return remoteRefs{}, fmt.Errorf("reading ref advertisement: %w", err) + } + } + return parseV0Advertisement(pkts, kind, line) +} + +// lsRefs runs the protocol v2 ls-refs command. +func (c *Cache) lsRefs(ctx context.Context, repoURL string) (remoteRefs, error) { + body := pktLine("command=ls-refs\n") + pktDelim + + pktLine("symrefs\n") + + pktLine("ref-prefix HEAD\n") + + pktLine("ref-prefix "+headsPrefix+"\n") + + pktLine("ref-prefix "+tagsPrefix+"\n") + + pktFlush + resp, err := c.upstreamRequest(ctx, http.MethodPost, repoURL+"/git-upload-pack", body) + if err != nil { + return remoteRefs{}, err + } + defer func() { _ = resp.Body.Close() }() + + remote := remoteRefs{refs: make(map[string]string)} + pkts := newPktReader(io.LimitReader(resp.Body, maxRefsResponse)) + for { + kind, line, err := pkts.next() + if err != nil { + return remoteRefs{}, fmt.Errorf("reading ls-refs response: %w", err) + } + if kind == pktFlushKind { + return remote, nil + } + if kind != pktData { + continue + } + fields := strings.Split(line, " ") + if len(fields) < 2 { //nolint:mnd // object id and ref name + return remoteRefs{}, fmt.Errorf("invalid ls-refs line %q", line) + } + if fields[1] == "HEAD" { + for _, attr := range fields[2:] { + if target, ok := strings.CutPrefix(attr, "symref-target:"); ok { + remote.head = target + } + } + continue + } + remote.add(fields[1], fields[0]) + } +} + +// parseV0Advertisement reads a protocol v0 ref advertisement whose first +// packet has already been read. The first ref carries the capabilities, +// including where HEAD points. +func parseV0Advertisement(pkts *pktReader, kind pktKind, line string) (remoteRefs, error) { + remote := remoteRefs{refs: make(map[string]string)} + first := true + for kind != pktFlushKind { + if kind == pktData { + ref, caps, _ := strings.Cut(line, "\x00") + if first { + remote.head = symrefTarget(caps, "HEAD") + first = false + } + oid, name, ok := strings.Cut(ref, " ") + if !ok { + return remoteRefs{}, fmt.Errorf("invalid ref advertisement line %q", ref) + } + remote.add(name, oid) + } + var err error + if kind, line, err = pkts.next(); err != nil { + return remoteRefs{}, fmt.Errorf("reading ref advertisement: %w", err) + } + } + return remote, nil +} + +// add keeps branches and tags, leaving out peeled tag entries. +func (r remoteRefs) add(name, oid string) { + if (strings.HasPrefix(name, headsPrefix) || strings.HasPrefix(name, tagsPrefix)) && !strings.HasSuffix(name, "^{}") { + r.refs[name] = oid + } +} + +func symrefTarget(caps, ref string) string { + for _, capability := range strings.Fields(caps) { + if value, ok := strings.CutPrefix(capability, "symref="+ref+":"); ok { + return value + } + } + return "" +} + +// upstreamRequest sends a smart HTTP request through the upstream client and +// classifies refusals. A non-empty body is sent as an upload-pack request. +func (c *Cache) upstreamRequest(ctx context.Context, method, target, body string) (*http.Response, error) { + var reader io.Reader + if body != "" { + reader = strings.NewReader(body) + } + req, err := http.NewRequestWithContext(ctx, method, target, reader) + if err != nil { + return nil, err + } + req.Header.Set("Git-Protocol", "version=2") + req.Header.Set("User-Agent", gitUserAgent) + if body != "" { + req.Header.Set("Content-Type", requestType) + req.Header.Set("Accept", resultType) + } + resp, err := c.client.Do(req) + if err != nil { + return nil, fmt.Errorf("upstream request: %w", err) + } + if err := upstreamStatusError(resp.StatusCode); err != nil { + _ = resp.Body.Close() + return nil, err + } + return resp, nil +} + +func upstreamStatusError(status int) error { + switch { + case status == http.StatusOK: + return nil + case status == http.StatusNotFound || status == http.StatusGone: + return fmt.Errorf("%w: status %d", ErrNotFound, status) + case status == http.StatusUnauthorized || status == http.StatusForbidden: + return fmt.Errorf("%w: status %d", ErrRefused, status) + case status >= http.StatusMultipleChoices && status < http.StatusBadRequest: + return fmt.Errorf("%w: redirect (status %d) not followed", ErrRefused, status) + default: + return fmt.Errorf("upstream returned status %d", status) + } +} diff --git a/internal/gitcache/wants.go b/internal/gitcache/wants.go new file mode 100644 index 0000000..8755ba1 --- /dev/null +++ b/internal/gitcache/wants.go @@ -0,0 +1,274 @@ +package gitcache + +import ( + "bytes" + "context" + "errors" + "fmt" + "io" + "maps" + "slices" + "strconv" + "strings" + "time" +) + +const ( + // wantedPrefix holds commits fetched because a client asked for them by + // object ID, such as a pull request head that is on no branch, as + // {wantedPrefix}{unix time}/{object ID}. The refs keep them from being + // garbage collected, and are hidden from clients. + wantedPrefix = "refs/proxy/wanted/" + // wantedMaxAge is how long a commit fetched by ID is kept while no + // cached branch or tag includes it. + wantedMaxAge = 7 * 24 * time.Hour + // wantRetryAfter is how long a want the upstream could not provide is + // not asked for again. Short, since a commit can reach a CI job before + // it reaches every upstream replica. A want too large for what + // max_repo_size leaves waits tooLargeRetryAfter instead. + wantRetryAfter = time.Minute + // maxFailedWants bounds the record of failed wants. + maxFailedWants = 4096 + // maxWantScan bounds how much of a request body is read for its wants. + maxWantScan = 1 << 20 + // maxWantFetch bounds the missing objects one request may have fetched. + maxWantFetch = 32 + // maxWantSplit bounds the wants of a failed fetch that are fetched again + // one at a time; a larger batch is refused as a whole. + maxWantSplit = 4 +) + +// readWants reads the object IDs a fetch request wants, from its first +// section, and returns them with a reader that replays the whole body. In +// protocol v0 that section holds the wants; in v2 it is the whole request. +func readWants(body io.Reader) ([]string, io.Reader) { + var consumed bytes.Buffer + pkts := newPktReader(io.TeeReader(io.LimitReader(body, maxWantScan), &consumed)) + var wants []string + for first := true; ; first = false { + kind, line, err := pkts.next() + if err != nil || kind == pktFlushKind { + break + } + if kind != pktData { + continue + } + if command, ok := strings.CutPrefix(line, "command="); ok && first && command != "fetch" { + break + } + if rest, ok := strings.CutPrefix(line, "want "); ok { + if oid, _, _ := strings.Cut(rest, " "); isObjectID(oid) { + wants = append(wants, oid) + } + } + } + return wants, io.MultiReader(&consumed, body) +} + +// fetchMissingWants fetches the wanted objects the repository lacks. Wants +// for branch and tag tips are already there after the refresh; this covers +// commits a client names directly, as actions/checkout does. +func (c *Cache) fetchMissingWants(ctx context.Context, rp *repo, repoURL string, wants []string) error { + missing, err := c.missingObjects(ctx, rp.dir, wants) + if err != nil { + return err + } + missing = c.withoutFailedWants(rp.key, missing) + if len(missing) == 0 || len(missing) > maxWantFetch { + return nil + } + unlock, err := rp.lockWrites(ctx) + if err != nil { + return err + } + defer unlock() + // Another request may have fetched them while this one waited. + if missing, err = c.missingObjects(ctx, rp.dir, missing); err != nil || len(missing) == 0 { + return err + } + defer c.evict() + + err = c.fetchWants(ctx, rp, repoURL, missing) + if err == nil || ctx.Err() != nil { + return err + } + if len(missing) == 1 || len(missing) > maxWantSplit || + errors.Is(err, ErrTooLarge) || errors.Is(err, ErrCacheFull) || errors.Is(err, errUpstreamUnanswered) { + // Fetched one at a time, wants too large for what max_repo_size + // or max_size leaves would exhaust the same budget, and an upstream + // that did not answer would be waited on once per want. + c.recordFailedWants(rp.key, missing, err) + return err + } + // Find which wants failed, so a good one asked for with a bad one is + // not refused too. These fetches hold the repository's write lock, so + // only a small batch is split. + var errs []error + for _, oid := range missing { + if err := c.fetchWants(ctx, rp, repoURL, []string{oid}); err != nil { + if ctx.Err() != nil { + return err + } + c.recordFailedWants(rp.key, []string{oid}, err) + errs = append(errs, err) + } + } + return errors.Join(errs...) +} + +// fetchWants fetches oids from the upstream under wanted refs, within what +// max_repo_size leaves. A want that does not fit is refused, not the +// repository: transfer.unpackLimit makes a cut-off transfer leave nothing +// behind. +func (c *Cache) fetchWants(ctx context.Context, rp *repo, repoURL string, oids []string) error { + limit, err := c.fetchLimit(rp) + if err != nil { + return err + } + now := time.Now() + refspecs := make([]string, len(oids)) + for i, oid := range oids { + refspecs[i] = oid + ":" + wantedRef(oid, now) + } + res := c.newReservation() + err = c.fetch(ctx, rp.dir, repoURL, limit, res, []string{"--atomic"}, refspecs...) + res.settle(rp, dirSize(rp.dir)) + return err +} + +func wantedRef(oid string, at time.Time) string { + return wantedPrefix + strconv.FormatInt(at.Unix(), 10) + "/" + oid +} + +// pruneWanted deletes wanted refs that are no longer needed: those older +// than wantedMaxAge, and, after a fetch has moved branches or tags, those +// whose commit a cached branch or tag now includes. +func (c *Cache) pruneWanted(ctx context.Context, dir string, wanted []string, fetched bool) error { + if len(wanted) == 0 { + return nil + } + cutoff := time.Now().Add(-wantedMaxAge).Unix() + var drop []string + keep := make(map[string]string, len(wanted)) + for _, ref := range wanted { + created, oid, ok := strings.Cut(strings.TrimPrefix(ref, wantedPrefix), "/") + unix, err := strconv.ParseInt(created, 10, 64) + if !ok || err != nil || unix < cutoff || !isObjectID(oid) { + drop = append(drop, ref) + continue + } + keep[oid] = ref + } + var mergedErr error + if fetched && len(keep) > 0 { + unmerged, err := c.unmergedCommits(ctx, dir, slices.Sorted(maps.Keys(keep))) + if err != nil { + mergedErr = fmt.Errorf("listing unmerged wanted commits: %w", err) + } else { + for oid, ref := range keep { + if !unmerged[oid] { + drop = append(drop, ref) + } + } + } + } + if len(drop) == 0 { + return mergedErr + } + var stdin strings.Builder + for _, ref := range drop { + stdin.WriteString("delete " + ref + "\n") + } + cmd := c.command(ctx, nil, "-C", dir, "update-ref", "--stdin") + cmd.Stdin = strings.NewReader(stdin.String()) + if out, err := cmd.CombinedOutput(); err != nil { + return fmt.Errorf("deleting wanted refs: %w: %s", err, strings.TrimSpace(string(out))) + } + return mergedErr +} + +// unmergedCommits returns which of commits no cached branch or tag +// includes. +func (c *Cache) unmergedCommits(ctx context.Context, dir string, commits []string) (map[string]bool, error) { + // rev-list prints what the commits, read from stdin, reach and no + // branch or tag does, so a commit it leaves out is merged. + cmd := c.command(ctx, nil, "-C", dir, "rev-list", "--stdin", "--not", "--branches", "--tags") + cmd.Stdin = strings.NewReader(strings.Join(commits, "\n") + "\n") + out, err := cmd.Output() + if err != nil { + return nil, err + } + unmerged := make(map[string]bool) + for line := range strings.Lines(string(out)) { + unmerged[strings.TrimSpace(line)] = true + } + return unmerged, nil +} + +// withoutFailedWants drops the object IDs a recent fetch for the +// repository could not get. +func (c *Cache) withoutFailedWants(key string, oids []string) []string { + c.mu.Lock() + defer c.mu.Unlock() + now := time.Now() + return slices.DeleteFunc(oids, func(oid string) bool { + until, ok := c.failedWants[key+" "+oid] + return ok && now.Before(until) + }) +} + +// recordFailedWants keeps oids from being fetched again for the repository +// for wantRetryAfter, or for tooLargeRetryAfter when they did not fit in +// max_repo_size. +func (c *Cache) recordFailedWants(key string, oids []string, err error) { + now := time.Now() + until := now.Add(wantRetryAfter) + if errors.Is(err, ErrTooLarge) { + until = now.Add(tooLargeRetryAfter) + } + c.mu.Lock() + defer c.mu.Unlock() + for k, expiry := range c.failedWants { + if !now.Before(expiry) { + delete(c.failedWants, k) + } + } + for _, oid := range oids { + if len(c.failedWants) >= maxFailedWants { + return + } + c.failedWants[key+" "+oid] = until + } +} + +// missingObjects returns the object IDs in oids the repository does not have. +func (c *Cache) missingObjects(ctx context.Context, dir string, oids []string) ([]string, error) { + if len(oids) == 0 { + return nil, nil + } + cmd := c.command(ctx, nil, "-C", dir, "cat-file", "--batch-check") + cmd.Stdin = strings.NewReader(strings.Join(oids, "\n") + "\n") + out, err := cmd.Output() + if err != nil { + return nil, err + } + var missing []string + for line := range strings.Lines(string(out)) { + if oid, ok := strings.CutSuffix(strings.TrimSuffix(line, "\n"), " missing"); ok { + missing = append(missing, oid) + } + } + return missing, nil +} + +func isObjectID(s string) bool { + if len(s) != 40 && len(s) != 64 { //nolint:mnd // SHA-1 and SHA-256 hex lengths + return false + } + for _, r := range s { + if (r < '0' || r > '9') && (r < 'a' || r > 'f') { + return false + } + } + return true +} diff --git a/internal/gitcache/wants_test.go b/internal/gitcache/wants_test.go new file mode 100644 index 0000000..f01df06 --- /dev/null +++ b/internal/gitcache/wants_test.go @@ -0,0 +1,319 @@ +package gitcache + +import ( + "crypto/rand" + "encoding/hex" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strconv" + "strings" + "testing" + "time" +) + +// pushPullRequest commits on a new branch from main, with data in a file if +// given, and pushes it only as refs/pull/{n}/head, so the commit is on no +// branch or tag upstream. +func (u *fakeUpstream) pushPullRequest(work string, n int, data []byte) string { + u.t.Helper() + branch := "pr" + strconv.Itoa(n) + runGit(u.t, work, "checkout", "--quiet", "-b", branch, "main") + if data != nil { + if err := os.WriteFile(filepath.Join(work, branch+".bin"), data, 0o600); err != nil { + u.t.Fatal(err) + } + runGit(u.t, work, "add", branch+".bin") + } + runGit(u.t, work, "commit", "--quiet", "--allow-empty", "-m", branch) + runGit(u.t, work, "push", "--quiet", "origin", "HEAD:refs/pull/"+strconv.Itoa(n)+"/head") + runGit(u.t, work, "checkout", "--quiet", "main") + return runGit(u.t, work, "rev-parse", branch) +} + +// fetchByID fetches one commit by ID from url, as actions/checkout does. +func fetchByID(t *testing.T, url, sha string) error { + t.Helper() + dir := t.TempDir() + runGit(t, dir, "init", "--quiet") + _, err := tryGit(t, dir, "fetch", "--quiet", "--depth=1", url, sha) + return err +} + +func randomBytes(n int) []byte { + b := make([]byte, n) + _, _ = rand.Read(b) + return b +} + +func (tc *testCache) wantedRefs(t *testing.T) []string { + t.Helper() + var refs []string + for line := range strings.Lines(tc.cachedRefs(t)) { + if _, name, _ := strings.Cut(strings.TrimSpace(line), " "); strings.HasPrefix(name, wantedPrefix) { + refs = append(refs, name) + } + } + return refs +} + +func TestMergedWantedCommitIsUnpinned(t *testing.T) { + upstream := newFakeUpstream(t) + work := upstream.newRepo("repo") + runGit(t, upstream.bare(), "config", "uploadpack.allowAnySHA1InWant", "true") + sha := upstream.pushPullRequest(work, 1, nil) + tc := newTestCache(t, upstream.server.URL, nil) + tc.clone(t, "repo") + if err := fetchByID(t, tc.url("repo"), sha); err != nil { + t.Fatalf("fetch by ID: %v", err) + } + if refs := tc.wantedRefs(t); len(refs) != 1 { + t.Fatalf("wanted refs %v, want one", refs) + } + + runGit(t, work, "push", "--quiet", "origin", "pr1:main") + tc.clone(t, "repo") + if refs := tc.wantedRefs(t); len(refs) != 0 { + t.Errorf("wanted refs %v after the commit was merged, want none", refs) + } +} + +func TestOldWantedCommitIsUnpinned(t *testing.T) { + upstream := newFakeUpstream(t) + work := upstream.newRepo("repo") + runGit(t, upstream.bare(), "config", "uploadpack.allowAnySHA1InWant", "true") + old := upstream.pushPullRequest(work, 1, nil) + recent := upstream.pushPullRequest(work, 2, nil) + tc := newTestCache(t, upstream.server.URL, nil) + tc.clone(t, "repo") + for _, sha := range []string{old, recent} { + if err := fetchByID(t, tc.url("repo"), sha); err != nil { + t.Fatalf("fetch by ID: %v", err) + } + } + + cached := filepath.Join(tc.dir, "up", "repo.git") + for _, ref := range tc.wantedRefs(t) { + if strings.HasSuffix(ref, "/"+old) { + runGit(t, cached, "update-ref", "-d", ref) + } + } + runGit(t, cached, "update-ref", wantedRef(old, time.Now().Add(-wantedMaxAge-time.Hour)), old) + + tc.clone(t, "repo") + refs := tc.wantedRefs(t) + if len(refs) != 1 || !strings.HasSuffix(refs[0], "/"+recent) { + t.Errorf("wanted refs %v, want only the recent commit's", refs) + } +} + +// TestRepositoryTooLargeToRefreshIsClonedAgain fills a repository with a +// commit fetched by ID, then grows its branch upstream past what is left of +// max_repo_size. Rather than stop following the upstream, the repository is +// dropped once idle and cloned again with only its branches and tags, which +// fit. +func TestRepositoryTooLargeToRefreshIsClonedAgain(t *testing.T) { + upstream := newFakeUpstream(t) + work := upstream.newRepo("repo") + runGit(t, upstream.bare(), "config", "uploadpack.allowAnySHA1InWant", "true") + pinned := upstream.pushPullRequest(work, 1, randomBytes(100<<10)) + base := repoSize(t, upstream, "repo") + tc := newTestCache(t, upstream.server.URL, func(o *Options) { o.MaxRepoSize = base + 150<<10 }) + tc.clone(t, "repo") + if err := fetchByID(t, tc.url("repo"), pinned); err != nil { + t.Fatalf("fetch by ID: %v", err) + } + + if err := os.WriteFile(filepath.Join(work, "grown.bin"), randomBytes(80<<10), 0o600); err != nil { + t.Fatal(err) + } + runGit(t, work, "add", "grown.bin") + head := upstream.commit(work, "grown") + runGit(t, work, "push", "--quiet", "origin", "main") + + // This clone's refresh does not fit. It is served the cached copy, or, + // if the repository is dropped between its requests, the new clone. + tc.clone(t, "repo") + if got := runGit(t, tc.clone(t, "repo"), "rev-parse", "HEAD"); got != head { + t.Errorf("HEAD = %s, want %s once cloned again", got, head) + } + waitIdle(t, tc.Cache) + if _, err := tryGit(t, filepath.Join(tc.dir, "up", "repo.git"), "cat-file", "-e", pinned); err == nil { + t.Error("the repository still holds the commit fetched by ID, so it was not cloned again") + } +} + +// TestTooLargeWantKeepsRepository asks for a commit by ID that does not fit +// in what max_repo_size leaves. The commit is refused, for a while, and the +// repository is kept, with nothing of the cut-off transfer left in it. +func TestTooLargeWantKeepsRepository(t *testing.T) { + upstream := newFakeUpstream(t) + work := upstream.newRepo("repo") + runGit(t, upstream.bare(), "config", "uploadpack.allowAnySHA1InWant", "true") + large := upstream.pushPullRequest(work, 1, randomBytes(200<<10)) + small := upstream.pushPullRequest(work, 2, nil) + base := repoSize(t, upstream, "repo") + tc := newTestCache(t, upstream.server.URL, func(o *Options) { o.MaxRepoSize = base + 100<<10 }) + tc.clone(t, "repo") + + if err := fetchByID(t, tc.url("repo"), large); err == nil { + t.Fatal("fetched a commit larger than max_repo_size leaves") + } + waitIdle(t, tc.Cache) + cached := filepath.Join(tc.dir, "up", "repo.git") + if !fileExists(cached) { + t.Fatal("the repository was dropped") + } + if _, err := tryGit(t, cached, "cat-file", "-e", large); err == nil { + t.Error("the cut-off transfer left the commit behind") + } + if leftovers, _ := filepath.Glob(filepath.Join(cached, "objects", "pack", "tmp_*")); len(leftovers) != 0 { + t.Errorf("the cut-off transfer left %v", leftovers) + } + tc.mu.Lock() + until := tc.failedWants["up/repo.git "+large] + tc.mu.Unlock() + if time.Until(until) <= wantRetryAfter { + t.Errorf("the large commit is refused until %s, want for tooLargeRetryAfter", until) + } + + before := upstream.gitRequests.Load() + if err := fetchByID(t, tc.url("repo"), large); err == nil { + t.Fatal("fetched the large commit on a second try") + } + if got := upstream.gitRequests.Load() - before; got != 0 { + t.Errorf("the second try made %d upstream fetch requests, want none", got) + } + if err := fetchByID(t, tc.url("repo"), small); err != nil { + t.Errorf("fetch of another commit by ID: %v", err) + } +} + +// TestWantsFetchedTogetherFailSeparately asks for a good and a bad commit +// in one request. The good one is still fetched, and only the bad one is +// refused for a while. +func TestWantsFetchedTogetherFailSeparately(t *testing.T) { + upstream := newFakeUpstream(t) + work := upstream.newRepo("repo") + runGit(t, upstream.bare(), "config", "uploadpack.allowAnySHA1InWant", "true") + good := upstream.pushPullRequest(work, 1, nil) + bad := hex.EncodeToString(randomBytes(20)) + tc := newTestCache(t, upstream.server.URL, nil) + tc.clone(t, "repo") + + dir := t.TempDir() + runGit(t, dir, "init", "--quiet") + if _, err := tryGit(t, dir, "fetch", "--quiet", tc.url("repo"), good, bad); err == nil { + t.Fatal("fetched a commit the upstream does not have") + } + waitIdle(t, tc.Cache) + if _, err := tryGit(t, filepath.Join(tc.dir, "up", "repo.git"), "cat-file", "-e", good); err != nil { + t.Error("the good commit was not fetched") + } + tc.mu.Lock() + _, goodRefused := tc.failedWants["up/repo.git "+good] + _, badRefused := tc.failedWants["up/repo.git "+bad] + tc.mu.Unlock() + if goodRefused || !badRefused { + t.Errorf("refused good=%v bad=%v, want only the bad commit", goodRefused, badRefused) + } +} + +func TestFailedWantIsNotRetriedAtOnce(t *testing.T) { + upstream := newFakeUpstream(t) + upstream.newRepo("repo") + tc := newTestCache(t, upstream.server.URL, nil) + tc.clone(t, "repo") + missing := hex.EncodeToString(randomBytes(20)) + + before := upstream.gitRequests.Load() + if err := fetchByID(t, tc.url("repo"), missing); err == nil { + t.Fatal("fetched a commit the upstream does not have") + } + if upstream.gitRequests.Load() == before { + t.Fatal("the first request did not ask the upstream") + } + before = upstream.gitRequests.Load() + if err := fetchByID(t, tc.url("repo"), missing); err == nil { + t.Fatal("fetched a commit the upstream does not have") + } + if got := upstream.gitRequests.Load() - before; got != 0 { + t.Errorf("the second request made %d upstream fetch requests, want none", got) + } +} + +func TestWantsAreNotFetchedWhenTurnedOff(t *testing.T) { + upstream := newFakeUpstream(t) + work := upstream.newRepo("repo") + runGit(t, upstream.bare(), "config", "uploadpack.allowAnySHA1InWant", "true") + sha := upstream.pushPullRequest(work, 1, nil) + tc := newTestCache(t, upstream.server.URL, nil) + server := httptest.NewServer(testFront(tc.Cache, upstream.server.URL, false)) + defer server.Close() + url := server.URL + "/git/up/repo" + runGit(t, "", "clone", "--quiet", url, filepath.Join(t.TempDir(), "clone")) + + sessions := upstream.gitSessions.Load() + if err := fetchByID(t, url, sha); err == nil { + t.Error("fetched a commit by ID with FetchWants off") + } + if got := upstream.gitSessions.Load() - sessions; got != 0 { + t.Errorf("upstream saw %d fetches, want none", got) + } +} + +// TestWantsDuringAnOutageAreNotFetchedOneByOne asks for two commits while +// the upstream is down. One failed fetch records both, rather than a fetch +// per commit, each waiting on the upstream. +func TestWantsDuringAnOutageAreNotFetchedOneByOne(t *testing.T) { + upstream := newFakeUpstream(t) + work := upstream.newRepo("repo") + runGit(t, upstream.bare(), "config", "uploadpack.allowAnySHA1InWant", "true") + first := upstream.pushPullRequest(work, 1, nil) + second := upstream.pushPullRequest(work, 2, nil) + tc := newTestCache(t, upstream.server.URL, nil) + tc.clone(t, "repo") + + upstream.status.Store(http.StatusServiceUnavailable) + sessions := upstream.gitSessions.Load() + dir := t.TempDir() + runGit(t, dir, "init", "--quiet") + if _, err := tryGit(t, dir, "fetch", "--quiet", tc.url("repo"), first, second); err == nil { + t.Fatal("fetched commits while the upstream was down") + } + if got := upstream.gitSessions.Load() - sessions; got != 1 { + t.Errorf("upstream saw %d fetches, want 1", got) + } + tc.mu.Lock() + _, firstRefused := tc.failedWants["up/repo.git "+first] + _, secondRefused := tc.failedWants["up/repo.git "+second] + tc.mu.Unlock() + if !firstRefused || !secondRefused { + t.Errorf("refused first=%v second=%v, want both", firstRefused, secondRefused) + } +} + +// TestLargeBatchOfFailedWantsIsNotSplit asks for more unknown commits at +// once than are fetched again one by one, which would hold the repository's +// write lock for a fetch per commit. +func TestLargeBatchOfFailedWantsIsNotSplit(t *testing.T) { + upstream := newFakeUpstream(t) + upstream.newRepo("repo") + tc := newTestCache(t, upstream.server.URL, nil) + tc.clone(t, "repo") + + args := []string{"fetch", "--quiet", tc.url("repo")} + for range maxWantSplit + 1 { + args = append(args, hex.EncodeToString(randomBytes(20))) + } + dir := t.TempDir() + runGit(t, dir, "init", "--quiet") + sessions := upstream.gitSessions.Load() + if _, err := tryGit(t, dir, args...); err == nil { + t.Fatal("fetched commits the upstream does not have") + } + if got := upstream.gitSessions.Load() - sessions; got != 1 { + t.Errorf("upstream saw %d fetches, want 1", got) + } +} diff --git a/internal/handler/apk.go b/internal/handler/apk.go index 6e18e74..045dbac 100644 --- a/internal/handler/apk.go +++ b/internal/handler/apk.go @@ -6,6 +6,7 @@ import ( "net/http" "regexp" "strings" + "time" "github.com/git-pkgs/proxy/internal/retention" "github.com/git-pkgs/purl" @@ -51,30 +52,45 @@ type APKHandler struct { proxy *Proxy proxyURL string repositories map[string]string + // snapshots: see WithSnapshots. + snapshots time.Duration } // NewAPKHandler creates an Alpine APK repository protocol handler. // When repositories is empty, a single repository named "alpine" pointing at // the official Alpine mirror is used. func NewAPKHandler(proxy *Proxy, proxyURL string, repositories map[string]string) *APKHandler { - h := &APKHandler{ + return &APKHandler{ proxy: proxy, proxyURL: strings.TrimSuffix(proxyURL, "/"), - repositories: make(map[string]string, len(repositories)), + repositories: APKRepositories(repositories), } - for name, repositoryURL := range repositories { - h.repositories[name] = strings.TrimSuffix(repositoryURL, "/") +} + +// APKRepositories returns the upstream.apk repositories by name without +// trailing slashes, or the official Alpine mirror as "alpine" when none are +// configured. +func APKRepositories(configured map[string]string) map[string]string { + repositories := make(map[string]string, len(configured)) + for name, repositoryURL := range configured { + repositories[name] = strings.TrimSuffix(repositoryURL, "/") } - if len(h.repositories) == 0 { - h.repositories[defaultAPKRepositoryName] = defaultAPKUpstream + if len(repositories) == 0 { + repositories[defaultAPKRepositoryName] = defaultAPKUpstream } - return h + return repositories +} + +// APKCacheFilename returns the filename a package at path +// ({release}/{repo}/{arch}/{file}) of repository is cached under. +func APKCacheFilename(repository, path string) string { + return repository + "/" + path } // Routes returns the HTTP handler for APK requests. // Mount this at /apk on your router. func (h *APKHandler) Routes() http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + return rejectQueryChars(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.Method != http.MethodGet && r.Method != http.MethodHead { http.Error(w, "method not allowed", http.StatusMethodNotAllowed) return @@ -87,14 +103,18 @@ func (h *APKHandler) Routes() http.Handler { return } - repository, rest, ok := strings.Cut(path, "/") - upstreamURL, found := h.repositories[repository] + segment, rest, ok := strings.Cut(path, "/") + repository, upstreamURL, day, snapshot, found := h.resolveRepository(segment) if !ok || rest == "" || !found { http.NotFound(w, r) return } switch { + case snapshot && (isAPKIndex(rest) || isAPKSignature(rest)): + // A dated snapshot serves the kept version of the index; packages + // and other files below are the same as under the plain path. + h.serveSnapshot(w, r, repository, upstreamURL, rest, day) case isAPKIndex(rest) || isAPKSignature(rest): // Indexes and detached signatures are signed upstream metadata. // Cache them with the metadata TTL and serve the stored bytes @@ -107,7 +127,7 @@ func (h *APKHandler) Routes() http.Handler { // Other files - proxy directly. h.proxyFile(w, r, upstreamURL, rest) } - }) + })) } // isAPKIndex reports whether the path names a repository index: @@ -138,7 +158,7 @@ func (h *APKHandler) handlePackageDownload(w http.ResponseWriter, r *http.Reques } downloadURL := upstreamURL + "/" + path - cacheFilename := repository + "/" + path + cacheFilename := APKCacheFilename(repository, path) h.proxy.Logger.Info("apk package download", "repository", repository, "name", name, "version", version, "arch", arch) @@ -160,8 +180,12 @@ func (h *APKHandler) handlePackageDownload(w http.ResponseWriter, r *http.Reques // metadata cache. Stored bytes are re-served verbatim, which keeps embedded // and detached signatures valid. func (h *APKHandler) handleMetadata(w http.ResponseWriter, r *http.Request, repository, upstreamURL, path string) { - h.proxy.ProxyCached(w, r, upstreamURL+"/"+path, apkEcosystem, - h.metadataCacheKey(repository, upstreamURL, path), "*/*") + cacheKey := h.metadataCacheKey(repository, upstreamURL, path) + if h.snapshotsEnabled() { + h.serveMetadataWithSnapshot(w, r, upstreamURL+"/"+path, cacheKey) + return + } + h.proxy.ProxyCached(w, r, upstreamURL+"/"+path, apkEcosystem, cacheKey, "*/*") } // metadataCacheKey derives the metadata cache key from the repository name, diff --git a/internal/handler/apk_snapshots.go b/internal/handler/apk_snapshots.go new file mode 100644 index 0000000..401dc00 --- /dev/null +++ b/internal/handler/apk_snapshots.go @@ -0,0 +1,239 @@ +package handler + +import ( + "bytes" + "context" + "crypto/rand" + "crypto/sha256" + "database/sql" + "encoding/hex" + "io" + "net/http" + "strconv" + "strings" + "time" + + "github.com/git-pkgs/proxy/internal/database" +) + +// apkSnapshotDateLayout is the date format of a snapshot path segment. +const apkSnapshotDateLayout = "2006-01-02" + +// WithSnapshots keeps earlier versions of the indexes this handler serves and +// makes them available under /apk/{name}@{YYYY-MM-DD}/, as signed upstream +// bytes that apk verifies as usual. keep is how long a version is kept after +// it was replaced; 0 disables snapshots. +func (h *APKHandler) WithSnapshots(keep time.Duration) *APKHandler { + h.snapshots = keep + return h +} + +// snapshotsEnabled reports whether snapshots are recorded and served. They +// need the metadata cache, which stores the documents they are copied from. +func (h *APKHandler) snapshotsEnabled() bool { + return h.snapshots > 0 && h.proxy.CacheMetadata && h.proxy.DB != nil && h.proxy.Storage != nil +} + +// resolveRepository maps the first path segment to a configured repository. +// A segment of the form {name}@{YYYY-MM-DD} names a snapshot of repository +// name for that day, when snapshots are enabled and no repository is +// configured under the full segment. ok is false for anything else. +func (h *APKHandler) resolveRepository(segment string) (repository, upstreamURL string, day time.Time, snapshot, ok bool) { + if upstreamURL, found := h.repositories[segment]; found { + return segment, upstreamURL, time.Time{}, false, true + } + if !h.snapshotsEnabled() { + return "", "", time.Time{}, false, false + } + at := strings.LastIndexByte(segment, '@') + if at < 0 { + return "", "", time.Time{}, false, false + } + upstreamURL, found := h.repositories[segment[:at]] + if !found { + return "", "", time.Time{}, false, false + } + day, err := time.Parse(apkSnapshotDateLayout, segment[at+1:]) + if err != nil { + return "", "", time.Time{}, false, false + } + return segment[:at], upstreamURL, day, true, true +} + +// serveSnapshot answers a request for an index or signature under a snapshot +// path with the version that was current at the end of day. A day for which +// no version was stored, or one that has not begun yet, is 404. +func (h *APKHandler) serveSnapshot(w http.ResponseWriter, r *http.Request, repository, upstreamURL, path string, day time.Time) { + end := day.AddDate(0, 0, 1) + if day.After(time.Now()) { + http.NotFound(w, r) + return + } + snap, err := h.proxy.DB.MetadataSnapshotAt(apkEcosystem, h.metadataCacheKey(repository, upstreamURL, path), end) + if err != nil { + h.proxy.Logger.Error("apk snapshot lookup failed", "repository", repository, "path", path, "error", err) + http.Error(w, "internal error", http.StatusInternalServerError) + return + } + if snap == nil { + http.NotFound(w, r) + return + } + + if writeMetadataValidators(w, r, cachedMeta{etag: `"` + snap.ContentDigest + `"`, lastModified: snap.ValidFrom()}) { + return + } + body, err := h.proxy.Storage.Open(r.Context(), snap.StoragePath) + if err != nil { + h.proxy.Logger.Error("apk snapshot unreadable", "repository", repository, "path", path, + "storage_path", snap.StoragePath, "error", err) + http.Error(w, "snapshot unavailable", http.StatusInternalServerError) + return + } + defer func() { _ = body.Close() }() + + if snap.ContentType.String != "" { + w.Header().Set(headerContentType, snap.ContentType.String) + } + w.Header().Set(headerContentLength, strconv.FormatInt(snap.Size, 10)) + if snap.ContentEncoding.String != "" { + w.Header().Set(headerContentEncoding, snap.ContentEncoding.String) + } + w.WriteHeader(http.StatusOK) + if r.Method != http.MethodHead { + _, _ = io.Copy(w, body) + } +} + +// serveMetadataWithSnapshot is ProxyCached, recording each version it serves. +func (h *APKHandler) serveMetadataWithSnapshot(w http.ResponseWriter, r *http.Request, upstream, cacheKey string) { + ctx := context.WithoutCancel(r.Context()) + h.proxy.proxyCachedWithEncoding(w, r, upstream, apkEcosystem, cacheKey, "identity", &metadataHooks{ + hit: func(entry *database.MetadataCacheEntry, seen time.Time) { + h.recordStoredSnapshot(ctx, cacheKey, entry, seen) + }, + fetched: func(body []byte, contentType, contentEncoding string) { + h.recordServedSnapshot(ctx, cacheKey, body, contentType, contentEncoding, time.Now()) + }, + }, "*/*") +} + +// recordServedSnapshot keeps body, the document a request is serving, as the +// version current from observed, unless the version current then already has +// its bytes. +func (h *APKHandler) recordServedSnapshot(ctx context.Context, cacheKey string, body []byte, contentType, contentEncoding string, observed time.Time) { + sum := sha256.Sum256(body) + digest := "sha256:" + hex.EncodeToString(sum[:]) + if !h.snapshotNeeded(cacheKey, digest, observed) { + return + } + storagePath := apkSnapshotStoragePath(cacheKey, digest, observed) + if _, _, err := h.proxy.Storage.Store(ctx, storagePath, bytes.NewReader(body)); err != nil { + h.proxy.Logger.Warn("failed to store apk snapshot", "path", storagePath, "error", err) + h.discardSnapshotBlob(ctx, storagePath) + return + } + h.addSnapshot(ctx, &database.MetadataSnapshot{ + Ecosystem: apkEcosystem, + Name: cacheKey, + StoragePath: storagePath, + ContentType: sql.NullString{String: contentType, Valid: contentType != ""}, + ContentEncoding: sql.NullString{String: contentEncoding, Valid: contentEncoding != ""}, + ContentDigest: digest, + Size: int64(len(body)), + ValidFromMS: observed.UnixMilli(), + }) +} + +// recordStoredSnapshot keeps the cached document entry describes as the +// version current from observed, unless the version current then already +// has its digest. +func (h *APKHandler) recordStoredSnapshot(ctx context.Context, cacheKey string, entry *database.MetadataCacheEntry, observed time.Time) { + if !entry.ContentDigest.Valid || !h.snapshotNeeded(cacheKey, entry.ContentDigest.String, observed) { + return + } + h.storeSnapshot(ctx, cacheKey, entry, observed) +} + +// snapshotNeeded reports whether a version with digest seen at observed +// differs from the version current then. It is only a shortcut that saves +// copying the document: AddMetadataSnapshot makes the same check. +func (h *APKHandler) snapshotNeeded(cacheKey, digest string, observed time.Time) bool { + current, err := h.proxy.DB.MetadataSnapshotAt(apkEcosystem, cacheKey, observed.Add(time.Millisecond)) + return err == nil && (current == nil || current.ContentDigest != digest) +} + +// storeSnapshot records the cached document entry as the version current +// from validFrom. Concurrent requests can both get here for the same +// version; each copies to a path of its own, so the one whose row is not +// added only deletes its own copy. +func (h *APKHandler) storeSnapshot(ctx context.Context, cacheKey string, entry *database.MetadataCacheEntry, validFrom time.Time) { + digest := entry.ContentDigest.String + storagePath := apkSnapshotStoragePath(cacheKey, digest, validFrom) + size, ok := h.copySnapshotBlob(ctx, entry.StoragePath, storagePath, digest) + if !ok { + return + } + h.addSnapshot(ctx, &database.MetadataSnapshot{ + Ecosystem: apkEcosystem, + Name: cacheKey, + StoragePath: storagePath, + ContentType: entry.ContentType, + ContentEncoding: entry.ContentEncoding, + ContentDigest: digest, + Size: size, + ValidFromMS: validFrom.UnixMilli(), + }) +} + +// addSnapshot adds the row for a snapshot whose blob is stored, and deletes +// the blob when the row isn't added, as when another request recorded the +// same version first. +func (h *APKHandler) addSnapshot(ctx context.Context, snap *database.MetadataSnapshot) { + added, err := h.proxy.DB.AddMetadataSnapshot(snap) + if err != nil { + h.proxy.Logger.Warn("failed to record apk snapshot", "key", snap.Name, "error", err) + } + if err != nil || !added { + h.discardSnapshotBlob(ctx, snap.StoragePath) + } +} + +// copySnapshotBlob copies the cached document at from to to and reports its +// size, provided the copied bytes still have digest. A concurrent fetch can +// replace the cached document after its row was read; that version is +// recorded by the request that stored it. +func (h *APKHandler) copySnapshotBlob(ctx context.Context, from, to, digest string) (int64, bool) { + src, err := h.proxy.Storage.Open(ctx, from) + if err != nil { + return 0, false + } + defer func() { _ = src.Close() }() + size, hash, err := h.proxy.Storage.Store(ctx, to, src) + if err != nil { + h.proxy.Logger.Warn("failed to store apk snapshot", "path", to, "error", err) + return 0, false + } + if "sha256:"+hash != digest { + h.discardSnapshotBlob(ctx, to) + return 0, false + } + return size, true +} + +func (h *APKHandler) discardSnapshotBlob(ctx context.Context, path string) { + if err := h.proxy.Storage.Delete(ctx, path); err != nil { + h.proxy.Logger.Warn("failed to discard apk snapshot blob", "path", path, "error", err) + } +} + +// apkSnapshotStoragePath returns a new path to store one kept version of the +// document cached under cacheKey at. The time it became current keeps a +// version that returns after an upgrade was rolled back apart from its +// earlier copy, and a random suffix keeps two requests recording the same +// version in the same millisecond apart. +func apkSnapshotStoragePath(cacheKey, digest string, validFrom time.Time) string { + return "_snapshots/" + apkEcosystem + "/" + cacheKey + "/" + + strconv.FormatInt(validFrom.UnixMilli(), 10) + "-" + strings.TrimPrefix(digest, "sha256:") + + "-" + rand.Text() +} diff --git a/internal/handler/apk_snapshots_test.go b/internal/handler/apk_snapshots_test.go new file mode 100644 index 0000000..83bb26d --- /dev/null +++ b/internal/handler/apk_snapshots_test.go @@ -0,0 +1,382 @@ +package handler + +import ( + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/git-pkgs/proxy/internal/database" + "github.com/git-pkgs/registries/fetch" +) + +const apkSnapshotIndexPath = "/v3.22/main/x86_64/APKINDEX.tar.gz" + +// apkSnapshotUpstream serves the index held in index, initially "index v1", +// and counts package downloads. +type apkSnapshotUpstream struct { + index atomic.Value + downloads atomic.Int32 + server *httptest.Server +} + +func newAPKSnapshotUpstream(t *testing.T) *apkSnapshotUpstream { + t.Helper() + u := &apkSnapshotUpstream{} + u.index.Store("index v1") + u.server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case apkSnapshotIndexPath: + _, _ = w.Write([]byte(u.index.Load().(string))) + case "/v3.22/main/x86_64/curl-8.5.0-r0.apk": + u.downloads.Add(1) + _, _ = w.Write([]byte("curl 8.5.0")) + default: + http.NotFound(w, r) + } + })) + t.Cleanup(u.server.Close) + return u +} + +// newSnapshotAPKHandler returns an APK handler with snapshots enabled whose +// metadata TTL is 0, so every index request asks upstream. +func newSnapshotAPKHandler(t *testing.T, upstreamURL string) (*APKHandler, *database.DB) { + t.Helper() + proxy, db, _, _ := setupTestProxy(t) + proxy.CacheMetadata = true + proxy.MetadataTTL = 0 + proxy.HTTPClient = http.DefaultClient + fetcher := fetch.NewFetcher(fetch.WithHTTPClient(http.DefaultClient), fetch.WithMaxRetries(0)) + proxy.Fetcher = fetcher + t.Cleanup(func() { _ = fetcher.Close() }) + h := NewAPKHandler(proxy, "http://proxy.example", map[string]string{"alpine": upstreamURL}). + WithSnapshots(30 * 24 * time.Hour) + return h, db +} + +func snapshotCount(t *testing.T, db *database.DB) int { + t.Helper() + var n int + if err := db.Get(&n, `SELECT COUNT(*) FROM metadata_snapshots`); err != nil { + t.Fatal(err) + } + return n +} + +func expectAPKResponse(t *testing.T, h *APKHandler, target string, status int, body string) { + t.Helper() + w := serveAPKRequest(h, target) + if w.Code != status { + t.Fatalf("%s: status = %d, want %d: %s", target, w.Code, status, w.Body.String()) + } + if status == http.StatusOK && w.Body.String() != body { + t.Errorf("%s: body = %q, want %q", target, w.Body.String(), body) + } +} + +// TestAPKSnapshots_ServeIndexCurrentAtDate records two versions of an index +// through the plain path and checks that each dated path serves the version +// that was current at the end of that day. +func TestAPKSnapshots_ServeIndexCurrentAtDate(t *testing.T) { + upstream := newAPKSnapshotUpstream(t) + h, db := newSnapshotAPKHandler(t, upstream.server.URL) + + expectAPKResponse(t, h, "/alpine"+apkSnapshotIndexPath, http.StatusOK, "index v1") + // Pretend v1 was first stored on 2026-01-10. + recorded := time.Date(2026, 1, 10, 12, 0, 0, 0, time.UTC) + if _, err := db.Exec(`UPDATE metadata_snapshots SET valid_from_ms = ?`, recorded.UnixMilli()); err != nil { + t.Fatal(err) + } + + upstream.index.Store("index v2") + expectAPKResponse(t, h, "/alpine"+apkSnapshotIndexPath, http.StatusOK, "index v2") + // An unchanged index adds no snapshot. + expectAPKResponse(t, h, "/alpine"+apkSnapshotIndexPath, http.StatusOK, "index v2") + if got := snapshotCount(t, db); got != 2 { + t.Fatalf("snapshots = %d, want 2", got) + } + + today := time.Now().UTC().Format(apkSnapshotDateLayout) + future := time.Now().UTC().AddDate(0, 0, 2).Format(apkSnapshotDateLayout) + expectAPKResponse(t, h, "/alpine@2026-01-09"+apkSnapshotIndexPath, http.StatusNotFound, "") + expectAPKResponse(t, h, "/alpine@2026-01-10"+apkSnapshotIndexPath, http.StatusOK, "index v1") + expectAPKResponse(t, h, "/alpine@"+today+apkSnapshotIndexPath, http.StatusOK, "index v2") + expectAPKResponse(t, h, "/alpine@"+future+apkSnapshotIndexPath, http.StatusNotFound, "") + expectAPKResponse(t, h, "/alpine@2026-13-01"+apkSnapshotIndexPath, http.StatusNotFound, "") + expectAPKResponse(t, h, "/other@2026-01-10"+apkSnapshotIndexPath, http.StatusNotFound, "") + expectAPKResponse(t, h, "/alpine@2026-01-10/v3.22/community/x86_64/APKINDEX.tar.gz", http.StatusNotFound, "") +} + +func TestAPKSnapshots_ConditionalRequest(t *testing.T) { + upstream := newAPKSnapshotUpstream(t) + h, _ := newSnapshotAPKHandler(t, upstream.server.URL) + expectAPKResponse(t, h, "/alpine"+apkSnapshotIndexPath, http.StatusOK, "index v1") + + target := "/alpine@" + time.Now().UTC().Format(apkSnapshotDateLayout) + apkSnapshotIndexPath + first := serveAPKRequest(h, target) + etag := first.Header().Get("ETag") + if first.Code != http.StatusOK || etag == "" { + t.Fatalf("status = %d, ETag = %q, want 200 with an ETag", first.Code, etag) + } + req := httptest.NewRequest(http.MethodGet, target, nil) + req.Header.Set("If-None-Match", etag) + w := httptest.NewRecorder() + h.Routes().ServeHTTP(w, req) + if w.Code != http.StatusNotModified { + t.Errorf("conditional request: status = %d, want 304", w.Code) + } +} + +// TestAPKSnapshots_PackagesShareTheCache checks that a package requested +// under a snapshot path is the cached artifact of the plain path. +func TestAPKSnapshots_PackagesShareTheCache(t *testing.T) { + upstream := newAPKSnapshotUpstream(t) + h, _ := newSnapshotAPKHandler(t, upstream.server.URL) + + pkg := "/v3.22/main/x86_64/curl-8.5.0-r0.apk" + expectAPKResponse(t, h, "/alpine"+pkg, http.StatusOK, "curl 8.5.0") + expectAPKResponse(t, h, "/alpine@2026-01-10"+pkg, http.StatusOK, "curl 8.5.0") + if got := upstream.downloads.Load(); got != 1 { + t.Errorf("upstream downloads = %d, want 1", got) + } + expectAPKResponse(t, h, "/alpine@2026-01-10/v3.22/main/x86_64/gone-1.0-r0.apk", http.StatusNotFound, "") +} + +func TestAPKSnapshots_DisabledByDefault(t *testing.T) { + upstream := newAPKSnapshotUpstream(t) + h, db := newSnapshotAPKHandler(t, upstream.server.URL) + h.WithSnapshots(0) + + expectAPKResponse(t, h, "/alpine"+apkSnapshotIndexPath, http.StatusOK, "index v1") + if got := snapshotCount(t, db); got != 0 { + t.Errorf("snapshots = %d, want 0", got) + } + today := time.Now().UTC().Format(apkSnapshotDateLayout) + expectAPKResponse(t, h, "/alpine@"+today+apkSnapshotIndexPath, http.StatusNotFound, "") +} + +// TestAPKSnapshots_ConfiguredNameWins checks that a repository whose +// configured name contains '@' is served as configured, not as a snapshot. +func TestAPKSnapshots_ConfiguredNameWins(t *testing.T) { + upstream := newAPKSnapshotUpstream(t) + h, _ := newSnapshotAPKHandler(t, upstream.server.URL) + h.repositories["alpine@2026-01-10"] = upstream.server.URL + + expectAPKResponse(t, h, "/alpine@2026-01-10"+apkSnapshotIndexPath, http.StatusOK, "index v1") +} + +// TestAPKSnapshots_SameVersionRecordedTwice checks that two requests +// recording the same version in the same millisecond, as coalesced fetches +// after an upstream update can, leave the recorded snapshot readable: the +// request whose row is not added must not delete the other's blob. +func TestAPKSnapshots_SameVersionRecordedTwice(t *testing.T) { + u := newAPKSnapshotUpstream(t) + h, db := newSnapshotAPKHandler(t, u.server.URL) + expectAPKResponse(t, h, "/alpine"+apkSnapshotIndexPath, http.StatusOK, "index v1") + + key := h.metadataCacheKey("alpine", u.server.URL, apkSnapshotIndexPath[1:]) + entry, err := db.GetMetadataCache(apkEcosystem, key) + if err != nil || entry == nil { + t.Fatalf("cached index row = %v, %v", entry, err) + } + if _, err := db.Exec(`DELETE FROM metadata_snapshots`); err != nil { + t.Fatal(err) + } + validFrom := time.Now() + h.storeSnapshot(t.Context(), key, entry, validFrom) + h.storeSnapshot(t.Context(), key, entry, validFrom) + + if n := snapshotCount(t, db); n != 1 { + t.Fatalf("%d snapshots recorded, want 1", n) + } + snap, err := db.LatestMetadataSnapshot(apkEcosystem, key) + if err != nil || snap == nil { + t.Fatalf("latest snapshot = %v, %v", snap, err) + } + body, err := h.proxy.Storage.Open(t.Context(), snap.StoragePath) + if err != nil { + t.Fatalf("recorded snapshot blob unreadable: %v", err) + } + _ = body.Close() + day := validFrom.UTC().Format(apkSnapshotDateLayout) + expectAPKResponse(t, h, "/alpine@"+day+apkSnapshotIndexPath, http.StatusOK, "index v1") +} + +// pausingWriter blocks the first Write until release is closed, after +// signalling on writing. +type pausingWriter struct { + *httptest.ResponseRecorder + once sync.Once + writing chan struct{} + release chan struct{} +} + +func (w *pausingWriter) Write(b []byte) (int, error) { + w.once.Do(func() { + close(w.writing) + <-w.release + }) + return w.ResponseRecorder.Write(b) +} + +// TestAPKSnapshots_OverlappingRequests pauses a request while it writes +// index v1, lets a second request fetch and serve v2, and then lets the first +// one finish. Both versions must be kept, in the order they were fetched, +// with readable blobs. +func TestAPKSnapshots_OverlappingRequests(t *testing.T) { + u := newAPKSnapshotUpstream(t) + h, db := newSnapshotAPKHandler(t, u.server.URL) + target := "/alpine" + apkSnapshotIndexPath + + first := &pausingWriter{ + ResponseRecorder: httptest.NewRecorder(), + writing: make(chan struct{}), + release: make(chan struct{}), + } + done := make(chan struct{}) + go func() { + defer close(done) + h.Routes().ServeHTTP(first, httptest.NewRequest(http.MethodGet, target, nil)) + }() + select { + case <-first.writing: + case <-done: + t.Fatal("first request finished without writing a body") + } + + u.index.Store("index v2") + expectAPKResponse(t, h, target, http.StatusOK, "index v2") + close(first.release) + <-done + if first.Code != http.StatusOK || first.Body.String() != "index v1" { + t.Fatalf("first request = %d %q, want 200 with index v1", first.Code, first.Body.String()) + } + + var snaps []database.MetadataSnapshot + if err := db.Select(&snaps, `SELECT `+ + `id, ecosystem, name, storage_path, content_type, content_encoding, content_digest, size, valid_from_ms `+ + `FROM metadata_snapshots ORDER BY valid_from_ms, id`); err != nil { + t.Fatal(err) + } + if len(snaps) != 2 { + t.Fatalf("%d snapshots recorded, want 2", len(snaps)) + } + for i, want := range []string{"index v1", "index v2"} { + body, err := h.proxy.Storage.Open(t.Context(), snaps[i].StoragePath) + if err != nil { + t.Fatalf("snapshot %d blob unreadable: %v", i, err) + } + got, _ := io.ReadAll(body) + _ = body.Close() + if string(got) != want { + t.Errorf("snapshot %d = %q, want %q", i, got, want) + } + if snaps[i].Size != int64(len(want)) { + t.Errorf("snapshot %d size = %d, want %d", i, snaps[i].Size, len(want)) + } + } +} + +// TestAPKSnapshots_ConcurrentReplicas records the same index version from +// two replicas sharing a Postgres database, many times at once. One snapshot +// row must remain, with a readable blob, and the other copies are deleted. +func TestAPKSnapshots_ConcurrentReplicas(t *testing.T) { + a, b, db := sharedInstances(t) + u := newAPKSnapshotUpstream(t) + handlers := make([]*APKHandler, 0, 2) + for _, p := range []*Proxy{a, b} { + p.CacheMetadata = true + p.HTTPClient = http.DefaultClient + handlers = append(handlers, NewAPKHandler(p, "http://proxy.example", map[string]string{"alpine": u.server.URL}). + WithSnapshots(30*24*time.Hour)) + } + expectAPKResponse(t, handlers[0], "/alpine"+apkSnapshotIndexPath, http.StatusOK, "index v1") + + key := handlers[0].metadataCacheKey("alpine", u.server.URL, apkSnapshotIndexPath[1:]) + entry, err := db.GetMetadataCache(apkEcosystem, key) + if err != nil || entry == nil { + t.Fatalf("cached index row = %v, %v", entry, err) + } + if _, err := db.Exec(`DELETE FROM metadata_snapshots`); err != nil { + t.Fatal(err) + } + // The request above recorded a copy of its own, which the test leaves be. + store := a.Storage.(*mockStorage) + store.mu.Lock() + before := map[string]bool{} + for path := range store.files { + before[path] = true + } + store.mu.Unlock() + + validFrom := time.Now() + var wg sync.WaitGroup + for i := range 16 { + wg.Go(func() { handlers[i%2].storeSnapshot(t.Context(), key, entry, validFrom) }) + } + wg.Wait() + + if n := snapshotCount(t, db); n != 1 { + t.Fatalf("%d snapshots recorded, want 1", n) + } + snap, err := db.LatestMetadataSnapshot(apkEcosystem, key) + if err != nil || snap == nil { + t.Fatalf("latest snapshot = %v, %v", snap, err) + } + store.mu.Lock() + defer store.mu.Unlock() + if got := string(store.files[snap.StoragePath]); got != "index v1" { + t.Errorf("snapshot blob = %q, want the index", got) + } + for path := range store.files { + if strings.HasPrefix(path, "_snapshots/") && path != snap.StoragePath && !before[path] { + t.Errorf("copy %s of a snapshot that wasn't recorded is left in storage", path) + } + } +} + +// TestAPKSnapshots_CacheHit records an index cached before snapshots were +// enabled when a request is served from the cache within its TTL, and adds +// no row for a later hit on the same version. +func TestAPKSnapshots_CacheHit(t *testing.T) { + u := newAPKSnapshotUpstream(t) + h, db := newSnapshotAPKHandler(t, u.server.URL) + h.proxy.MetadataTTL = 5 * time.Minute + h.WithSnapshots(0) + expectAPKResponse(t, h, "/alpine"+apkSnapshotIndexPath, http.StatusOK, "index v1") + if n := snapshotCount(t, db); n != 0 { + t.Fatalf("%d snapshots recorded with snapshots off, want 0", n) + } + + h.WithSnapshots(30 * 24 * time.Hour) + // Upstream moved on; a hit still serves the cached v1. + u.index.Store("index v2") + expectAPKResponse(t, h, "/alpine"+apkSnapshotIndexPath, http.StatusOK, "index v1") + if n := snapshotCount(t, db); n != 1 { + t.Fatalf("%d snapshots recorded on a cache hit, want 1", n) + } + key := h.metadataCacheKey("alpine", u.server.URL, apkSnapshotIndexPath[1:]) + snap, err := db.LatestMetadataSnapshot(apkEcosystem, key) + if err != nil || snap == nil { + t.Fatalf("latest snapshot = %v, %v", snap, err) + } + body, err := h.proxy.Storage.Open(t.Context(), snap.StoragePath) + if err != nil { + t.Fatalf("recorded snapshot blob unreadable: %v", err) + } + got, _ := io.ReadAll(body) + _ = body.Close() + if string(got) != "index v1" { + t.Fatalf("snapshot blob = %q, want %q", got, "index v1") + } + + expectAPKResponse(t, h, "/alpine"+apkSnapshotIndexPath, http.StatusOK, "index v1") + if n := snapshotCount(t, db); n != 1 { + t.Fatalf("%d snapshots after a second hit on the same version, want 1", n) + } +} diff --git a/internal/handler/arch.go b/internal/handler/arch.go index f2abedf..da1a6f1 100644 --- a/internal/handler/arch.go +++ b/internal/handler/arch.go @@ -198,13 +198,13 @@ func (h *ArchHandler) handleDatabase(w http.ResponseWriter, r *http.Request, rep } d := h.database(repository, upstreamURL, path) if _, hit := p.cachedMetadataState(r.Context(), archEcosystem, d.dbKey, nil); hit != nil { - metrics.RecordCacheHit(archEcosystem) - h.writeMetadata(w, r, d.dbKey, *hit) + metrics.RecordMetadataCacheHit(archEcosystem, len(hit.body)) + h.writeMetadata(w, r, *hit) return } p.recordMetadataCacheMiss(archEcosystem) res := h.sharedRefresh(r.Context(), d, true) - h.writeMetadata(w, r, d.dbKey, res) + h.writeMetadata(w, r, res) } // handleDatabaseSignature serves the signature stored for the cached @@ -217,8 +217,8 @@ func (h *ArchHandler) handleDatabaseSignature(w http.ResponseWriter, r *http.Req } d := h.database(repository, upstreamURL, strings.TrimSuffix(path, archSignatureSuffix)) if res, ok := h.cachedSignature(r.Context(), d); ok { - metrics.RecordCacheHit(archEcosystem) - h.writeMetadata(w, r, d.sigKey, res) + metrics.RecordMetadataCacheHit(archEcosystem, len(res.body)) + h.writeMetadata(w, r, res) return } p.recordMetadataCacheMiss(archEcosystem) @@ -242,7 +242,7 @@ func (h *ArchHandler) handleDatabaseSignature(w http.ResponseWriter, r *http.Req } return metadataResult{err: errArchSignatureUnpaired} }) - h.writeMetadata(w, r, d.sigKey, res) + h.writeMetadata(w, r, res) } var errArchSignatureUnpaired = errors.New("database signature could not be paired with the database") @@ -324,7 +324,7 @@ func (h *ArchHandler) fetchDatabase(ctx context.Context, d archDatabase, entry * return metadataResult{err: fmt.Errorf("upstream failed and no cached metadata: %w", err)}, nil } p.Logger.Warn("upstream metadata fetch failed, checking cache", "ecosystem", archEcosystem, "key", d.dbKey, "error", err) - return h.readDatabase(ctx, p.currentMetadataEntry(archEcosystem, d.dbKey, entry), err) + return h.readDatabase(ctx, p.currentMetadataEntry(archEcosystem, d.dbKey, entry), err, true) } // storeDatabase caches meta under its digest and returns the database the @@ -336,7 +336,7 @@ func (h *ArchHandler) storeDatabase(ctx context.Context, d archDatabase, meta *u defer h.lock(d.dbKey)() previous, _ := p.DB.GetMetadataCache(archEcosystem, d.dbKey) - if previous != nil && previous.StoragePath == path { + if previous != nil && previous.StoragePath == path && h.blobExists(ctx, path) { // Same bytes: a failed rewrite would delete the blob the row uses. h.touchDatabase(previous, meta) } else { @@ -345,15 +345,22 @@ func (h *ArchHandler) storeDatabase(ctx context.Context, d archDatabase, meta *u row, _ := p.DB.GetMetadataCache(archEcosystem, d.dbKey) if row == nil { // Nothing cached at all: serve it like an uncached proxy would. - return metadataResult{body: meta.body, contentType: meta.contentType, contentEncoding: meta.contentEncoding}, nil + return fetchedResult(meta, ""), nil } if row.StoragePath != path { - return h.readDatabase(ctx, row, errArchDatabaseNotCached) + return h.readDatabase(ctx, row, errArchDatabaseNotCached, false) } if previous != nil && previous.StoragePath != path { _ = p.Storage.Delete(ctx, previous.StoragePath) } - return metadataResult{body: meta.body, contentType: meta.contentType, contentEncoding: meta.contentEncoding}, row + return fetchedResult(meta, row.ContentDigest.String), row +} + +// blobExists reports whether path is stored. Size eviction can remove a blob +// while a refresh re-creates its row, and only a rewrite brings it back. +func (h *ArchHandler) blobExists(ctx context.Context, path string) bool { + ok, err := h.proxy.Storage.Exists(ctx, path) + return ok || err != nil } // touchDatabase marks an unchanged cached database as fetched now. @@ -370,13 +377,18 @@ func (h *ArchHandler) touchDatabase(row *database.MetadataCacheEntry, meta *upst var errArchDatabaseNotCached = errors.New("database could not be cached") // readDatabase returns the cached database row's bytes, or cause if they are -// unreadable. -func (h *ArchHandler) readDatabase(ctx context.Context, row *database.MetadataCacheEntry, cause error) (metadataResult, *database.MetadataCacheEntry) { +// unreadable. stale marks them as served because the upstream failed with +// cause. +func (h *ArchHandler) readDatabase(ctx context.Context, row *database.MetadataCacheEntry, cause error, stale bool) (metadataResult, *database.MetadataCacheEntry) { body, contentType, err := h.proxy.readCachedMetadata(ctx, row, nil) if err != nil { return metadataResult{err: fmt.Errorf("cached database unusable (%v): %w", err, cause)}, nil } - return metadataResult{body: body, contentType: contentType, contentEncoding: row.ContentEncoding.String}, row + res := metadataResult{body: body, contentType: contentType, contentEncoding: row.ContentEncoding.String} + if stale { + res.stale, res.upstreamErr = true, cause + } + return res.describedBy(row), row } // lock serializes cache writes for one database and its signature, so a row @@ -426,7 +438,7 @@ func (h *ArchHandler) storedSignature(ctx context.Context, d archDatabase, dbDig if err != nil { return metadataResult{}, false } - return metadataResult{body: body, contentType: contentType, contentEncoding: entry.ContentEncoding.String}, true + return metadataResult{body: body, contentType: contentType, contentEncoding: entry.ContentEncoding.String}.describedBy(entry), true } return metadataResult{}, false } @@ -471,7 +483,7 @@ func archDigest(body []byte) string { return "sha256:" + hex.EncodeToString(digest[:]) } -func (h *ArchHandler) writeMetadata(w http.ResponseWriter, r *http.Request, cacheKey string, res metadataResult) { +func (h *ArchHandler) writeMetadata(w http.ResponseWriter, r *http.Request, res metadataResult) { if res.err != nil { if errors.Is(res.err, ErrUpstreamNotFound) { http.Error(w, "not found", http.StatusNotFound) @@ -484,7 +496,7 @@ func (h *ArchHandler) writeMetadata(w http.ResponseWriter, r *http.Request, cach http.Error(w, "failed to fetch from upstream", http.StatusBadGateway) return } - h.proxy.writeMetadataCachedResponseWithEncoding(w, r, archEcosystem, cacheKey, res.body, res.contentType, res.contentEncoding) + writeMetadataResult(w, r, res) } // metadataCacheKey hashes repository, upstream URL and path, as APKHandler does. diff --git a/internal/handler/arch_test.go b/internal/handler/arch_test.go index 3affad5..02c87fa 100644 --- a/internal/handler/arch_test.go +++ b/internal/handler/arch_test.go @@ -1,6 +1,7 @@ package handler import ( + "database/sql" "fmt" "net/http" "net/http/httptest" @@ -648,3 +649,55 @@ func serveArchRequest(h *ArchHandler, method, target string, header http.Header) h.Routes().ServeHTTP(w, req) return w } + +// TestArchHandler_DatabaseValidatorsDescribeBody checks a fetched database +// goes out with its own Last-Modified, not that of the cache row, which +// another instance may have rewritten while the signature was fetched. +func TestArchHandler_DatabaseValidatorsDescribeBody(t *testing.T) { + const dbPath, sigPath = "/core/os/x86_64/core.db", "/core/os/x86_64/core.db.sig" + fetched := time.Date(2026, 10, 1, 12, 0, 0, 0, time.UTC) + rewritten := fetched.Add(time.Hour) + upstream := newArchUpstream(t, map[string][]byte{dbPath: []byte("core-db-v1"), sigPath: []byte("sig")}) + upstream.modified[dbPath] = fetched + proxy := newArchTestProxy(t, upstream) + h := NewArchHandler(proxy, "http://proxy.example", map[string]string{"archlinux": upstream.URL}) + key := h.metadataCacheKey("archlinux", upstream.URL, "core/os/x86_64/core.db") + upstream.served = func(path string) { + if path != sigPath { + return + } + entry, err := proxy.DB.GetMetadataCache(archEcosystem, key) + if err != nil || entry == nil { + t.Errorf("database row while fetching the signature: %v", err) + return + } + entry.LastModified = sql.NullTime{Time: rewritten, Valid: true} + if err := proxy.DB.UpsertMetadataCache(entry); err != nil { + t.Error(err) + } + } + + w := serveArchRequest(h, http.MethodGet, "/archlinux"+dbPath, nil) + assertArchBody(t, w, "database", []byte("core-db-v1")) + if got := w.Header().Get("Last-Modified"); got != fetched.Format(http.TimeFormat) { + t.Errorf("Last-Modified = %q, want the fetched database's %q", got, fetched.Format(http.TimeFormat)) + } +} + +// TestArchHandler_StaleDatabaseMarkedWithoutTTL checks the stale fallback +// carries the Warning header with metadata_ttl 0. +func TestArchHandler_StaleDatabaseMarkedWithoutTTL(t *testing.T) { + db := []byte("core-db-bytes") + upstream := newArchUpstream(t, map[string][]byte{"/core/os/x86_64/core.db": db}) + proxy := newArchTestProxy(t, upstream) + proxy.MetadataTTL = 0 + h := NewArchHandler(proxy, "http://proxy.example", map[string]string{"archlinux": upstream.URL}) + + assertArchBody(t, serveArchRequest(h, http.MethodGet, "/archlinux/core/os/x86_64/core.db", nil), "seed", db) + upstream.available.Store(false) + w := serveArchRequest(h, http.MethodGet, "/archlinux/core/os/x86_64/core.db", nil) + assertArchBody(t, w, "stale", db) + if got := w.Header().Get("Warning"); got != staleWarning { + t.Errorf("Warning = %q, want %q", got, staleWarning) + } +} diff --git a/internal/handler/artifact_size.go b/internal/handler/artifact_size.go deleted file mode 100644 index d4c733b..0000000 --- a/internal/handler/artifact_size.go +++ /dev/null @@ -1,76 +0,0 @@ -package handler - -import ( - "context" - "errors" - "fmt" - "io" - "net/http" - - "github.com/git-pkgs/registries/fetch" -) - -// ErrArtifactTooLarge is returned for an upstream artifact larger than the -// configured artifact size limit. -var ErrArtifactTooLarge = errors.New("artifact exceeds size limit") - -// LimitArtifactSize wraps fetcher so no artifact over maxSize bytes is -// fetched. An artifact whose declared size is over the limit is refused -// before its body is read; one of unknown size fails once reading passes the -// limit, so the store or stream consuming it fails and nothing is cached. -// A maxSize of zero or less returns fetcher unchanged. -func LimitArtifactSize(fetcher fetch.FetcherInterface, maxSize int64) fetch.FetcherInterface { //nolint:ireturn // returns fetcher itself when there is no limit - if maxSize <= 0 { - return fetcher - } - return &sizeLimitedFetcher{FetcherInterface: fetcher, maxSize: maxSize} -} - -type sizeLimitedFetcher struct { - fetch.FetcherInterface - maxSize int64 -} - -func (f *sizeLimitedFetcher) Fetch(ctx context.Context, url string) (*fetch.Artifact, error) { - return f.limit(f.FetcherInterface.Fetch(ctx, url)) -} - -func (f *sizeLimitedFetcher) FetchWithHeaders(ctx context.Context, url string, headers http.Header) (*fetch.Artifact, error) { - return f.limit(f.FetcherInterface.FetchWithHeaders(ctx, url, headers)) -} - -func (f *sizeLimitedFetcher) limit(artifact *fetch.Artifact, err error) (*fetch.Artifact, error) { - if err != nil { - return nil, err - } - if artifact.Size > f.maxSize { - _ = artifact.Body.Close() - return nil, fmt.Errorf("%w: upstream declared %d bytes, limit is %d", ErrArtifactTooLarge, artifact.Size, f.maxSize) - } - limited := *artifact - limited.Body = &sizeLimitedBody{ReadCloser: artifact.Body, remaining: f.maxSize} - return &limited, nil -} - -// sizeLimitedBody fails with ErrArtifactTooLarge once more than the limit has -// been read. It reads one byte past the limit to tell an artifact of exactly -// the limit from a larger one. -type sizeLimitedBody struct { - io.ReadCloser - remaining int64 -} - -func (b *sizeLimitedBody) Read(p []byte) (int, error) { - if b.remaining < 0 { - return 0, ErrArtifactTooLarge - } - if int64(len(p)) > b.remaining+1 { - p = p[:b.remaining+1] - } - n, err := b.ReadCloser.Read(p) - b.remaining -= int64(n) - if b.remaining < 0 { - return n + int(b.remaining), ErrArtifactTooLarge - } - return n, err -} diff --git a/internal/handler/artifact_size_test.go b/internal/handler/artifact_size_test.go index f6fe9af..68dc25d 100644 --- a/internal/handler/artifact_size_test.go +++ b/internal/handler/artifact_size_test.go @@ -6,83 +6,36 @@ import ( "io" "net/http" "net/http/httptest" - "strings" "testing" "github.com/git-pkgs/registries/fetch" ) -type closeRecorder struct { - io.Reader - closed bool -} - -func (c *closeRecorder) Close() error { - c.closed = true - return nil -} - -func TestLimitArtifactSizeUnlimitedReturnsFetcher(t *testing.T) { - fetcher := &mockFetcher{} - if got := LimitArtifactSize(fetcher, 0); got != fetcher { - t.Errorf("LimitArtifactSize(f, 0) = %T, want the fetcher itself", got) - } -} - -func TestLimitArtifactSizeRefusesDeclaredOversize(t *testing.T) { - body := &closeRecorder{Reader: strings.NewReader("0123456789")} - limited := LimitArtifactSize(&mockFetcher{artifact: &fetch.Artifact{Body: body, Size: 10}}, 4) - - _, err := limited.Fetch(context.Background(), "https://registry.example/a.tgz") - if !errors.Is(err, ErrArtifactTooLarge) { - t.Fatalf("Fetch error = %v, want ErrArtifactTooLarge", err) - } - if !body.closed { - t.Error("refused body was not closed") - } -} - -func TestLimitArtifactSizeFailsUndeclaredOversizeWhileReading(t *testing.T) { - limited := LimitArtifactSize(&mockFetcher{artifact: &fetch.Artifact{ - Body: io.NopCloser(strings.NewReader("0123456789")), Size: -1, - }}, 4) - - artifact, err := limited.Fetch(context.Background(), "https://registry.example/a.tgz") - if err != nil { - t.Fatalf("Fetch failed: %v", err) - } - if _, err := io.ReadAll(artifact.Body); !errors.Is(err, ErrArtifactTooLarge) { - t.Errorf("reading body error = %v, want ErrArtifactTooLarge", err) - } -} - -func TestLimitArtifactSizeAllowsArtifactAtLimit(t *testing.T) { - limited := LimitArtifactSize(&mockFetcher{artifact: &fetch.Artifact{ - Body: io.NopCloser(strings.NewReader("0123")), Size: -1, - }}, 4) - - artifact, err := limited.FetchWithHeaders(context.Background(), "https://registry.example/a.tgz", nil) - if err != nil { - t.Fatalf("Fetch failed: %v", err) - } - data, err := io.ReadAll(artifact.Body) - if err != nil || string(data) != "0123" { - t.Errorf("body = %q, %v; want %q, nil", data, err, "0123") - } +func artifactSizeFetcher(t *testing.T) (*fetch.Fetcher, string) { + t.Helper() + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.(http.Flusher).Flush() + _, _ = io.WriteString(w, "0123456789") + })) + t.Cleanup(upstream.Close) + f := fetch.NewFetcher(fetch.WithHTTPClient(upstream.Client()), fetch.WithMaxArtifactSize(4)) + t.Cleanup(func() { _ = f.Close() }) + return f, upstream.URL } func TestOversizedArtifactIsNotCached(t *testing.T) { - proxy, db, store, fetcher := setupTestProxy(t) - fetcher.artifact = &fetch.Artifact{Body: io.NopCloser(strings.NewReader("0123456789")), Size: -1} - proxy.Fetcher = LimitArtifactSize(fetcher, 4) + proxy, db, store, _ := setupTestProxy(t) + limited, upstream := artifactSizeFetcher(t) + proxy.Fetcher = limited - _, err := proxy.GetOrFetchArtifactFromURL(context.Background(), "npm", "big", "1.0.0", "big-1.0.0.tgz", "https://registry.example/big-1.0.0.tgz") - if !errors.Is(err, ErrArtifactTooLarge) { - t.Fatalf("GetOrFetchArtifactFromURL error = %v, want ErrArtifactTooLarge", err) + _, err := proxy.GetOrFetchArtifactFromURL(context.Background(), "npm", "big", "1.0.0", "big-1.0.0.tgz", upstream+"/big-1.0.0.tgz") + if !errors.Is(err, fetch.ErrArtifactTooLarge) { + t.Fatalf("GetOrFetchArtifactFromURL error = %v, want fetch.ErrArtifactTooLarge", err) } if len(store.files) != 0 { t.Errorf("storage holds %d objects after an oversized fetch, want 0", len(store.files)) } + fetchErr := err record, err := db.GetArtifact("pkg:npm/big@1.0.0", "big-1.0.0.tgz") if err != nil { t.Fatalf("GetArtifact failed: %v", err) @@ -92,24 +45,24 @@ func TestOversizedArtifactIsNotCached(t *testing.T) { } rec := httptest.NewRecorder() - proxy.serveArtifactError(rec, err, "failed to fetch package") + proxy.serveArtifactError(rec, fetchErr, "failed to fetch package") if rec.Code != http.StatusBadGateway { t.Errorf("status = %d, want %d", rec.Code, http.StatusBadGateway) } } func TestOversizedStreamedArtifactFailsTheStream(t *testing.T) { - proxy, _, _, fetcher := setupTestProxy(t) + proxy, _, _, _ := setupTestProxy(t) proxy.StreamArtifacts = true - fetcher.artifact = &fetch.Artifact{Body: io.NopCloser(strings.NewReader("0123456789")), Size: -1} - proxy.Fetcher = LimitArtifactSize(fetcher, 4) + limited, upstream := artifactSizeFetcher(t) + proxy.Fetcher = limited - result, err := proxy.GetOrFetchArtifactFromURL(context.Background(), "npm", "big", "1.0.0", "big-1.0.0.tgz", "https://registry.example/big-1.0.0.tgz") + result, err := proxy.GetOrFetchArtifactFromURL(context.Background(), "npm", "big", "1.0.0", "big-1.0.0.tgz", upstream+"/big-1.0.0.tgz") if err != nil { t.Fatalf("GetOrFetchArtifactFromURL failed: %v", err) } defer func() { _ = result.Reader.Close() }() - if _, err := io.ReadAll(result.Reader); !errors.Is(err, ErrArtifactTooLarge) { - t.Errorf("streamed body error = %v, want ErrArtifactTooLarge", err) + if _, err := io.ReadAll(result.Reader); !errors.Is(err, fetch.ErrArtifactTooLarge) { + t.Errorf("streamed body error = %v, want fetch.ErrArtifactTooLarge", err) } } diff --git a/internal/handler/cache_key.go b/internal/handler/cache_key.go new file mode 100644 index 0000000..6c2e8a5 --- /dev/null +++ b/internal/handler/cache_key.go @@ -0,0 +1,21 @@ +package handler + +import ( + "crypto/sha256" + "encoding/hex" + "strconv" +) + +// hashedCacheKey derives a metadata cache key from parts such as the +// upstream URL, the request path and the query. Each part is length-prefixed +// before hashing, so no two different part lists share a key, whatever bytes +// the parts contain. +func hashedCacheKey(parts ...string) string { + h := sha256.New() + for _, part := range parts { + _, _ = h.Write([]byte(strconv.Itoa(len(part)))) + _, _ = h.Write([]byte{':'}) + _, _ = h.Write([]byte(part)) + } + return hex.EncodeToString(h.Sum(nil)) +} diff --git a/internal/handler/cache_key_test.go b/internal/handler/cache_key_test.go new file mode 100644 index 0000000..8af47a2 --- /dev/null +++ b/internal/handler/cache_key_test.go @@ -0,0 +1,74 @@ +package handler + +import ( + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" +) + +// TestConanMetadataKeysKeepReferencesApart checks that Conan references whose +// paths only differ in where '/' and '_' fall, or in a query, are cached +// apart. Names and versions may contain '_'. +func TestConanMetadataKeysKeepReferencesApart(t *testing.T) { + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _, _ = io.WriteString(w, r.URL.Path+"?"+r.URL.RawQuery) + })) + defer upstream.Close() + + proxy, _, _, _ := setupTestProxy(t) + proxy.CacheMetadata = true + proxy.MetadataTTL = time.Hour + proxy.HTTPClient = upstream.Client() + srv := httptest.NewServer(NewConanHandlerWithUpstream(proxy, testProxyURL, upstream.URL).Routes()) + defer srv.Close() + + for _, pair := range [][2]string{ + {"/v2/conans/foo/bar_1.0/_/_/latest", "/v2/conans/foo_bar/1.0/_/_/latest"}, + {"/v2/conans/foo/bar_1.0/_/_/revisions/r1/files/conanfile.py", "/v2/conans/foo_bar/1.0/_/_/revisions/r1/files/conanfile.py"}, + {"/v2/conans/search?q=zlib", "/v2/conans/search_q=zlib"}, + } { + for _, target := range pair { + resp, err := http.Get(srv.URL + target) + if err != nil { + t.Fatal(err) + } + body, _ := io.ReadAll(resp.Body) + _ = resp.Body.Close() + want := target + if !strings.Contains(want, "?") { + want += "?" + } + if string(body) != want { + t.Errorf("GET %s served %q, want %q", target, body, want) + } + } + } +} + +// TestMetadataCacheKeysUnambiguous checks that the path-based metadata cache +// keys of the other ecosystems keep paths apart that differ only in where +// '/' and '_' fall. +func TestMetadataCacheKeysUnambiguous(t *testing.T) { + const a, b = "x/foo/bar_1.0/file", "x/foo_bar/1.0/file" + + maven := mavenSource{upstreamURL: "https://repo.test"} + debian := NewDebianHandler(nil, "http://proxy.test", "https://deb.test", nil) + rpm := NewRPMHandlerWithUpstream(nil, "http://proxy.test", "https://rpm.test") + cran := NewCRANHandlerWithUpstream(nil, "http://proxy.test", "https://cran.test") + conda := NewCondaHandlerWithUpstream(nil, "http://proxy.test", "https://conda.test") + + for name, key := range map[string]func(string) string{ + "maven": maven.metadataCacheKey, + "debian": func(p string) string { return debian.metadataCacheKeyFor("", debian.upstreamURL, p) }, + "rpm": func(p string) string { return rpm.metadataCacheKey(p) }, + "cran": func(p string) string { return cran.metadataCacheKey("/" + p) }, + "conda": func(p string) string { return conda.metadataCacheKey("/" + p) }, + } { + if key(a) == key(b) { + t.Errorf("%s: %s and %s share metadata cache key %q", name, a, b, key(a)) + } + } +} diff --git a/internal/handler/cargo.go b/internal/handler/cargo.go index d30d2e6..aca7416 100644 --- a/internal/handler/cargo.go +++ b/internal/handler/cargo.go @@ -2,6 +2,7 @@ package handler import ( "bufio" + "bytes" "encoding/json" "errors" "fmt" @@ -102,7 +103,7 @@ func (h *CargoHandler) handleIndex(w http.ResponseWriter, r *http.Request) { return } - h.proxy.Logger.Info("cargo index request", "crate", name) + h.proxy.Logger.Debug("cargo index request", "crate", name) indexPath := h.buildIndexPath(name) upstreamURL := fmt.Sprintf("%s/%s", h.indexURL, indexPath) @@ -171,7 +172,7 @@ func (h *CargoHandler) applyCooldownFiltering(downstreamResponse http.ResponseWr cratePURL := canonicalPackagePURL("cargo", crate.Name) - if !h.proxy.Cooldown.IsAllowed("cargo", cratePURL, publishedAt) { + if !h.proxy.cooldown().IsAllowed("cargo", cratePURL, publishedAt) { h.proxy.Logger.Info("cooldown: filtering cargo version", "crate", crate.Name, "version", crate.Version, "published", crate.PublishTime) @@ -186,6 +187,32 @@ func (h *CargoHandler) applyCooldownFiltering(downstreamResponse http.ResponseWr } } +// publishTime reads a crate version's pubtime from the sparse index, sharing +// the index cache with handleIndex. Entries published before crates.io +// recorded pubtime have none. +func (h *CargoHandler) publishTime(r *http.Request, name, version string) (time.Time, bool, error) { + upstreamURL := fmt.Sprintf("%s/%s", h.indexURL, h.buildIndexPath(name)) + body, _, err := h.proxy.FetchOrCacheMetadata(r.Context(), "cargo", name, upstreamURL, "text/plain") + if err != nil { + return time.Time{}, false, err + } + for line := range bytes.SplitSeq(body, []byte("\n")) { + if len(bytes.TrimSpace(line)) == 0 { + continue + } + var entry crateIndexEntry + if err := json.Unmarshal(line, &entry); err != nil { + return time.Time{}, false, err + } + if entry.Version != version { + continue + } + published, err := time.Parse(time.RFC3339, entry.PublishTime) + return published, err == nil, nil + } + return time.Time{}, false, nil +} + // buildIndexPath builds the sparse index path for a crate name. func (h *CargoHandler) buildIndexPath(name string) string { name = strings.ToLower(name) @@ -214,9 +241,19 @@ func (h *CargoHandler) handleDownload(w http.ResponseWriter, r *http.Request) { filename := fmt.Sprintf("%s-%s.crate", name, version) - h.proxy.Logger.Info("cargo download request", + h.proxy.Logger.Debug("cargo download request", "crate", name, "version", version, "filename", filename) + if h.proxy.withholdInCooldown(w, r, downloadVersion{ + ecosystem: "cargo", policyName: name, storedName: name, version: version, cacheName: name, filename: filename, + lookup: func() (time.Time, bool, bool, error) { + published, ok, err := h.publishTime(r, name, version) + return published, ok, false, err + }, + }) { + return + } + downloadURL := fmt.Sprintf( "%s/%s/%s", h.downloadURL, diff --git a/internal/handler/chef.go b/internal/handler/chef.go new file mode 100644 index 0000000..cf2002d --- /dev/null +++ b/internal/handler/chef.go @@ -0,0 +1,355 @@ +package handler + +import ( + "bytes" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "net/http" + "net/url" + "path" + "regexp" + "strings" +) + +const ( + chefEcosystem = "chef" + chefMountPath = "/chef" + chefAPIPath = "/api/v1" + // 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") +) + +// ChefHandler serves a read-only Chef Supermarket at /chef. Berkshelf and +// Policyfiles resolve dependencies against /universe and then download each +// cookbook through the cookbook API. Every download location in those +// documents is rewritten to the proxy, so cookbooks are fetched through it and +// cached; dependency constraints and every other field pass through unchanged. +type ChefHandler struct { + proxy *Proxy + proxyURL string + upstreamURL string + // upstreamKey identifies the upstream in cache keys, so pointing + // upstream.chef at another Supermarket does not serve the previous one's + // documents or archives. + upstreamKey string +} + +// NewChefHandler creates a Chef Supermarket handler for the Supermarket at +// upstreamURL, such as https://supermarket.chef.io or a private Supermarket. +func NewChefHandler(proxy *Proxy, proxyURL, upstreamURL string) *ChefHandler { + upstreamURL = strings.TrimSuffix(upstreamURL, "/") + digest := sha256.Sum256([]byte(upstreamURL)) + return &ChefHandler{ + proxy: proxy, + proxyURL: strings.TrimSuffix(proxyURL, "/"), + upstreamURL: upstreamURL, + upstreamKey: hex.EncodeToString(digest[:])[:chefUpstreamKeyLength], + } +} + +// Routes returns the HTTP handler for Chef Supermarket requests. +func (h *ChefHandler) Routes() http.Handler { + mux := http.NewServeMux() + mux.HandleFunc("GET /universe", h.handleUniverse) + mux.HandleFunc("GET "+chefAPIPath+"/cookbooks/{name}", h.handleCookbook) + mux.HandleFunc("GET "+chefAPIPath+"/cookbooks/{name}/versions/{version}", h.handleVersion) + mux.HandleFunc("GET "+chefAPIPath+"/cookbooks/{name}/versions/{version}/download", h.handleDownload) + return mux +} + +func (h *ChefHandler) handleUniverse(w http.ResponseWriter, r *http.Request) { + h.serveDocument(w, r, "universe", h.upstreamURL+"/universe", h.rewriteUniverse) +} + +func (h *ChefHandler) handleCookbook(w http.ResponseWriter, r *http.Request) { + name, ok := chefCookbookFromRequest(r) + if !ok { + http.Error(w, "invalid cookbook name", http.StatusBadRequest) + return + } + h.serveDocument(w, r, "cookbooks/"+name, h.upstreamCookbookURL(name), func(body []byte) ([]byte, error) { + return h.rewriteCookbook(name, body) + }) +} + +func (h *ChefHandler) handleVersion(w http.ResponseWriter, r *http.Request) { + name, version, ok := chefVersionFromRequest(r) + if !ok { + http.Error(w, "invalid cookbook version", http.StatusBadRequest) + return + } + h.serveDocument(w, r, "cookbooks/"+name+"/versions/"+version, h.upstreamVersionURL(name, version), func(body []byte) ([]byte, error) { + return h.rewriteVersion(name, version, body) + }) +} + +// handleDownload serves a cookbook archive from the cache. An archive not +// cached yet is fetched through the Supermarket download endpoint, following +// the redirect it answers with. A cached archive is served without the +// upstream. Archives are cached per upstream, since two Supermarkets can +// publish different cookbooks under the same name and version. +func (h *ChefHandler) handleDownload(w http.ResponseWriter, r *http.Request) { + name, version, ok := chefVersionFromRequest(r) + if !ok { + http.Error(w, "invalid cookbook version", http.StatusBadRequest) + return + } + + result, err := h.proxy.GetOrFetchArtifactFromURL( + r.Context(), chefEcosystem, name, version, h.archiveFilename(name, version), h.upstreamVersionURL(name, version)+"/download") + if err != nil { + h.proxy.serveArtifactError(w, err, "failed to fetch cookbook") + return + } + if result.Artifact.MediaType == "" { + w.Header().Set(headerContentType, "application/gzip") + } + ServeArtifactRequest(w, r, result) +} + +// serveDocument serves a JSON document from the metadata cache, which applies +// the metadata TTL and falls back to the stored copy while the upstream is +// unavailable, rewritten by rewrite. +func (h *ChefHandler) serveDocument(w http.ResponseWriter, r *http.Request, documentKey, upstreamURL string, rewrite func([]byte) ([]byte, error)) { + cacheKey := h.cacheKey(documentKey) + if stored, ok := h.proxy.storedRewrite(chefEcosystem, cacheKey, h.proxyURL, cacheKey); ok { + serveRewrittenMetadata(w, r, stored) + return + } + + upstream := h.proxy.fetchMetadataDocument(r.Context(), chefEcosystem, cacheKey, upstreamURL, contentTypeJSON, nil) + if err := upstream.err; err != nil { + if errors.Is(err, ErrUpstreamNotFound) { + http.Error(w, "not found", http.StatusNotFound) + return + } + if writeUpstreamHeld(w, err) { + return + } + h.proxy.Logger.Error("Chef Supermarket request failed", "url", upstreamURL, "error", err) + http.Error(w, "upstream request failed", http.StatusBadGateway) + return + } + + rewritten, err := h.proxy.cachedRewrite(r.Context(), chefEcosystem, h.proxyURL, cacheKey, upstream.body, upstream.digest, + func(body []byte) ([]byte, []string, error) { + out, err := rewrite(body) + return out, nil, err + }) + if err != nil { + if r.Context().Err() != nil { + return // the client left while waiting on a shared rewrite + } + // Serving the document unrewritten would send clients straight to + // the upstream, bypassing the cache. + h.proxy.Logger.Warn("failed to rewrite Chef Supermarket document", "url", upstreamURL, "error", err) + http.Error(w, "invalid Chef Supermarket response", http.StatusBadGateway) + return + } + markStale(w, upstream.stale) + serveRewrittenMetadata(w, r, rewritten) +} + +// 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 (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) +} + +// rewriteCookbook points a cookbook's version URLs at the proxy. +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) +} + +// rewriteVersion points a cookbook version's cookbook and file URLs at the +// proxy. +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) +} + +func (h *ChefHandler) downloadURL(name, version string) string { + return h.versionURL(name, version) + "/download" +} + +func (h *ChefHandler) upstreamCookbookURL(name string) string { + return h.upstreamURL + chefAPIPath + "/cookbooks/" + url.PathEscape(name) +} + +func (h *ChefHandler) upstreamVersionURL(name, version string) string { + return h.upstreamCookbookURL(name) + "/versions/" + url.PathEscape(version) +} + +// cacheKey prefixes a metadata cache key with the upstream's key. +func (h *ChefHandler) cacheKey(documentKey string) string { + return h.upstreamKey + "/" + documentKey +} + +// archiveFilename names a cookbook archive in the cache. The filename is part +// of the artifact's cache identity, so it carries the upstream's key; the +// .tgz extension is kept for browsing the archive. +func (h *ChefHandler) archiveFilename(name, version string) string { + return name + "-" + version + "-" + h.upstreamKey + ".tgz" +} + +func chefCookbookFromRequest(r *http.Request) (string, bool) { + name := r.PathValue("name") + if !chefCookbookName.MatchString(name) || containsPathTraversal(name) { + return "", false + } + return name, true +} + +func chefVersionFromRequest(r *http.Request) (name, version string, ok bool) { + name, ok = chefCookbookFromRequest(r) + if !ok { + return "", "", false + } + version, ok = normalizeChefVersion(r.PathValue("version")) + 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. +func normalizeChefVersion(version string) (string, bool) { + version = strings.ReplaceAll(version, "_", ".") + if !chefVersion.MatchString(version) { + return "", false + } + return version, true +} + +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. +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 +} diff --git a/internal/handler/chef_test.go b/internal/handler/chef_test.go new file mode 100644 index 0000000..51290a5 --- /dev/null +++ b/internal/handler/chef_test.go @@ -0,0 +1,475 @@ +package handler + +import ( + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "net/url" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + upstreamhttp "github.com/git-pkgs/proxy/internal/httpclient" + "github.com/git-pkgs/registries/fetch" +) + +const ( + chefTestProxyURL = "http://proxy.example" + chefTestAPI = chefTestProxyURL + "/chef/api/v1" + chefTestTarball = "cookbook tarball bytes" +) + +// fakeSupermarket serves the parts of the Supermarket API Berkshelf uses, in +// the shapes supermarket.chef.io returns them. Downloads redirect to a second +// server standing in for the storage host, as Supermarket redirects to S3. +type fakeSupermarket struct { + api *httptest.Server + files *httptest.Server + // filesURL is files.URL on another hostname, so a redirect to it leaves + // the API host the way a redirect to S3 does. + filesURL string + + available atomic.Bool + // token, when set, is the bearer token the API requires. + token string + // tarball is the content of every cookbook archive it serves. + tarball string + + mu sync.Mutex + requests map[string]int + fileAuth []string +} + +func newFakeSupermarket(t *testing.T, token string) *fakeSupermarket { + t.Helper() + s := &fakeSupermarket{token: token, tarball: chefTestTarball, requests: map[string]int{}} + s.available.Store(true) + + s.files = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + s.mu.Lock() + s.requests["files "+r.URL.Path]++ + s.fileAuth = append(s.fileAuth, r.Header.Get("Authorization")) + s.mu.Unlock() + if !s.available.Load() { + http.Error(w, "unavailable", http.StatusServiceUnavailable) + return + } + if r.URL.Path != "/cookbook_versions/tarballs/34899/original/apt.tgz" { + http.NotFound(w, r) + return + } + w.Header().Set("Content-Type", "application/x-gzip") + _, _ = w.Write([]byte(s.tarball)) + })) + t.Cleanup(s.files.Close) + s.filesURL = strings.Replace(s.files.URL, "127.0.0.1", "localhost", 1) + + s.api = httptest.NewServer(http.HandlerFunc(s.serveAPI)) + t.Cleanup(s.api.Close) + return s +} + +func (s *fakeSupermarket) serveAPI(w http.ResponseWriter, r *http.Request) { + s.mu.Lock() + s.requests[r.URL.Path]++ + s.mu.Unlock() + if !s.available.Load() { + http.Error(w, "unavailable", http.StatusServiceUnavailable) + return + } + if s.token != "" && r.Header.Get("Authorization") != "Bearer "+s.token { + http.Error(w, "unauthorized", http.StatusUnauthorized) + return + } + + api := s.api.URL + "/api/v1" + w.Header().Set("Content-Type", "application/json") + switch r.URL.Path { + case "/universe": + // Like Supermarket's, these locations carry an explicit port. + located := api + _, _ = fmt.Fprintf(w, `{"apt":{"7.5.22":{"location_type":"opscode","location_path":%q,"download_url":%q,"dependencies":{"compat_resource":">= 0.0.0"}},`+ + `"7.6.0":{"location_type":"opscode","location_path":%q,"download_url":%q,"dependencies":{}}},`+ + `"compat_resource":{"12.19.1":{"location_type":"opscode","location_path":%q,"download_url":%q,"dependencies":{"apt":"~> 7.5"}}}}`, + located, api+"/cookbooks/apt/versions/7.5.22/download", + located, api+"/cookbooks/apt/versions/7.6.0/download", + located, api+"/cookbooks/compat_resource/versions/12.19.1/download") + case "/api/v1/cookbooks/apt": + _, _ = fmt.Fprintf(w, `{"name":"apt","maintainer":"sous-chefs","latest_version":%q,"external_url":"https://github.com/sous-chefs/apt","deprecated":false,"versions":[%q,%q]}`, + api+"/cookbooks/apt/versions/7.6.0", api+"/cookbooks/apt/versions/7.6.0", api+"/cookbooks/apt/versions/7.5.22") + case "/api/v1/cookbooks/apt/versions/7.5.22": + _, _ = fmt.Fprintf(w, `{"license":"Apache-2.0","tarball_file_size":%d,"version":"7.5.22","cookbook":%q,"file":%q,"dependencies":{"compat_resource":">= 0.0.0"}}`, + len(s.tarball), api+"/cookbooks/apt", api+"/cookbooks/apt/versions/7.5.22/download") + case "/api/v1/cookbooks/apt/versions/7.5.22/download": + http.Redirect(w, r, s.filesURL+"/cookbook_versions/tarballs/34899/original/apt.tgz?1714639378", http.StatusFound) + default: + http.NotFound(w, r) + } +} + +func (s *fakeSupermarket) count(key string) int { + s.mu.Lock() + defer s.mu.Unlock() + return s.requests[key] +} + +// newChefTestHandler returns a handler for s using client for every upstream +// request, with metadata caching on. +func newChefTestHandler(t *testing.T, s *fakeSupermarket, client *http.Client) (*ChefHandler, *Proxy) { + t.Helper() + proxy, _, _, _ := setupTestProxy(t) + proxy.CacheMetadata = true + proxy.MetadataTTL = time.Hour + proxy.HTTPClient = client + fetcher := fetch.NewFetcher(fetch.WithHTTPClient(client), fetch.WithMaxRetries(0)) + proxy.Fetcher = fetcher + t.Cleanup(func() { _ = fetcher.Close() }) + return NewChefHandler(proxy, chefTestProxyURL, s.api.URL), proxy +} + +func serveChefRequest(h *ChefHandler, target string) *httptest.ResponseRecorder { + w := httptest.NewRecorder() + h.Routes().ServeHTTP(w, httptest.NewRequest(http.MethodGet, target, nil)) + return w +} + +// proxyPath turns an absolute proxy URL from a rewritten document into the +// path the handler is mounted at. +func proxyPath(t *testing.T, rawURL string) string { + t.Helper() + parsed, err := url.Parse(rawURL) + if err != nil { + t.Fatalf("parse %q: %v", rawURL, err) + } + if parsed.Scheme+"://"+parsed.Host != chefTestProxyURL || !strings.HasPrefix(parsed.Path, "/chef/") { + t.Fatalf("URL %q does not point at the proxy", rawURL) + } + return strings.TrimPrefix(parsed.Path, "/chef") +} + +type chefUniverseEntry struct { + LocationType string `json:"location_type"` + LocationPath string `json:"location_path"` + DownloadURL string `json:"download_url"` + Dependencies json.RawMessage `json:"dependencies"` +} + +func decodeChefUniverse(t *testing.T, body []byte) map[string]map[string]chefUniverseEntry { + t.Helper() + var universe map[string]map[string]chefUniverseEntry + if err := json.Unmarshal(body, &universe); err != nil { + t.Fatalf("decode universe: %v\n%s", err, body) + } + return universe +} + +func TestChefUniverseRewritesLocations(t *testing.T) { + s := newFakeSupermarket(t, "") + h, _ := newChefTestHandler(t, s, s.api.Client()) + + w := serveChefRequest(h, "/universe") + if w.Code != http.StatusOK { + t.Fatalf("status = %d, want 200: %s", w.Code, w.Body.String()) + } + if got := w.Header().Get("Content-Type"); got != contentTypeJSON { + t.Errorf("Content-Type = %q, want %q", got, contentTypeJSON) + } + body := w.Body.String() + if strings.Contains(body, s.api.URL) { + t.Errorf("rewritten universe still points at the upstream: %s", body) + } + + universe := decodeChefUniverse(t, w.Body.Bytes()) + wantDeps := map[string]map[string]string{ + "apt": {"7.5.22": `{"compat_resource":">= 0.0.0"}`, "7.6.0": `{}`}, + "compat_resource": {"12.19.1": `{"apt":"~> 7.5"}`}, + } + for name, versions := range wantDeps { + for version, deps := range versions { + entry, ok := universe[name][version] + if !ok { + t.Errorf("universe lost %s %s", name, version) + continue + } + if entry.LocationType != "opscode" { + t.Errorf("%s %s location_type = %q, want opscode", name, version, entry.LocationType) + } + if entry.LocationPath != chefTestAPI { + t.Errorf("%s %s location_path = %q, want %q", name, version, entry.LocationPath, chefTestAPI) + } + wantDownload := chefTestAPI + "/cookbooks/" + name + "/versions/" + version + "/download" + if entry.DownloadURL != wantDownload { + t.Errorf("%s %s download_url = %q, want %q", name, version, entry.DownloadURL, wantDownload) + } + if string(entry.Dependencies) != deps { + t.Errorf("%s %s dependencies = %s, want %s unchanged", name, version, entry.Dependencies, deps) + } + } + } + // Constraints keep their spelling rather than being HTML-escaped. + if !strings.Contains(body, `">= 0.0.0"`) || !strings.Contains(body, `"~> 7.5"`) { + t.Errorf("dependency constraints were re-escaped: %s", body) + } +} + +func TestChefCookbookMetadataRewritesVersionURLs(t *testing.T) { + s := newFakeSupermarket(t, "") + h, _ := newChefTestHandler(t, s, s.api.Client()) + + w := serveChefRequest(h, "/api/v1/cookbooks/apt") + if w.Code != http.StatusOK { + t.Fatalf("status = %d, want 200: %s", w.Code, w.Body.String()) + } + var cookbook struct { + Name string `json:"name"` + LatestVersion string `json:"latest_version"` + Versions []string `json:"versions"` + ExternalURL string `json:"external_url"` + Deprecated bool `json:"deprecated"` + } + if err := json.Unmarshal(w.Body.Bytes(), &cookbook); err != nil { + t.Fatalf("decode: %v", err) + } + if cookbook.LatestVersion != chefTestAPI+"/cookbooks/apt/versions/7.6.0" { + t.Errorf("latest_version = %q", cookbook.LatestVersion) + } + want := []string{chefTestAPI + "/cookbooks/apt/versions/7.6.0", chefTestAPI + "/cookbooks/apt/versions/7.5.22"} + if strings.Join(cookbook.Versions, ",") != strings.Join(want, ",") { + t.Errorf("versions = %v, want %v", cookbook.Versions, want) + } + if cookbook.Name != "apt" || cookbook.ExternalURL != "https://github.com/sous-chefs/apt" || cookbook.Deprecated { + t.Errorf("unrelated fields changed: %+v", cookbook) + } +} + +func TestChefVersionMetadataAcceptsBerkshelfVersions(t *testing.T) { + s := newFakeSupermarket(t, "") + h, _ := newChefTestHandler(t, s, s.api.Client()) + + // Berkshelf writes versions with underscores in cookbook API paths. + for _, version := range []string{"7_5_22", "7.5.22"} { + w := serveChefRequest(h, "/api/v1/cookbooks/apt/versions/"+version) + if w.Code != http.StatusOK { + t.Fatalf("%s: status = %d, want 200: %s", version, w.Code, w.Body.String()) + } + var document struct { + Version string `json:"version"` + Cookbook string `json:"cookbook"` + File string `json:"file"` + Dependencies json.RawMessage `json:"dependencies"` + License string `json:"license"` + } + if err := json.Unmarshal(w.Body.Bytes(), &document); err != nil { + t.Fatalf("%s: decode: %v", version, err) + } + if document.Cookbook != chefTestAPI+"/cookbooks/apt" { + t.Errorf("%s: cookbook = %q", version, document.Cookbook) + } + if document.File != chefTestAPI+"/cookbooks/apt/versions/7.5.22/download" { + t.Errorf("%s: file = %q", version, document.File) + } + if string(document.Dependencies) != `{"compat_resource":">= 0.0.0"}` || document.License != "Apache-2.0" || document.Version != "7.5.22" { + t.Errorf("%s: unrelated fields changed: %+v", version, document) + } + } + // Both spellings are one document, fetched once. + if got := s.count("/api/v1/cookbooks/apt/versions/7.5.22"); got != 1 { + t.Errorf("upstream version requests = %d, want 1", got) + } +} + +// TestChefBerkshelfFlow follows the requests Berkshelf makes: the universe, +// then the cookbook version at the universe's location_path, then its file. +// The download redirects to the storage host and is cached. It is then served +// with the upstream down, as is the universe. +func TestChefBerkshelfFlow(t *testing.T) { + s := newFakeSupermarket(t, "") + h, proxy := newChefTestHandler(t, s, s.api.Client()) + + universe := decodeChefUniverse(t, serveChefRequest(h, "/universe").Body.Bytes()) + locationPath := universe["apt"]["7.5.22"].LocationPath + + versionResponse := serveChefRequest(h, proxyPath(t, locationPath+"/cookbooks/apt/versions/7_5_22")) + if versionResponse.Code != http.StatusOK { + t.Fatalf("version status = %d: %s", versionResponse.Code, versionResponse.Body.String()) + } + var version struct { + File string `json:"file"` + } + if err := json.Unmarshal(versionResponse.Body.Bytes(), &version); err != nil { + t.Fatalf("decode version: %v", err) + } + + download := serveChefRequest(h, proxyPath(t, version.File)) + if download.Code != http.StatusOK { + t.Fatalf("download status = %d: %s", download.Code, download.Body.String()) + } + if download.Body.String() != chefTestTarball { + t.Errorf("download body = %q, want the tarball", download.Body.String()) + } + if got := s.count("files /cookbook_versions/tarballs/34899/original/apt.tgz"); got != 1 { + t.Errorf("storage host requests = %d, want 1 after following the redirect", got) + } + + // A second download is a cache hit. + if again := serveChefRequest(h, proxyPath(t, version.File)); again.Code != http.StatusOK || again.Body.String() != chefTestTarball { + t.Fatalf("cached download = %d %q", again.Code, again.Body.String()) + } + if got := s.count("/api/v1/cookbooks/apt/versions/7.5.22/download"); got != 1 { + t.Errorf("upstream download requests = %d, want 1 (second served from cache)", got) + } + + // With the upstream down and the metadata TTL lapsed, the cached + // cookbook and the stored universe are still served. + s.available.Store(false) + proxy.MetadataTTL = 0 + if offline := serveChefRequest(h, proxyPath(t, version.File)); offline.Code != http.StatusOK || offline.Body.String() != chefTestTarball { + t.Errorf("offline download = %d %q, want the cached tarball", offline.Code, offline.Body.String()) + } + offlineUniverse := serveChefRequest(h, "/universe") + if offlineUniverse.Code != http.StatusOK { + t.Fatalf("offline universe status = %d: %s", offlineUniverse.Code, offlineUniverse.Body.String()) + } + if got := decodeChefUniverse(t, offlineUniverse.Body.Bytes())["apt"]["7.5.22"].DownloadURL; got != version.File { + t.Errorf("offline universe download_url = %q, want %q", got, version.File) + } +} + +func TestChefUpstreamAuthentication(t *testing.T) { + const token = "supermarket-token" + s := newFakeSupermarket(t, token) + // Credentials are scoped to the Supermarket, as upstream.auth scopes + // them by URL, so the storage host it redirects to never sees them. + client := &http.Client{Transport: upstreamhttp.NewTransport(http.DefaultTransport, + upstreamhttp.AuthFunc(func(requestURL string) (string, string) { + if strings.HasPrefix(requestURL, s.api.URL+"/") { + return "Authorization", "Bearer " + token + } + return "", "" + }))} + h, _ := newChefTestHandler(t, s, client) + + for _, target := range []string{"/universe", "/api/v1/cookbooks/apt", "/api/v1/cookbooks/apt/versions/7.5.22"} { + if w := serveChefRequest(h, target); w.Code != http.StatusOK { + t.Errorf("%s: status = %d, want 200: %s", target, w.Code, w.Body.String()) + } + } + download := serveChefRequest(h, "/api/v1/cookbooks/apt/versions/7.5.22/download") + if download.Code != http.StatusOK || download.Body.String() != chefTestTarball { + t.Fatalf("download = %d %q", download.Code, download.Body.String()) + } + + s.mu.Lock() + defer s.mu.Unlock() + for _, auth := range s.fileAuth { + if auth != "" { + t.Errorf("storage host received Authorization %q", auth) + } + } +} + +func TestChefRejectsInvalidRequests(t *testing.T) { + s := newFakeSupermarket(t, "") + h, _ := newChefTestHandler(t, s, s.api.Client()) + + tests := []struct { + target string + want int + }{ + {"/api/v1/cookbooks/.hidden", http.StatusBadRequest}, + {"/api/v1/cookbooks/apt/versions/latest", http.StatusBadRequest}, + {"/api/v1/cookbooks/apt/versions/1.2.3.4", http.StatusBadRequest}, + {"/api/v1/cookbooks/apt/versions/1.x/download", http.StatusBadRequest}, + {"/api/v1/cookbooks/missing", http.StatusNotFound}, + {"/api/v1/cookbooks/apt/versions/9.9.9", http.StatusNotFound}, + } + for _, tt := range tests { + if w := serveChefRequest(h, tt.target); w.Code != tt.want { + t.Errorf("%s: status = %d, want %d: %s", tt.target, w.Code, tt.want, w.Body.String()) + } + } +} + +// An upstream document that cannot be rewritten is refused rather than +// passed through, which would send clients around the proxy. +func TestChefUnreadableUniverseIsBadGateway(t *testing.T) { + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + _, _ = w.Write([]byte(`["not","a","universe"]`)) + })) + defer upstream.Close() + + proxy, _, _, _ := setupTestProxy(t) + proxy.HTTPClient = upstream.Client() + h := NewChefHandler(proxy, chefTestProxyURL, upstream.URL) + + w := serveChefRequest(h, "/universe") + if w.Code != http.StatusBadGateway { + t.Fatalf("status = %d, want 502: %s", w.Code, w.Body.String()) + } + if strings.Contains(w.Body.String(), "not") { + t.Errorf("unreadable document was passed through: %s", w.Body.String()) + } +} + +// Switching upstream.chef to another Supermarket keeps the cache, but an +// archive cached from the previous one is not served for a cookbook the new +// one publishes under the same name and version. +func TestChefArchiveCacheDependsOnUpstream(t *testing.T) { + const target = "/api/v1/cookbooks/apt/versions/7.5.22/download" + public := newFakeSupermarket(t, "") + private := newFakeSupermarket(t, "") + private.tarball = "private cookbook tarball bytes" + + publicHandler, proxy := newChefTestHandler(t, public, public.api.Client()) + if w := serveChefRequest(publicHandler, target); w.Code != http.StatusOK || w.Body.String() != public.tarball { + t.Fatalf("public download = %d %q", w.Code, w.Body.String()) + } + + privateHandler := NewChefHandler(proxy, chefTestProxyURL, private.api.URL) + w := serveChefRequest(privateHandler, target) + if w.Code != http.StatusOK { + t.Fatalf("private download status = %d: %s", w.Code, w.Body.String()) + } + if w.Body.String() != private.tarball { + t.Errorf("private download = %q, want the private Supermarket's tarball", w.Body.String()) + } + if got := private.count(target); got != 1 { + t.Errorf("private download requests = %d, want 1", got) + } + + // Each upstream's archive stays cached under its own identity. + for _, tt := range []struct { + handler *ChefHandler + upstream *fakeSupermarket + }{{publicHandler, public}, {privateHandler, private}} { + if again := serveChefRequest(tt.handler, target); again.Code != http.StatusOK || again.Body.String() != tt.upstream.tarball { + t.Errorf("cached download from %s = %d %q, want %q", tt.upstream.api.URL, again.Code, again.Body.String(), tt.upstream.tarball) + } + if got := tt.upstream.count(target); got != 1 { + t.Errorf("download requests to %s = %d, want 1 (second served from cache)", tt.upstream.api.URL, got) + } + } +} + +func TestChefCacheKeyDependsOnUpstream(t *testing.T) { + a := NewChefHandler(nil, chefTestProxyURL, "https://supermarket.chef.io") + b := NewChefHandler(nil, chefTestProxyURL, "https://supermarket.example.com/") + if a.cacheKey("universe") == b.cacheKey("universe") { + t.Error("two Supermarkets share a universe cache key") + } + if containsPathTraversal(a.cacheKey("cookbooks/apt/versions/7.5.22")) { + t.Error("cache key is not a valid metadata key") + } + if a.archiveFilename("apt", "7.5.22") == b.archiveFilename("apt", "7.5.22") { + t.Error("two Supermarkets share an archive filename") + } + if got := a.archiveFilename("apt", "7.5.22"); !strings.HasPrefix(got, "apt-7.5.22-") || !strings.HasSuffix(got, ".tgz") { + t.Errorf("archive filename = %q, want apt-7.5.22-.tgz", got) + } + if NewChefHandler(nil, chefTestProxyURL, "https://supermarket.example.com").upstreamKey != b.upstreamKey { + t.Error("a trailing slash changes the upstream key") + } +} diff --git a/internal/handler/composer.go b/internal/handler/composer.go index c28ae0c..6b82cff 100644 --- a/internal/handler/composer.go +++ b/internal/handler/composer.go @@ -55,6 +55,7 @@ type ComposerHandler struct { repoURL string proxyURL string routes packageRoutes + indexCache composerIndexCache } // NewComposerHandler creates a new Composer protocol handler. @@ -100,12 +101,20 @@ func (h *ComposerHandler) Routes() http.Handler { mux.HandleFunc("GET /search.json", h.proxyUpstream) mux.HandleFunc("GET /packages/list.json", h.proxyUpstream) + // Security advisories and filter lists, as the default repository offers them + mux.HandleFunc("GET "+composerAdvisoriesPath, h.handleSecurityAdvisories) + mux.HandleFunc("POST "+composerAdvisoriesPath, h.handleSecurityAdvisories) + mux.HandleFunc("GET "+composerFilterSummaryPath, h.handleFilterSummary) + return mux } -// handleServiceIndex returns the Composer repository service index. +// handleServiceIndex returns the Composer repository service index. It +// carries the security advisories and filter list entries of the default +// repository's own index when that has them, kept in memory for the metadata +// TTL; if the repository has not been reached, the index goes out without +// them. func (h *ComposerHandler) handleServiceIndex(w http.ResponseWriter, r *http.Request) { - // Return a minimal service index pointing to our proxy index := map[string]any{ "packages": map[string]any{}, "metadata-url": h.proxyURL + "/composer/p2/%package%.json", @@ -113,6 +122,9 @@ func (h *ComposerHandler) handleServiceIndex(w http.ResponseWriter, r *http.Requ "search": h.proxyURL + "/composer/search.json?q=%query%&type=%type%", "providers-lazy-url": h.proxyURL + "/composer/p2/%package%.json", } + if upstream, ok := h.upstreamIndex(r.Context()); ok { + upstream.advertise(index, h.proxyURL) + } w.Header().Set(headerContentType, "application/json") _ = json.NewEncoder(w).Encode(index) @@ -144,7 +156,7 @@ func (h *ComposerHandler) handlePackageMetadata(w http.ResponseWriter, r *http.R pkg := parts[1] packageName := vendor + "/" + pkg - h.proxy.Logger.Info("composer metadata request", "package", packageName) + h.proxy.Logger.Debug("composer metadata request", "package", packageName) repoURL, cacheKey := h.sourceFor(packageName) upstreamURL := fmt.Sprintf("%s/p2/%s/%s.json", repoURL, vendor, pkg) @@ -170,7 +182,7 @@ func (h *ComposerHandler) handlePackageMetadata(w http.ResponseWriter, r *http.R return } - upstream := h.proxy.fetchMetadataDocument(r.Context(), "composer", cacheKey, upstreamURL, contentTypeJSON) + upstream := h.proxy.fetchMetadataDocument(r.Context(), "composer", cacheKey, upstreamURL, contentTypeJSON, nil) if err := upstream.err; err != nil { if errors.Is(err, ErrUpstreamNotFound) { http.Error(w, "not found", http.StatusNotFound) @@ -189,31 +201,24 @@ func (h *ComposerHandler) handlePackageMetadata(w http.ResponseWriter, r *http.R if r.Context().Err() != nil { return // the client left while waiting on a shared rewrite } + if h.proxy.mustFilterMetadata("composer", basePackage) { + h.proxy.Logger.Error("failed to filter composer metadata", "package", basePackage, "error", err) + http.Error(w, "failed to filter package metadata", http.StatusBadGateway) + return + } h.proxy.Logger.Warn("failed to rewrite metadata, proxying original", "error", err) + markStale(w, upstream.stale) w.Header().Set(headerContentType, "application/json") _, _ = w.Write(upstream.body) return } + markStale(w, upstream.stale) serveRewrittenMetadata(w, r, rewritten) } -// rewriteMetadata rewrites dist URLs in Composer metadata to point at this proxy. -// If cooldown is enabled, versions published too recently are filtered out. -// -// The document is never decoded as a whole. Packagist serves large packages -// as minified lists of thousands of versions, and expanding them into generic -// maps took many times the document's size for every rewrite. Instead each -// version list is walked in place and the response is assembled from slices -// of the original bytes: only dist values are written fresh, and minified -// metadata stays minified. -func (h *ComposerHandler) rewriteMetadata(body []byte) ([]byte, error) { - out, _, err := h.rewriteMetadataKeeping(body) - return out, err -} - -// rewriteMetadataKeeping is rewriteMetadata that also reports the versions -// it kept, each as its package name and version. +// rewriteMetadataKeeping rewrites dist URLs and filters versions in cooldown. +// It returns the kept package names and versions without expanding minified lists. func (h *ComposerHandler) rewriteMetadataKeeping(body []byte) ([]byte, []string, error) { return h.rewriteMetadataWithLocal(body, "", nil) } @@ -396,17 +401,12 @@ func (h *ComposerHandler) shouldFilterVersion(packagePURL, packageName, version return false } - var timeStr string - if err := json.Unmarshal(published, &timeStr); err != nil { + publishedAt, ok := composerPublishTime(published) + if !ok { return false } - publishedAt, err := time.Parse(time.RFC3339, timeStr) - if err != nil { - return false - } - - if !h.proxy.Cooldown.IsAllowed("composer", packagePURL, publishedAt) { + if !h.proxy.cooldown().IsAllowed("composer", packagePURL, publishedAt) { h.proxy.Logger.Info("cooldown: filtering composer version", "package", packageName, "version", version) return true @@ -415,13 +415,25 @@ func (h *ComposerHandler) shouldFilterVersion(packagePURL, packageName, version return false } +// composerPublishTime parses the raw "time" field of a version, reporting +// false when it is missing or not an RFC 3339 string. +func composerPublishTime(published []byte) (time.Time, bool) { + var timeStr string + if err := json.Unmarshal(published, &timeStr); err != nil { + return time.Time{}, false + } + publishedAt, err := time.Parse(time.RFC3339, timeStr) + return publishedAt, err == nil +} + // disableDefaultNotification stops Composer from reporting installs of a routed // package to the default repository's notify-batch URL, which would disclose // the package name to it. Composer only falls back to notify-batch when a // version has no notification-url of its own, and skips an empty one. Setting // it on the expanded fields keeps it set for the versions that inherit them. +// Composer reads a null notification-url as absent too. func disableDefaultNotification(fields *composerFields) { - if fields.get("notification-url") == nil { + if v := fields.get("notification-url"); v == nil || string(v) == "null" { fields.set("notification-url", []byte(`"notification-url"`), []byte(`""`)) } } @@ -623,7 +635,7 @@ func (h *ComposerHandler) handleDownload(w http.ResponseWriter, r *http.Request) packageName := vendor + "/" + pkg - h.proxy.Logger.Info("composer download request", + h.proxy.Logger.Debug("composer download request", "package", packageName, "version", version, "filename", filename) local, err := h.proxy.GetLocalArtifact(r.Context(), "composer", packageName, version, filename) @@ -640,64 +652,28 @@ func (h *ComposerHandler) handleDownload(w http.ResponseWriter, r *http.Request) return } - // We need to fetch the metadata to get the actual download URL since - // Packagist URLs include a hash. Packagist serves dev versions (e.g. - // "3.x-dev", "dev-master") from a separate "~dev" metadata file, while - // tagged releases live in the regular file. Try the file most likely to - // contain this version first, then fall back to the other so that both - // stable and dev versions resolve correctly. - metaURLs := h.metadataURLsForVersion(vendor, pkg, version) - - h.proxy.Logger.Debug("resolving download URL", - "package", packageName, "version", version, - "metadata_urls", metaURLs) - - var dist composerDist - for _, metaURL := range metaURLs { - found, err := h.findDownloadURLFromMetadata(r.Context(), metaURL, packageName, version) - if err != nil { - if writeUpstreamHeld(w, err) { - return - } - h.proxy.Logger.Error("failed to fetch metadata", "error", err, "url", metaURL) - http.Error(w, "failed to fetch metadata", http.StatusBadGateway) - return - } - if found.url != "" { - dist = found - break - } - } - - if dist.url == "" { - h.proxy.Logger.Debug("version not found in any metadata source", - "package", packageName, "version", version, - "tried_urls", metaURLs) - http.Error(w, "version not found", http.StatusNotFound) - return - } - - // Lock files name archive URLs directly, so a version filtered out of the - // metadata still has to be withheld here. - if h.shouldFilterVersion(canonicalPackagePURL("composer", packageName), packageName, version, dist.published) { - http.Error(w, "version not found", http.StatusNotFound) - return - } - // The archive is cached under the file name from the path, so fetch the // one that name stands for. Compare it as sent, the way rewriteDist handed // it out, query included. requested := path.Base(r.URL.EscapedPath()) if r.URL.RawQuery != "" { requested += "?" + r.URL.RawQuery + } else if h.serveCachedRelease(w, r, packageName, version, filename) { + return } - listedURL := dist.url - downloadURL, ok := upstreamDistURL(listedURL, dist.distType, requested, isDevVersion(version)) + files := h.metadataFilesForVersion(vendor, pkg, version) + dist, downloadURL, ok := h.cachedDist(r.Context(), files, packageName, version, requested) if !ok { - h.proxy.Logger.Info("composer file not in upstream metadata", - "package", packageName, "version", version, - "filename", requested, "listed_url", listedURL) - http.Error(w, "file not found", http.StatusNotFound) + if dist, downloadURL, ok = h.upstreamDist(w, r, files, packageName, version, requested); !ok { + return + } + } + h.recordPublishTime(packageName, version, dist.published) + + // Lock files name archive URLs directly, so a version filtered out of the + // metadata still has to be withheld here. + if h.shouldFilterVersion(canonicalPackagePURL("composer", packageName), packageName, version, dist.published) { + http.Error(w, "version not found", http.StatusNotFound) return } @@ -719,7 +695,7 @@ func (h *ComposerHandler) handleDownload(w http.ResponseWriter, r *http.Request) h.discardOtherCommit(packageName, version, cacheFilename, commit) } result, err := h.proxy.GetOrFetchArtifactFromURLWithIntegrity(r.Context(), "composer", packageName, version, cacheFilename, downloadURL, - composerIntegrity(dist.shasum, version, downloadURL == listedURL)) + composerIntegrity(dist.shasum, version, downloadURL == dist.url)) if err != nil { h.proxy.serveArtifactError(w, err, "failed to fetch package") return @@ -734,6 +710,77 @@ func (h *ComposerHandler) handleDownload(w http.ResponseWriter, r *http.Request) ServeArtifactRequest(w, r, result) } +// releaseTimeStored reports whether the publish time of version is kept in +// the versions table, so a download can be checked against cooldown without +// the metadata. That holds for tagged releases of packages from the default +// repository. A branch is left out: its archive and time change with every +// push. So are routed packages, as for npm: the versions row is keyed by the +// plain PURL, which does not say which repository the version came from, so +// a time read from the default repository would be trusted for a private +// version of the same name, and the other way round. +func (h *ComposerHandler) releaseTimeStored(packageName, version string) bool { + if h.proxy.DB == nil || isDevVersion(version) { + return false + } + _, routed := h.routes.match(packageName) + return !routed +} + +// serveCachedRelease serves a tagged release's archive from the cache +// without looking up its dist in the metadata, and reports whether it wrote a +// response. The archive was only cached under its name after that name was +// checked against the metadata, and the cache verifies it against the digest +// recorded then. Cooldown is checked against the publish time recorded when +// the dist was first resolved; without one, as for an archive cached by an +// older proxy, it returns false and the caller takes the metadata path, which +// records it. Requests with a query string, which pick a commit, always take +// that path. +func (h *ComposerHandler) serveCachedRelease(w http.ResponseWriter, r *http.Request, packageName, version, filename string) bool { + if !h.releaseTimeStored(packageName, version) { + return false + } + if h.proxy.Cooldown != nil && h.proxy.Cooldown.Enabled() { + ver, err := h.proxy.DB.GetVersionByPURL(canonicalVersionPURL("composer", packageName, version)) + if err != nil || ver == nil || !ver.PublishedAt.Valid { + return false + } + if !h.proxy.cooldown().IsAllowed("composer", canonicalPackagePURL("composer", packageName), ver.PublishedAt.Time) { + h.proxy.Logger.Info("cooldown: withholding composer archive", + "package", packageName, "version", version) + http.Error(w, "version not found", http.StatusNotFound) + return true + } + } + cached, err := h.proxy.GetCachedArtifact(r.Context(), "composer", packageName, version, filename) + if err != nil { + h.proxy.serveArtifactError(w, err, "failed to read cached package") + return true + } + if cached == nil { + return false + } + ServeArtifactRequest(w, r, cached) + return true +} + +// recordPublishTime stores the publish time a release's metadata lists, for +// serveCachedRelease. It is stored whether or not cooldown is enabled, so +// enabling it later does not send cached archives back to the metadata. +func (h *ComposerHandler) recordPublishTime(packageName, version string, published []byte) { + if !h.releaseTimeStored(packageName, version) { + return + } + publishedAt, ok := composerPublishTime(published) + if !ok { + return + } + if err := h.proxy.DB.SetVersionPublishedAt(canonicalVersionPURL("composer", packageName, version), + canonicalPackagePURL("composer", packageName), publishedAt); err != nil { + h.proxy.Logger.Warn("failed to store composer publish time", + "package", packageName, "version", version, "error", err) + } +} + // discardOtherCommit clears a cached branch archive named for commit that was // fetched from another commit's URL. Proxy versions before the pinned-commit // fix cached the branch head under whatever commit a lock file asked for. The @@ -768,19 +815,98 @@ func isDevVersion(version string) bool { return strings.HasPrefix(version, "dev-") || strings.HasSuffix(version, "-dev") } -// metadataURLsForVersion returns the upstream metadata URLs to consult for a +// composerMetadataFile is one of the metadata documents a version's dist can +// be listed in: its upstream URL and the key the proxy caches it under. +type composerMetadataFile struct { + url, cacheKey string +} + +// metadataFilesForVersion returns the metadata documents to consult for a // given version, in priority order. Dev versions are served from the "~dev" // file, tagged releases from the regular file; the other file is included as a -// fallback so an unexpected classification still resolves. -func (h *ComposerHandler) metadataURLsForVersion(vendor, pkg, version string) []string { - repoURL, _ := h.sourceFor(vendor + "/" + pkg) - stable := fmt.Sprintf("%s/p2/%s/%s.json", repoURL, vendor, pkg) - dev := fmt.Sprintf("%s/p2/%s/%s~dev.json", repoURL, vendor, pkg) +// fallback so an unexpected classification still resolves. The cache keys are +// the ones handlePackageMetadata stores the documents under. +func (h *ComposerHandler) metadataFilesForVersion(vendor, pkg, version string) []composerMetadataFile { + file := func(name string) composerMetadataFile { + repoURL, cacheKey := h.sourceFor(name) + return composerMetadataFile{url: fmt.Sprintf("%s/p2/%s.json", repoURL, name), cacheKey: cacheKey} + } + stable := file(vendor + "/" + pkg) + dev := file(vendor + "/" + pkg + composerDevFile) if isDevVersion(version) { - return []string{dev, stable} + return []composerMetadataFile{dev, stable} } - return []string{stable, dev} + return []composerMetadataFile{stable, dev} +} + +// cachedDist looks up the dist of version in the metadata documents the proxy +// caches for Composer, returning it with the URL to download the requested +// file from. While the documents are fresh this costs no upstream request, +// and when upstream fails their cached copies still resolve the archive. ok is +// false when neither document lists a dist the requested file stands for, as +// for a version published after the metadata was cached, so the caller asks +// upstream instead. Without cache_metadata there is nothing to look in. +func (h *ComposerHandler) cachedDist(ctx context.Context, files []composerMetadataFile, packageName, version, requested string) (composerDist, string, bool) { + if !h.proxy.CacheMetadata || h.proxy.DB == nil { + return composerDist{}, "", false + } + for _, f := range files { + doc := h.proxy.fetchMetadataDocument(ctx, "composer", f.cacheKey, f.url, contentTypeJSON, nil) + if doc.err != nil { + continue + } + dist, err := composerDistURL(doc.body, packageName, version) + if err != nil || dist.url == "" { + continue + } + if downloadURL, ok := upstreamDistURL(dist.url, dist.distType, requested, isDevVersion(version)); ok { + return dist, downloadURL, true + } + } + return composerDist{}, "", false +} + +// upstreamDist looks up the dist of version in the metadata upstream serves +// now, returning it with the URL to download the requested file from. When it +// cannot, it writes the error response and returns false. +func (h *ComposerHandler) upstreamDist(w http.ResponseWriter, r *http.Request, files []composerMetadataFile, packageName, version, requested string) (composerDist, string, bool) { + h.proxy.Logger.Debug("resolving download URL", + "package", packageName, "version", version) + + var dist composerDist + for _, f := range files { + found, err := h.findDownloadURLFromMetadata(r.Context(), f.url, packageName, version) + if err != nil { + if writeUpstreamHeld(w, err) { + return composerDist{}, "", false + } + h.proxy.Logger.Error("failed to fetch metadata", "error", err, "url", f.url) + http.Error(w, "failed to fetch metadata", http.StatusBadGateway) + return composerDist{}, "", false + } + if found.url != "" { + dist = found + break + } + } + + if dist.url == "" { + h.proxy.Logger.Debug("version not found in any metadata source", + "package", packageName, "version", version) + http.Error(w, "version not found", http.StatusNotFound) + return composerDist{}, "", false + } + + downloadURL, ok := upstreamDistURL(dist.url, dist.distType, requested, isDevVersion(version)) + if !ok { + h.proxy.Logger.Info("composer file not in upstream metadata", + "package", packageName, "version", version, + "filename", requested, "listed_url", dist.url) + http.Error(w, "file not found", http.StatusNotFound) + return composerDist{}, "", false + } + return dist, downloadURL, true } // composerDist is what a version's metadata says about its archive: the dist @@ -792,9 +918,9 @@ type composerDist struct { } // findDownloadURLFromMetadata fetches a metadata document and returns the dist -// of the given version, with an empty URL if the version is not present. An -// error is returned only on transport failure; a missing document (non-200) -// or a missing version both yield an empty URL so the caller can fall back. +// of the given version, with an empty URL if the version is not present. A +// missing document (404 or 410) or a missing version both yield an empty URL +// so the caller can fall back; any other failure is an error. func (h *ComposerHandler) findDownloadURLFromMetadata(ctx context.Context, metaURL, packageName, version string) (composerDist, error) { h.proxy.Logger.Debug("fetching upstream metadata for download lookup", "url", metaURL, "package", packageName, "version", version) @@ -813,8 +939,16 @@ func (h *ComposerHandler) findDownloadURLFromMetadata(ctx context.Context, metaU h.proxy.Logger.Debug("upstream metadata response", "url", metaURL, "status", resp.StatusCode) - if resp.StatusCode != http.StatusOK { + switch { + case resp.StatusCode == http.StatusNotFound || resp.StatusCode == http.StatusGone: return composerDist{}, nil + case resp.StatusCode == http.StatusTooManyRequests && h.proxy.RateLimits != nil: + if err := h.proxy.RateLimits.Held(metaURL); err != nil { + return composerDist{}, err + } + } + if resp.StatusCode != http.StatusOK { + return composerDist{}, fmt.Errorf("upstream metadata returned %d", resp.StatusCode) } body, err := h.proxy.ReadMetadata(resp.Body) @@ -899,6 +1033,36 @@ func composerIntegrity(shasum, version string, listed bool) string { return sha1Checksum(shasum) } +// ComposerReleaseArchive returns the file name the Composer handler caches a +// tagged release's archive under, and the integrity it checks it against, +// given the dist the release's metadata lists. It refuses versions the +// handler only serves after reading the metadata again: branches, whose +// archive changes with every push, and archives whose URL has a query, which +// clients ask for with one. +func ComposerReleaseArchive(version, distURL, distType, shasum string) (filename, declared string, err error) { + switch { + case isDevVersion(version): + return "", "", fmt.Errorf("%s is a branch; Composer branches are fetched when requested, not mirrored", version) + case distURL == "": + return "", "", fmt.Errorf("%s has no dist archive", version) + case strings.ContainsAny(distURL, "?#"): + return "", "", fmt.Errorf("the archive URL of %s has a query, which isn't mirrored", version) + } + return distFilename(distURL, distType), composerIntegrity(shasum, version, true), nil +} + +// RecordComposerPublishTime stores the publish time of a tagged release from +// the default repository, as the Composer handler does when it resolves the +// release's dist, so the archive is served from the cache without the +// metadata, with or without cooldown. +func (p *Proxy) RecordComposerPublishTime(packageName, version string, publishedAt time.Time) error { + if p.DB == nil || isDevVersion(version) || publishedAt.IsZero() { + return nil + } + return p.DB.SetVersionPublishedAt(canonicalVersionPURL("composer", packageName, version), + canonicalPackagePURL("composer", packageName), publishedAt) +} + // proxyUpstream forwards a request to packagist.org without caching. func (h *ComposerHandler) proxyUpstream(w http.ResponseWriter, r *http.Request) { upstreamURL := h.upstreamURL + r.URL.Path diff --git a/internal/handler/composer_advisories.go b/internal/handler/composer_advisories.go new file mode 100644 index 0000000..aa0fa26 --- /dev/null +++ b/internal/handler/composer_advisories.go @@ -0,0 +1,351 @@ +package handler + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "net/url" + "strings" + "sync" + "time" + + "golang.org/x/sync/singleflight" +) + +const ( + composerAdvisoriesPath = "/api/security-advisories/" + composerFilterSummaryPath = "/lists/summary.json" + composerPackagesParam = "packages" + + // composerAdvisoriesMaxBody caps an advisories query. Composer sends at + // most 500 package names per request. + composerAdvisoriesMaxBody = 1 << 20 +) + +// composerUpstreamIndex holds the parts of the default repository's +// packages.json that the proxy advertises in its own: the security +// advisories API and the filter lists (Packagist's malware list). Composer +// reads advisories and filter entries for each package from its p2 metadata, +// which the proxy passes on unchanged, and asks these URLs for the rest. +type composerUpstreamIndex struct { + advisoriesURL string + advisoriesMetadata bool + filterLists json.RawMessage + filterSummaryURL string +} + +// composerIndexFallbackTTL is how long the upstream index is kept when the +// metadata TTL is 0. +const composerIndexFallbackTTL = time.Hour + +// composerIndexCache keeps the default repository's parsed packages.json in +// memory, whether or not metadata caching is on, so that serving the proxy's +// own packages.json does not wait on the upstream. A failed fetch is +// remembered for the same interval: the last good copy, or none, is used +// until then instead of retrying on every request. The zero value is ready +// to use. +type composerIndexCache struct { + mu sync.Mutex + index composerUpstreamIndex + ok bool + fetchedAt time.Time + group singleflight.Group + now func() time.Time // for tests; nil means time.Now +} + +func (c *composerIndexCache) clock() time.Time { + if c.now != nil { + return c.now() + } + return time.Now() +} + +// upstreamIndex returns the default repository's packages.json fields. ok is +// false when the repository has not been reached since the proxy started; a +// document without the fields yields an empty index. +func (h *ComposerHandler) upstreamIndex(ctx context.Context) (composerUpstreamIndex, bool) { + c := &h.indexCache + ttl := h.proxy.MetadataTTL + if ttl <= 0 { + ttl = composerIndexFallbackTTL + } + c.mu.Lock() + if !c.fetchedAt.IsZero() && c.clock().Sub(c.fetchedAt) < ttl { + index, ok := c.index, c.ok + c.mu.Unlock() + return index, ok + } + c.mu.Unlock() + + // One fetch serves every waiting request. It is detached from the + // request that started it, so a client hanging up neither fails the + // others nor gets remembered as an upstream failure. + _, _, _ = c.group.Do("index", func() (any, error) { + index, err := h.fetchUpstreamIndex(context.WithoutCancel(ctx)) + c.mu.Lock() + defer c.mu.Unlock() + if err == nil { + c.index, c.ok = index, true + } + c.fetchedAt = c.clock() + return nil, nil + }) + c.mu.Lock() + defer c.mu.Unlock() + return c.index, c.ok +} + +// fetchUpstreamIndex fetches and parses the default repository's +// packages.json. A document that doesn't parse is rejected before it is +// cached, so a broken response never replaces a good copy: with metadata +// caching the stored copy is used instead, and without it the error keeps +// the copy in memory. +func (h *ComposerHandler) fetchUpstreamIndex(ctx context.Context) (composerUpstreamIndex, error) { + indexURL := h.repoURL + "/packages.json" + cacheKey := hashedCacheKey(h.repoURL, "/packages.json") + validate := func(body []byte) error { + _, err := parseComposerUpstreamIndex(indexURL, body) + return err + } + res := h.proxy.fetchMetadataDocument(ctx, "composer", cacheKey, indexURL, contentTypeJSON, validate) + if res.err != nil { + h.proxy.Logger.Warn("failed to fetch upstream composer packages.json", "url", indexURL, "error", res.err) + return composerUpstreamIndex{}, res.err + } + return parseComposerUpstreamIndex(indexURL, res.body) +} + +// errComposerIndexNotObject is returned for a packages.json that is valid +// JSON but not an object, such as null. +var errComposerIndexNotObject = errors.New("composer packages.json is not a JSON object") + +// parseComposerUpstreamIndex reads the advisories and filter fields of a +// packages.json. A document without them yields an empty index; one that is +// not a JSON object, or has them in the wrong shape, is an error. +func parseComposerUpstreamIndex(indexURL string, body []byte) (composerUpstreamIndex, error) { + var doc struct { + SecurityAdvisories struct { + Metadata bool `json:"metadata"` + APIURL string `json:"api-url"` + } `json:"security-advisories"` + Filter struct { + Metadata bool `json:"metadata"` + Lists json.RawMessage `json:"lists"` + SummaryURL string `json:"summary-url"` + } `json:"filter"` + } + var index composerUpstreamIndex + if trimmed := bytes.TrimSpace(body); len(trimmed) == 0 || trimmed[0] != '{' { + return index, errComposerIndexNotObject + } + if err := json.Unmarshal(body, &doc); err != nil { + return index, fmt.Errorf("parsing composer packages.json: %w", err) + } + // Composer refuses advisories configured without an api-url unless the + // repository lists its packages, which the proxy does not. + if apiURL, ok := resolveComposerURL(indexURL, doc.SecurityAdvisories.APIURL); ok { + index.advisoriesURL = apiURL + index.advisoriesMetadata = doc.SecurityAdvisories.Metadata + } + // Composer only applies filter lists a repository marks with metadata. + // A filter api-url is not passed on: without it Composer reads the + // entries from package metadata, narrowed by the summary. + if doc.Filter.Metadata && len(doc.Filter.Lists) > 0 && doc.Filter.Lists[0] == '{' { + index.filterLists = doc.Filter.Lists + index.filterSummaryURL, _ = resolveComposerURL(indexURL, doc.Filter.SummaryURL) + } + return index, nil +} + +// resolveComposerURL resolves a URL from packages.json against the document's +// own, as Composer does, and accepts only http and https. +func resolveComposerURL(base, ref string) (string, bool) { + if ref == "" { + return "", false + } + b, err := url.Parse(base) + if err != nil { + return "", false + } + u, err := b.Parse(ref) + if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" { + return "", false + } + return u.String(), true +} + +// advertise adds the advisories and filter entries to the proxy's +// packages.json, pointing at the proxy. +func (index composerUpstreamIndex) advertise(packages map[string]any, proxyURL string) { + if index.advisoriesURL != "" { + packages["security-advisories"] = map[string]any{ + "metadata": index.advisoriesMetadata, + "api-url": proxyURL + "/composer" + composerAdvisoriesPath, + } + } + if index.filterLists != nil { + filter := map[string]any{"metadata": true, "lists": index.filterLists} + if index.filterSummaryURL != "" { + filter["summary-url"] = proxyURL + "/composer" + composerFilterSummaryPath + } + packages["filter"] = filter + } +} + +// handleSecurityAdvisories relays a security advisories query to the URL the +// default repository advertises. Composer sends the package names as +// packages[] in a POST form; a GET query is accepted too. Names served by a +// package route or a hosted-only vendor are removed first, so private package +// names are never sent to the public API. +// +// Responses are not cached: each query names a different set of packages. +func (h *ComposerHandler) handleSecurityAdvisories(w http.ResponseWriter, r *http.Request) { + query, err := h.advisoriesQuery(w, r) + if err != nil { + var maxBytesErr *http.MaxBytesError + if errors.As(err, &maxBytesErr) { + JSONError(w, http.StatusRequestEntityTooLarge, "advisories request too large") + return + } + JSONError(w, http.StatusBadRequest, "could not read advisories request") + return + } + + asked := len(query[composerPackagesParam+"[]"]) + public := h.publicPackageNames(query[composerPackagesParam+"[]"]) + if asked > 0 && len(public) == 0 { + w.Header().Set(headerContentType, contentTypeJSON) + _, _ = io.WriteString(w, `{"advisories":{}}`) + return + } + if asked > 0 { + query[composerPackagesParam+"[]"] = public + } + + index, ok := h.upstreamIndex(r.Context()) + if !ok { + JSONError(w, http.StatusBadGateway, "upstream repository unavailable") + return + } + if index.advisoriesURL == "" { + JSONError(w, http.StatusNotFound, "upstream repository has no security advisories API") + return + } + + req, err := h.advisoriesRequest(r, index.advisoriesURL, query) + if err != nil { + JSONError(w, http.StatusInternalServerError, "failed to create request") + return + } + h.proxy.Logger.Debug("composer advisories request", "packages", len(public), "withheld", asked-len(public)) + + resp, err := h.proxy.HTTPClient.Do(req) + if err != nil { + if writeUpstreamHeld(w, err) { + return + } + h.proxy.Logger.Error("composer advisories request failed", "error", err) + JSONError(w, http.StatusBadGateway, "failed to reach upstream repository") + return + } + defer func() { _ = resp.Body.Close() }() + + h.proxy.relayResponse(w, r, resp, nil) +} + +// advisoriesQuery reads the query of an advisories request, from the form +// body of a POST or the URL of a GET. Package names come back under +// "packages[]" whichever spelling the client used: PHP's http_build_query, +// which Composer uses, numbers them as packages[0], packages[1], ... +func (h *ComposerHandler) advisoriesQuery(w http.ResponseWriter, r *http.Request) (url.Values, error) { + raw := r.URL.RawQuery + if r.Method == http.MethodPost { + body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, composerAdvisoriesMaxBody)) + if err != nil { + return nil, err + } + raw = string(body) + } + values, err := url.ParseQuery(raw) + if err != nil { + return nil, err + } + query := url.Values{} + for key, vals := range values { + if key == composerPackagesParam || strings.HasPrefix(key, composerPackagesParam+"[") { + key = composerPackagesParam + "[]" + } + query[key] = append(query[key], vals...) + } + return query, nil +} + +// publicPackageNames drops the names the default repository does not serve. +func (h *ComposerHandler) publicPackageNames(names []string) []string { + public := make([]string, 0, len(names)) + for _, name := range names { + if _, routed := h.routes.match(name); routed || h.proxy.hostedOnly("composer", name) { + continue + } + public = append(public, name) + } + return public +} + +// advisoriesRequest builds the upstream request, sending the query the way +// the client did. +func (h *ComposerHandler) advisoriesRequest(r *http.Request, apiURL string, query url.Values) (*http.Request, error) { + u, err := url.Parse(apiURL) + if err != nil { + return nil, err + } + var body io.Reader + if r.Method == http.MethodPost { + body = strings.NewReader(query.Encode()) + } else { + u.RawQuery = joinQuery(u.RawQuery, query.Encode()) + } + req, err := http.NewRequestWithContext(r.Context(), r.Method, u.String(), body) + if err != nil { + return nil, err + } + if r.Method == http.MethodPost { + req.Header.Set(headerContentType, "application/x-www-form-urlencoded") + } + for _, header := range []string{headerAccept, headerAcceptEncoding} { + if v := r.Header.Get(header); v != "" { + req.Header.Set(header, v) + } + } + return req, nil +} + +func joinQuery(a, b string) string { + if a == "" || b == "" { + return a + b + } + return a + "&" + b +} + +// handleFilterSummary relays the filter list summary the default repository +// advertises. It lists every package on a filter list, so the request names +// no packages. It is not cached, so a newly listed package is blocked as soon +// as the upstream lists it; Composer revalidates its own copy with +// If-Modified-Since, which is passed on. +func (h *ComposerHandler) handleFilterSummary(w http.ResponseWriter, r *http.Request) { + index, ok := h.upstreamIndex(r.Context()) + if !ok { + JSONError(w, http.StatusBadGateway, "upstream repository unavailable") + return + } + if index.filterSummaryURL == "" { + JSONError(w, http.StatusNotFound, "upstream repository has no filter list summary") + return + } + h.proxy.ProxyUpstream(w, r, index.filterSummaryURL, + []string{headerAccept, headerAcceptEncoding, "If-Modified-Since", "If-None-Match"}) +} diff --git a/internal/handler/composer_advisories_test.go b/internal/handler/composer_advisories_test.go new file mode 100644 index 0000000..097d8cc --- /dev/null +++ b/internal/handler/composer_advisories_test.go @@ -0,0 +1,470 @@ +package handler + +import ( + "encoding/json" + "fmt" + "io" + "net/http" + "net/http/httptest" + "net/url" + "slices" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/git-pkgs/proxy/internal/database" +) + +// composerAdvisoryUpstream serves a packages.json advertising security +// advisories and a malware filter list, and records the advisories and +// summary requests it gets. +type composerAdvisoryUpstream struct { + *httptest.Server + index string + down atomic.Bool // answer every request with 503 + // malformed answers packages.json with an HTML page and status 200. + malformed atomic.Bool + + mu sync.Mutex + requests []*recordedRequest +} + +type recordedRequest struct { + method string + path string + query url.Values + body string + header http.Header +} + +const composerAdvisoriesResponse = `{"advisories":{"public/library":[{"advisoryId":"PKSA-1","affectedVersions":"<1.0.1"}]}}` + +const composerFilterSummary = `{"filter":{"malware":{"evil/package":"1.0.0"}}}` + +func newComposerAdvisoryUpstream(t *testing.T) *composerAdvisoryUpstream { + t.Helper() + u := &composerAdvisoryUpstream{} + u.Server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + body, _ := io.ReadAll(r.Body) + u.mu.Lock() + u.requests = append(u.requests, &recordedRequest{r.Method, r.URL.Path, r.URL.Query(), string(body), r.Header.Clone()}) + u.mu.Unlock() + if u.down.Load() { + w.WriteHeader(http.StatusServiceUnavailable) + return + } + w.Header().Set("Content-Type", "application/json") + switch r.URL.Path { + case "/packages.json": + if u.malformed.Load() { + w.Header().Set("Content-Type", "text/html") + _, _ = io.WriteString(w, "Service temporarily unavailable") + return + } + _, _ = io.WriteString(w, u.index) + case "/api/security-advisories/": + _, _ = io.WriteString(w, composerAdvisoriesResponse) + case "/lists/all/summary.json": + if r.Header.Get("If-Modified-Since") != "" { + w.WriteHeader(http.StatusNotModified) + return + } + _, _ = io.WriteString(w, composerFilterSummary) + default: + http.NotFound(w, r) + } + })) + // Like Packagist's: the API on one host, the summary as a relative URL. + u.index = `{ + "packages": [], + "metadata-url": "/p2/%package%.json", + "security-advisories": {"metadata": true, "api-url": "` + u.URL + `/api/security-advisories/"}, + "filter": {"metadata": true, "lists": {"malware": {"enabled": true}}, "summary-url": "/lists/all/summary.json"} + }` + t.Cleanup(u.Close) + return u +} + +// requestsTo returns the recorded requests for path. +func (u *composerAdvisoryUpstream) requestsTo(path string) []*recordedRequest { + u.mu.Lock() + defer u.mu.Unlock() + var out []*recordedRequest + for _, r := range u.requests { + if r.path == path { + out = append(out, r) + } + } + return out +} + +func newAdvisoryComposerHandler(t *testing.T, upstream *composerAdvisoryUpstream) *ComposerHandler { + t.Helper() + proxy, _, _, _ := setupTestProxy(t) + proxy.HostedEnabled = true + proxy.HostedComposerVendors = []string{"acme"} + return NewComposerHandlerWithUpstreams(proxy, "http://proxy.test", upstream.URL, upstream.URL). + WithPackageRoutes(map[string]string{"example/*": "https://packages.example.com/composer"}) +} + +func serveComposerIndex(t *testing.T, h *ComposerHandler) map[string]any { + t.Helper() + w := serveComposer(h, "/packages.json") + if w.Code != http.StatusOK { + t.Fatalf("status = %d, want 200; body: %s", w.Code, w.Body) + } + var index map[string]any + if err := json.Unmarshal(w.Body.Bytes(), &index); err != nil { + t.Fatalf("parsing packages.json: %v", err) + } + return index +} + +func TestComposerServiceIndexAdvertisesAdvisoriesAndFilter(t *testing.T) { + upstream := newComposerAdvisoryUpstream(t) + index := serveComposerIndex(t, newAdvisoryComposerHandler(t, upstream)) + + advisories, _ := index["security-advisories"].(map[string]any) + if advisories["api-url"] != "http://proxy.test/composer/api/security-advisories/" || advisories["metadata"] != true { + t.Errorf("security-advisories = %v, want the proxy's api-url with metadata", index["security-advisories"]) + } + filter, _ := index["filter"].(map[string]any) + if filter["summary-url"] != "http://proxy.test/composer/lists/summary.json" || filter["metadata"] != true { + t.Errorf("filter = %v, want the proxy's summary-url with metadata", index["filter"]) + } + lists, _ := filter["lists"].(map[string]any) + if _, ok := lists["malware"]; !ok { + t.Errorf("filter lists = %v, want upstream's malware list", filter["lists"]) + } + if index["metadata-url"] != "http://proxy.test/composer/p2/%package%.json" { + t.Errorf("metadata-url = %v, want the proxy's", index["metadata-url"]) + } +} + +func TestComposerServiceIndexWithoutUpstreamSupport(t *testing.T) { + tests := []struct { + name string + index string + }{ + {"not advertised", `{"packages": [], "metadata-url": "/p2/%package%.json"}`}, + {"advisories without api-url", `{"security-advisories": {"metadata": true}}`}, + {"filter without metadata", `{"filter": {"lists": {"malware": {"enabled": true}}, "api-url": "/filter"}}`}, + {"not json", ``}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + upstream := newComposerAdvisoryUpstream(t) + upstream.index = tt.index + index := serveComposerIndex(t, newAdvisoryComposerHandler(t, upstream)) + for _, key := range []string{"security-advisories", "filter"} { + if _, ok := index[key]; ok { + t.Errorf("%s advertised although upstream does not offer it: %v", key, index[key]) + } + } + }) + } +} + +func TestComposerServiceIndexUpstreamDown(t *testing.T) { + upstream := newComposerAdvisoryUpstream(t) + h := newAdvisoryComposerHandler(t, upstream) + upstream.Close() + + index := serveComposerIndex(t, h) + if _, ok := index["security-advisories"]; ok { + t.Errorf("security-advisories advertised without an upstream index: %v", index["security-advisories"]) + } + if index["metadata-url"] == nil { + t.Error("packages.json lacks metadata-url while the upstream is down") + } +} + +func advertisesAdvisories(index map[string]any) bool { + _, ok := index["security-advisories"] + return ok +} + +func TestComposerServiceIndexUpstreamDownNotRetried(t *testing.T) { + upstream := newComposerAdvisoryUpstream(t) + upstream.down.Store(true) + h := newAdvisoryComposerHandler(t, upstream) + + serveComposerIndex(t, h) + fetched := len(upstream.requestsTo("/packages.json")) + if fetched == 0 { + t.Fatal("first packages.json made no upstream request") + } + index := serveComposerIndex(t, h) + if got := len(upstream.requestsTo("/packages.json")); got != fetched { + t.Errorf("second packages.json made %d upstream requests, want none", got-fetched) + } + if advertisesAdvisories(index) { + t.Errorf("security-advisories advertised without an upstream index: %v", index["security-advisories"]) + } +} + +func TestComposerServiceIndexKeptInMemory(t *testing.T) { + upstream := newComposerAdvisoryUpstream(t) + h := newAdvisoryComposerHandler(t, upstream) + h.proxy.MetadataTTL = 0 + now := time.Now() + h.indexCache.now = func() time.Time { return now } + + if !advertisesAdvisories(serveComposerIndex(t, h)) { + t.Fatal("security-advisories not advertised") + } + if got := len(upstream.requestsTo("/packages.json")); got != 1 { + t.Fatalf("upstream packages.json requests = %d, want 1", got) + } + + // Within the interval the copy in memory is served without asking. + upstream.down.Store(true) + now = now.Add(composerIndexFallbackTTL - time.Minute) + if !advertisesAdvisories(serveComposerIndex(t, h)) { + t.Error("security-advisories dropped within the interval") + } + if got := len(upstream.requestsTo("/packages.json")); got != 1 { + t.Errorf("upstream packages.json requests = %d within the interval, want 1", got) + } + + // After it the index is fetched again; the failure keeps the last good + // copy and is not retried until the next interval. + now = now.Add(2 * time.Minute) + if !advertisesAdvisories(serveComposerIndex(t, h)) { + t.Error("last good copy dropped after a failed fetch") + } + fetched := len(upstream.requestsTo("/packages.json")) + if fetched < 2 { + t.Fatalf("upstream packages.json requests = %d after the interval, want a new fetch", fetched) + } + serveComposerIndex(t, h) + if got := len(upstream.requestsTo("/packages.json")); got != fetched { + t.Errorf("failed fetch retried %d times within the interval", got-fetched) + } +} + +// assertComposerSecurityAdvertised checks that h advertises the upstream's +// advisories API and malware filter, and relays both. +func assertComposerSecurityAdvertised(t *testing.T, h *ComposerHandler, when string) { + t.Helper() + index := serveComposerIndex(t, h) + if !advertisesAdvisories(index) { + t.Errorf("%s: security-advisories not advertised: %v", when, index) + } + if _, ok := index["filter"]; !ok { + t.Errorf("%s: filter not advertised: %v", when, index) + } + w := serveAdvisories(h, http.MethodPost, "/api/security-advisories/", "packages%5B%5D=public%2Flibrary") + if w.Code != http.StatusOK || w.Body.String() != composerAdvisoriesResponse { + t.Errorf("%s: advisories = %d %q, want upstream's advisories", when, w.Code, w.Body) + } + if w := serveComposer(h, "/lists/summary.json"); w.Code != http.StatusOK || w.Body.String() != composerFilterSummary { + t.Errorf("%s: filter summary = %d %q, want upstream's summary", when, w.Code, w.Body) + } +} + +// A packages.json that doesn't parse, sent with status 200, must not replace +// the last good index, with metadata caching on or off: the advisories API +// and the malware filter stay advertised and relayed. +func TestComposerServiceIndexMalformedRefreshKeepsLastGood(t *testing.T) { + for _, cacheMetadata := range []bool{false, true} { + t.Run(fmt.Sprintf("cache_metadata=%v", cacheMetadata), func(t *testing.T) { + upstream := newComposerAdvisoryUpstream(t) + h := newAdvisoryComposerHandler(t, upstream) + h.proxy.CacheMetadata = cacheMetadata + h.proxy.MetadataTTL = time.Hour + now := time.Now() + h.indexCache.now = func() time.Time { return now } + cacheKey := hashedCacheKey(upstream.URL, "/packages.json") + + assertComposerSecurityAdvertised(t, h, "before the refresh") + var stored *database.MetadataCacheEntry + if cacheMetadata { + var err error + if stored, err = h.proxy.DB.GetMetadataCache("composer", cacheKey); err != nil || stored == nil { + t.Fatalf("packages.json not cached: %v, %v", stored, err) + } + expireMetadata(t, h.proxy.DB, "composer", cacheKey) + } + + upstream.malformed.Store(true) + now = now.Add(2 * time.Hour) + fetched := len(upstream.requestsTo("/packages.json")) + assertComposerSecurityAdvertised(t, h, "after a malformed refresh") + if got := len(upstream.requestsTo("/packages.json")); got == fetched { + t.Fatal("packages.json was not fetched again after the TTL") + } + + if !cacheMetadata { + return + } + after, err := h.proxy.DB.GetMetadataCache("composer", cacheKey) + if err != nil || after == nil || after.ContentDigest != stored.ContentDigest { + t.Errorf("cached packages.json replaced by the malformed refresh: %v, %v", after, err) + } + // A fresh handler, as after a restart, has nothing in memory and + // reads the stored copy. + restarted := NewComposerHandlerWithUpstreams(h.proxy, "http://proxy.test", upstream.URL, upstream.URL) + assertComposerSecurityAdvertised(t, restarted, "after a restart") + }) + } +} + +func TestComposerServiceIndexFetchedOnce(t *testing.T) { + upstream := newComposerAdvisoryUpstream(t) + h := newAdvisoryComposerHandler(t, upstream) + + var wg sync.WaitGroup + for range 10 { + wg.Go(func() { serveComposer(h, "/packages.json") }) + } + wg.Wait() + if got := len(upstream.requestsTo("/packages.json")); got != 1 { + t.Errorf("upstream packages.json requests = %d for parallel requests, want 1", got) + } +} + +func serveAdvisories(h *ComposerHandler, method, target, body string) *httptest.ResponseRecorder { + var reader io.Reader + if body != "" { + reader = strings.NewReader(body) + } + req := httptest.NewRequest(method, target, reader) + if method == http.MethodPost { + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + } + w := httptest.NewRecorder() + h.Routes().ServeHTTP(w, req) + return w +} + +func TestComposerAdvisoriesWithholdPrivateNames(t *testing.T) { + // The form Composer sends: PHP's http_build_query numbers the entries. + form := url.Values{ + "packages[0]": {"public/library"}, + "packages[1]": {"example/private"}, + "packages[2]": {"Acme/hosted"}, + "packages[3]": {"other/library"}, + } + tests := []struct { + name, method, target, body string + }{ + {"POST form", http.MethodPost, "/api/security-advisories/", form.Encode()}, + {"GET query", http.MethodGet, "/api/security-advisories/?" + form.Encode(), ""}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + upstream := newComposerAdvisoryUpstream(t) + h := newAdvisoryComposerHandler(t, upstream) + + w := serveAdvisories(h, tt.method, tt.target, tt.body) + + if w.Code != http.StatusOK || w.Body.String() != composerAdvisoriesResponse { + t.Fatalf("got %d %q, want upstream's advisories", w.Code, w.Body) + } + sent := upstream.requestsTo("/api/security-advisories/") + if len(sent) != 1 { + t.Fatalf("upstream got %d advisories requests, want 1", len(sent)) + } + if sent[0].method != tt.method { + t.Errorf("upstream method = %s, want %s", sent[0].method, tt.method) + } + query := sent[0].query + if tt.method == http.MethodPost { + query, _ = url.ParseQuery(sent[0].body) + } + got := query["packages[]"] + slices.Sort(got) + if want := []string{"other/library", "public/library"}; !slices.Equal(got, want) { + t.Errorf("upstream was asked about %v, want only the public packages %v", got, want) + } + }) + } +} + +func TestComposerAdvisoriesOnlyPrivateNames(t *testing.T) { + upstream := newComposerAdvisoryUpstream(t) + h := newAdvisoryComposerHandler(t, upstream) + + w := serveAdvisories(h, http.MethodPost, "/api/security-advisories/", "packages%5B0%5D=example%2Fprivate") + + if w.Code != http.StatusOK || w.Body.String() != `{"advisories":{}}` { + t.Errorf("got %d %q, want an empty advisories answer", w.Code, w.Body) + } + if sent := upstream.requestsTo("/api/security-advisories/"); len(sent) != 0 { + t.Errorf("upstream was asked although every package is private: %+v", sent[0]) + } +} + +func TestComposerAdvisoriesUpdatedSince(t *testing.T) { + upstream := newComposerAdvisoryUpstream(t) + h := newAdvisoryComposerHandler(t, upstream) + + w := serveAdvisories(h, http.MethodGet, "/api/security-advisories/?updatedSince=1700000000", "") + + if w.Code != http.StatusOK { + t.Fatalf("status = %d, want 200", w.Code) + } + sent := upstream.requestsTo("/api/security-advisories/") + if len(sent) != 1 || sent[0].query.Get("updatedSince") != "1700000000" { + t.Errorf("updatedSince was not passed on: %+v", sent) + } +} + +func TestComposerAdvisoriesNotOffered(t *testing.T) { + upstream := newComposerAdvisoryUpstream(t) + upstream.index = `{"packages": []}` + h := newAdvisoryComposerHandler(t, upstream) + + if w := serveAdvisories(h, http.MethodPost, "/api/security-advisories/", "packages%5B%5D=public%2Flibrary"); w.Code != http.StatusNotFound { + t.Errorf("advisories status = %d, want 404 when upstream has no API", w.Code) + } + if w := serveComposer(h, "/lists/summary.json"); w.Code != http.StatusNotFound { + t.Errorf("summary status = %d, want 404 when upstream has no filter", w.Code) + } +} + +func TestComposerFilterSummaryRelayed(t *testing.T) { + upstream := newComposerAdvisoryUpstream(t) + h := newAdvisoryComposerHandler(t, upstream) + + w := serveComposer(h, "/lists/summary.json") + if w.Code != http.StatusOK || w.Body.String() != composerFilterSummary { + t.Fatalf("got %d %q, want upstream's summary", w.Code, w.Body) + } + + req := httptest.NewRequest(http.MethodGet, "/lists/summary.json", nil) + req.Header.Set("If-Modified-Since", "Wed, 21 Oct 2026 15:45:01 GMT") + w = httptest.NewRecorder() + h.Routes().ServeHTTP(w, req) + if w.Code != http.StatusNotModified { + t.Errorf("revalidation status = %d, want 304 passed on from upstream", w.Code) + } +} + +func TestComposerMetadataKeepsAdvisoriesAndFilter(t *testing.T) { + h := NewComposerHandler(testProxy(), "http://proxy.test") + body := []byte(`{ + "minified": "composer/2.0", + "packages": {"evil/package": [{"name": "evil/package", "version": "1.0.0", "dist": {"url": "https://example.com/evil.zip", "type": "zip"}}]}, + "security-advisories": [{"advisoryId": "PKSA-1", "affectedVersions": "<2.0.0"}], + "filter": {"malware": [{"constraint": "1.0.0", "reason": "malware", "id": "PKFE-1"}]} + }`) + + out, _, err := h.rewriteMetadataKeeping(body) + if err != nil { + t.Fatalf("rewrite: %v", err) + } + var doc map[string]json.RawMessage + if err := json.Unmarshal(out, &doc); err != nil { + t.Fatalf("parsing rewritten metadata: %v", err) + } + if !strings.Contains(string(doc["security-advisories"]), "PKSA-1") { + t.Errorf("security-advisories lost in rewrite: %s", out) + } + if !strings.Contains(string(doc["filter"]), "PKFE-1") { + t.Errorf("filter lost in rewrite: %s", out) + } +} diff --git a/internal/handler/composer_download_lookup_test.go b/internal/handler/composer_download_lookup_test.go new file mode 100644 index 0000000..53a0cfe --- /dev/null +++ b/internal/handler/composer_download_lookup_test.go @@ -0,0 +1,356 @@ +package handler + +import ( + "fmt" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/git-pkgs/cooldown" + registryclient "github.com/git-pkgs/registries/client" + "github.com/git-pkgs/registries/fetch" +) + +// composerLookupUpstream serves v/p's metadata listing versions and the +// archives they point at, counts metadata and archive requests, and fails +// every request while down is set, with downStatus or 503. A version listed in +// published carries that publish time. +type composerLookupUpstream struct { + h http.Handler + handler *ComposerHandler + proxy *Proxy + versions atomic.Value // []string + published map[string]time.Time + down atomic.Bool + downStatus atomic.Int32 + metadata atomic.Int32 + archives atomic.Int32 + routeURL string +} + +func setupComposerLookup(t *testing.T, cacheMetadata bool, versions ...string) *composerLookupUpstream { + t.Helper() + u := &composerLookupUpstream{published: map[string]time.Time{}} + u.versions.Store(versions) + var srv *httptest.Server + srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if u.down.Load() { + status := int(u.downStatus.Load()) + if status == 0 { + status = http.StatusServiceUnavailable + } + w.Header().Set("Retry-After", "30") + http.Error(w, "down", status) + return + } + switch { + case r.URL.Path == "/p2/v/p.json": + u.metadata.Add(1) + var entries []string + for _, v := range u.versions.Load().([]string) { + var published string + if at, ok := u.published[v]; ok { + published = fmt.Sprintf(`"time":%q,`, at.Format(time.RFC3339)) + } + entries = append(entries, fmt.Sprintf(`{"version":%q,%s"dist":{"url":%q,"type":"zip"}}`, v, published, srv.URL+"/archives/"+v+".zip")) + } + _, _ = fmt.Fprintf(w, `{"packages":{"v/p":[%s]}}`, strings.Join(entries, ",")) + case r.URL.Path == "/p2/v/p~dev.json": + u.metadata.Add(1) + http.NotFound(w, r) + case strings.HasPrefix(r.URL.Path, "/archives/"): + u.archives.Add(1) + _, _ = io.WriteString(w, "archive "+r.URL.Path) + default: + http.NotFound(w, r) + } + })) + t.Cleanup(srv.Close) + + proxy, _, _, _ := setupTestProxy(t) + proxy.CacheMetadata = cacheMetadata + proxy.MetadataTTL = time.Hour + fetcher := fetch.NewFetcher(fetch.WithHTTPClient(srv.Client()), fetch.WithMaxRetries(0)) + proxy.Fetcher = fetcher + t.Cleanup(func() { _ = fetcher.Close() }) + u.proxy = proxy + u.handler = NewComposerHandlerWithUpstreams(proxy, "http://proxy", srv.URL, srv.URL) + u.h = u.handler.Routes() + u.routeURL = srv.URL + return u +} + +// route sends v/p to a custom repository, which is the same server under +// another name. +func (u *composerLookupUpstream) route() { + u.h = u.handler.WithPackageRoutes(map[string]string{"v/*": u.routeURL}).Routes() +} + +func (u *composerLookupUpstream) get(t *testing.T, target string) *httptest.ResponseRecorder { + t.Helper() + w := httptest.NewRecorder() + u.h.ServeHTTP(w, httptest.NewRequest(http.MethodGet, target, nil)) + return w +} + +func (u *composerLookupUpstream) download(t *testing.T, version string) { + t.Helper() + w := u.get(t, "/files/v/p/"+version+"/"+version+".zip") + if want := "archive /archives/" + version + ".zip"; w.Code != http.StatusOK || w.Body.String() != want { + t.Fatalf("download %s: status %d, body %q, want 200 %q", version, w.Code, w.Body.String(), want) + } +} + +// TestComposerDownloadResolvesFromCachedMetadata checks that downloads find +// their archive in the metadata Composer was just served, instead of fetching +// it from upstream again for every archive. +func TestComposerDownloadResolvesFromCachedMetadata(t *testing.T) { + u := setupComposerLookup(t, true, "1.0.0") + if w := u.get(t, "/p2/v/p.json"); w.Code != http.StatusOK { + t.Fatalf("metadata: status %d", w.Code) + } + u.download(t, "1.0.0") + u.download(t, "1.0.0") + if n := u.metadata.Load(); n != 1 { + t.Errorf("upstream metadata requests = %d, want 1 (the metadata request itself)", n) + } + if n := u.archives.Load(); n != 1 { + t.Errorf("upstream archive requests = %d, want 1", n) + } +} + +// TestComposerCachedArchiveServedWhileUpstreamDown checks that a cached +// archive stays installable when upstream fails, rather than failing on the +// metadata lookup that only names where to fetch it from. +func TestComposerCachedArchiveServedWhileUpstreamDown(t *testing.T) { + u := setupComposerLookup(t, true, "1.0.0") + u.download(t, "1.0.0") + u.down.Store(true) + u.download(t, "1.0.0") +} + +// TestComposerDownloadOfVersionNewerThanCachedMetadata checks that a version +// published after the metadata was cached, which a lock file can name before +// the cached copy expires, is still looked up upstream. +func TestComposerDownloadOfVersionNewerThanCachedMetadata(t *testing.T) { + u := setupComposerLookup(t, true, "1.0.0") + u.download(t, "1.0.0") + u.versions.Store([]string{"1.0.0", "1.1.0"}) + u.download(t, "1.1.0") +} + +// TestComposerDownloadWithoutMetadataCache checks that without cache_metadata +// a download asks upstream for the metadata once, as it always has. +func TestComposerDownloadWithoutMetadataCache(t *testing.T) { + u := setupComposerLookup(t, false, "1.0.0") + u.download(t, "1.0.0") + if n := u.metadata.Load(); n != 1 { + t.Errorf("upstream metadata requests = %d, want 1", n) + } +} + +// TestComposerDownloadLookupUpstreamError checks that a download whose +// metadata lookup fails upstream answers 502, or 503 while upstream holds +// requests, and not 404: Composer treats 404 as the version being gone. +func TestComposerDownloadLookupUpstreamError(t *testing.T) { + for _, status := range []int{http.StatusInternalServerError, http.StatusServiceUnavailable} { + t.Run(http.StatusText(status), func(t *testing.T) { + u := setupComposerLookup(t, false, "1.0.0") + u.downStatus.Store(int32(status)) + u.down.Store(true) + if w := u.get(t, "/files/v/p/1.0.0/1.0.0.zip"); w.Code != http.StatusBadGateway { + t.Errorf("status = %d, want 502", w.Code) + } + }) + } + + t.Run("rate limited", func(t *testing.T) { + u := setupComposerLookup(t, false, "1.0.0") + gate := registryclient.NewRateLimitGate(http.DefaultTransport) + u.proxy.HTTPClient = &http.Client{Transport: gate} + u.proxy.RateLimits = gate + u.downStatus.Store(http.StatusTooManyRequests) + u.down.Store(true) + w := u.get(t, "/files/v/p/1.0.0/1.0.0.zip") + if w.Code != http.StatusServiceUnavailable || w.Header().Get("Retry-After") == "" { + t.Errorf("status = %d, Retry-After %q; want 503 with Retry-After", w.Code, w.Header().Get("Retry-After")) + } + }) + + t.Run("not listed", func(t *testing.T) { + u := setupComposerLookup(t, false, "1.0.0") + if w := u.get(t, "/files/v/p/2.0.0/2.0.0.zip"); w.Code != http.StatusNotFound { + t.Errorf("status = %d, want 404", w.Code) + } + }) +} + +// storedPublishTime returns the publish time recorded for v/p at version. +func (u *composerLookupUpstream) storedPublishTime(t *testing.T, version string) (time.Time, bool) { + t.Helper() + ver, err := u.proxy.DB.GetVersionByPURL(canonicalVersionPURL("composer", "v/p", version)) + if err != nil { + t.Fatalf("reading versions row: %v", err) + } + if ver == nil || !ver.PublishedAt.Valid { + return time.Time{}, false + } + return ver.PublishedAt.Time, true +} + +func (u *composerLookupUpstream) wantMetadataRequests(t *testing.T, want int32) { + t.Helper() + if n := u.metadata.Load(); n != want { + t.Errorf("upstream metadata requests = %d, want %d", n, want) + } +} + +// TestComposerCachedReleaseSkipsMetadata checks that a tagged release whose +// archive is cached is served without asking upstream for the metadata +// again, with and without cache_metadata, and with cooldown, which takes the +// publish time recorded when the archive was first resolved. +func TestComposerCachedReleaseSkipsMetadata(t *testing.T) { + for _, tt := range []struct { + name string + cacheMetadata bool + cooldown bool + }{ + {"metadata not cached", false, false}, + {"metadata cached", true, false}, + {"cooldown", false, true}, + } { + t.Run(tt.name, func(t *testing.T) { + u := setupComposerLookup(t, tt.cacheMetadata, "1.0.0") + u.published["1.0.0"] = time.Now().Add(-30 * 24 * time.Hour) + if tt.cooldown { + u.proxy.Cooldown = &cooldown.Config{Default: "3d"} + } + u.download(t, "1.0.0") + // With cache_metadata the cached copy expires; the archive must + // not need it. + u.proxy.MetadataTTL = 0 + u.download(t, "1.0.0") + u.download(t, "1.0.0") + u.wantMetadataRequests(t, 1) + if n := u.archives.Load(); n != 1 { + t.Errorf("upstream archive requests = %d, want 1", n) + } + }) + } +} + +// TestComposerDownloadStoresPublishTime checks that resolving a tagged +// release records its publish time, so later downloads can check cooldown +// without the metadata. +func TestComposerDownloadStoresPublishTime(t *testing.T) { + u := setupComposerLookup(t, false, "1.0.0") + published := time.Date(2024, 5, 6, 7, 8, 9, 0, time.UTC) + u.published["1.0.0"] = published + u.download(t, "1.0.0") + got, ok := u.storedPublishTime(t, "1.0.0") + if !ok || !got.Equal(published) { + t.Errorf("stored publish time = %v, %v, want %v", got, ok, published) + } +} + +// TestComposerCachedReleaseCooldownFromStoredTime checks that a cached +// archive whose stored publish time is still inside the cooldown window is +// withheld without the metadata, including when cooldown was enabled or +// raised after the archive was cached. +func TestComposerCachedReleaseCooldownFromStoredTime(t *testing.T) { + u := setupComposerLookup(t, false, "1.0.0", "2.0.0") + u.published["1.0.0"] = time.Now().Add(-5 * 24 * time.Hour) + u.published["2.0.0"] = time.Now().Add(-1 * time.Hour) + u.download(t, "2.0.0") + u.proxy.Cooldown = &cooldown.Config{Default: "3d"} + u.download(t, "1.0.0") + + if w := u.get(t, "/files/v/p/2.0.0/2.0.0.zip"); w.Code != http.StatusNotFound { + t.Errorf("2.0.0 after enabling cooldown: status %d, want 404", w.Code) + } + u.proxy.Cooldown = &cooldown.Config{Default: "7d"} + if w := u.get(t, "/files/v/p/1.0.0/1.0.0.zip"); w.Code != http.StatusNotFound { + t.Errorf("1.0.0 after raising cooldown: status %d, want 404", w.Code) + } + u.wantMetadataRequests(t, 2) +} + +// TestComposerCachedReleaseWithoutStoredTime checks that with cooldown a +// cached archive the proxy recorded no publish time for, such as one cached +// by an older version, is checked against the metadata, which then records +// the time. +func TestComposerCachedReleaseWithoutStoredTime(t *testing.T) { + u := setupComposerLookup(t, false, "1.0.0") + u.published["1.0.0"] = time.Now().Add(-1 * time.Hour) + u.download(t, "1.0.0") + if _, err := u.proxy.DB.Exec(`UPDATE versions SET published_at = NULL`); err != nil { + t.Fatal(err) + } + + u.proxy.Cooldown = &cooldown.Config{Default: "3d"} + if w := u.get(t, "/files/v/p/1.0.0/1.0.0.zip"); w.Code != http.StatusNotFound { + t.Errorf("status %d, want 404", w.Code) + } + u.wantMetadataRequests(t, 2) + if _, ok := u.storedPublishTime(t, "1.0.0"); !ok { + t.Error("publish time not recorded from the metadata") + } +} + +// TestComposerCachedDevVersionUsesMetadata checks that a branch, whose +// archive and publish time change with every push, is still resolved from +// the metadata on each download and records no publish time. +func TestComposerCachedDevVersionUsesMetadata(t *testing.T) { + u := setupComposerLookup(t, false, "dev-main") + u.published["dev-main"] = time.Now().Add(-30 * 24 * time.Hour) + u.download(t, "dev-main") + before := u.metadata.Load() + u.download(t, "dev-main") + if u.metadata.Load() == before { + t.Error("cached branch archive served without consulting the metadata") + } + if _, ok := u.storedPublishTime(t, "dev-main"); ok { + t.Error("publish time recorded for a branch") + } +} + +// TestComposerCachedRoutedReleaseUsesMetadata checks that a routed package +// keeps resolving every download from its route's metadata: the versions +// table is keyed by a PURL that does not say which repository the version +// came from, so it neither stores nor trusts a publish time for it. +func TestComposerCachedRoutedReleaseUsesMetadata(t *testing.T) { + u := setupComposerLookup(t, false, "1.0.0") + u.published["1.0.0"] = time.Now().Add(-1 * time.Hour) + u.route() + u.download(t, "1.0.0") + u.download(t, "1.0.0") + u.wantMetadataRequests(t, 2) + if _, ok := u.storedPublishTime(t, "1.0.0"); ok { + t.Error("publish time recorded for a routed package") + } + + // A time stored for the public package of the same name is not used. + if err := u.proxy.DB.SetVersionPublishedAt(canonicalVersionPURL("composer", "v/p", "1.0.0"), + canonicalPackagePURL("composer", "v/p"), time.Now().Add(-30*24*time.Hour)); err != nil { + t.Fatal(err) + } + u.proxy.Cooldown = &cooldown.Config{Default: "3d"} + if w := u.get(t, "/files/v/p/1.0.0/1.0.0.zip"); w.Code != http.StatusNotFound { + t.Errorf("routed release in cooldown: status %d, want 404", w.Code) + } +} + +// TestComposerCachedReleaseDenied checks that the denylist still blocks a +// cached release served without the metadata. +func TestComposerCachedReleaseDenied(t *testing.T) { + u := setupComposerLookup(t, false, "1.0.0") + u.download(t, "1.0.0") + setTestDenylist(t, u.proxy, "pkg:composer/v/p@1.0.0") + if w := u.get(t, "/files/v/p/1.0.0/1.0.0.zip"); w.Code != http.StatusForbidden { + t.Errorf("status %d, want 403", w.Code) + } +} diff --git a/internal/handler/composer_hosted.go b/internal/handler/composer_hosted.go index 9a27e6f..be8a1d6 100644 --- a/internal/handler/composer_hosted.go +++ b/internal/handler/composer_hosted.go @@ -43,6 +43,12 @@ func (h *ComposerHandler) composerLocalEntries(packageName string, dev bool) ([] manifest["name"] = packageName manifest["version"] = lv.Version manifest["time"] = lv.PushedAt.Format(time.RFC3339) + // As for routed packages, keep Composer from reporting installs of + // a private version to the default repository's notify-batch. + // Composer reads a null notification-url as absent too. + if manifest["notification-url"] == nil { + manifest["notification-url"] = "" + } manifest["dist"] = map[string]string{ "type": "zip", "url": h.localDistURL(packageName, lv.Version, lv.Filename), @@ -78,7 +84,7 @@ func pushedComposerVersion(local []composerLocalEntry, version string) bool { // upstream does not know the package, the document holds only the pushed // versions. func (h *ComposerHandler) serveMetadataWithLocal(w http.ResponseWriter, r *http.Request, packageName, upstreamURL, cacheKey string, local []composerLocalEntry) { - upstream := h.proxy.fetchMetadataDocument(r.Context(), "composer", cacheKey, upstreamURL, contentTypeJSON) + upstream := h.proxy.fetchMetadataDocument(r.Context(), "composer", cacheKey, upstreamURL, contentTypeJSON, nil) var out []byte var err error switch { @@ -99,6 +105,7 @@ func (h *ComposerHandler) serveMetadataWithLocal(w http.ResponseWriter, r *http. http.Error(w, "failed to rewrite package metadata", http.StatusBadGateway) return } + markStale(w, upstream.stale) serveRewrittenMetadata(w, r, h.proxy.uncachedRewrite("composer", h.proxyURL, cacheKey, out)) } diff --git a/internal/handler/composer_hosted_test.go b/internal/handler/composer_hosted_test.go index 048c291..dd792ca 100644 --- a/internal/handler/composer_hosted_test.go +++ b/internal/handler/composer_hosted_test.go @@ -58,11 +58,11 @@ func newComposerHostedFixture(t *testing.T, upstream map[string]string) composer func (f composerHostedFixture) push(t *testing.T, name, version, manifest string) HostedArtifact { t.Helper() - target, err := HostedTargetFor("composer", name, version) + target, err := HostedTargetFor("composer", name, version, "") if err != nil { t.Fatalf("HostedTargetFor: %v", err) } - pushed, err := f.proxy.PushLocalArtifact(context.Background(), "composer", target, bytes.NewReader(composerZip("", manifest)), "") + pushed, err := f.proxy.PushLocalArtifact(context.Background(), "composer", target, bytes.NewReader(composerZip("", manifest)), "", "") if err != nil { t.Fatalf("PushLocalArtifact: %v", err) } @@ -243,3 +243,28 @@ func TestComposerDownloadOfPushedArchiveWhileStreamingArtifacts(t *testing.T) { t.Error("a pushed archive was fetched upstream while streaming artifacts") } } + +func TestComposerPushedVersionsDisableDefaultNotification(t *testing.T) { + f := newComposerHostedFixture(t, map[string]string{"/p2/monolog/monolog.json": monologMetadata}) + f.proxy.HostedComposerVendors = []string{"acme"} + f.push(t, "monolog/monolog", "3.6.0", `{"name":"monolog/monolog"}`) + f.push(t, "acme/private", "1.0.0", `{"name":"acme/private"}`) + f.push(t, "other/private", "1.0.0", `{"name":"other/private"}`) + // Composer reads a null notification-url as absent. + f.push(t, "acme/nulled", "1.0.0", `{"name":"acme/nulled","notification-url":null}`) + f.push(t, "acme/own", "1.0.0", `{"name":"acme/own","notification-url":"https://acme.example.com/notify"}`) + + for _, tc := range []struct{ path, name, version, want string }{ + {"/p2/monolog/monolog.json", "monolog/monolog", "3.6.0", ""}, + {"/p2/acme/private.json", "acme/private", "1.0.0", ""}, + {"/p2/other/private.json", "other/private", "1.0.0", ""}, + {"/p2/acme/nulled.json", "acme/nulled", "1.0.0", ""}, + // A manifest's own URL is kept. + {"/p2/acme/own.json", "acme/own", "1.0.0", "https://acme.example.com/notify"}, + } { + v := f.versions(t, tc.path, tc.name)[tc.version] + if got, ok := v["notification-url"]; !ok || got != tc.want { + t.Errorf("%s %s notification-url = %v (set %v), want %q", tc.name, tc.version, got, ok, tc.want) + } + } +} diff --git a/internal/handler/composer_rewrite_bench_test.go b/internal/handler/composer_rewrite_bench_test.go index 1fc8c5a..075b371 100644 --- a/internal/handler/composer_rewrite_bench_test.go +++ b/internal/handler/composer_rewrite_bench_test.go @@ -56,7 +56,7 @@ func BenchmarkComposerRewriteMetadata(b *testing.B) { b.SetBytes(int64(len(body))) b.ReportAllocs() for b.Loop() { - if _, err := h.rewriteMetadata(body); err != nil { + if _, _, err := h.rewriteMetadataKeeping(body); err != nil { b.Fatal(err) } } diff --git a/internal/handler/composer_rewrite_test.go b/internal/handler/composer_rewrite_test.go index 1eb6f7f..460e38e 100644 --- a/internal/handler/composer_rewrite_test.go +++ b/internal/handler/composer_rewrite_test.go @@ -86,7 +86,7 @@ func TestComposerRewriteMetadataKeepsUpstreamBytes(t *testing.T) { input := `{"packages":{"v/p":[{"version":"1.0.0","extra":{"big":12345678901234567890,"html":"&"},` + `"dist":{"type":"zip","url":"https://example.com/abc.zip","reference":"abc"}}]},"security-advisories":[]}` - out, err := h.rewriteMetadata([]byte(input)) + out, _, err := h.rewriteMetadataKeeping([]byte(input)) if err != nil { t.Fatal(err) } @@ -107,7 +107,7 @@ func TestComposerRewriteMetadataStaysMinified(t *testing.T) { `{"version":"1.0.0","require":"__unset"}` + `]}}` - out, err := h.rewriteMetadata([]byte(input)) + out, _, err := h.rewriteMetadataKeeping([]byte(input)) if err != nil { t.Fatal(err) } @@ -136,7 +136,7 @@ func TestComposerRewriteMetadataCooldownCarriesChanges(t *testing.T) { {"version":"5.4.8","time":"` + old + `"} ]}}` - out, err := cooldownComposerHandler().rewriteMetadata([]byte(input)) + out, _, err := cooldownComposerHandler().rewriteMetadataKeeping([]byte(input)) if err != nil { t.Fatal(err) } @@ -174,7 +174,7 @@ func TestComposerRewriteMetadataCooldownAfterDevReset(t *testing.T) { {"version":"1.x-dev","time":"` + old + `"} ]}}` - out, err := cooldownComposerHandler().rewriteMetadata([]byte(input)) + out, _, err := cooldownComposerHandler().rewriteMetadataKeeping([]byte(input)) if err != nil { t.Fatal(err) } @@ -196,7 +196,7 @@ func TestComposerRewriteMetadataCooldownAfterDevReset(t *testing.T) { func TestComposerRewriteMetadataInvalidJSON(t *testing.T) { h := &ComposerHandler{proxy: testProxy(), proxyURL: "http://proxy"} - if _, err := h.rewriteMetadata([]byte(`{"packages":{"v/p":[{"version":"1.0.0"}]}`)); err == nil { + if _, _, err := h.rewriteMetadataKeeping([]byte(`{"packages":{"v/p":[{"version":"1.0.0"}]}`)); err == nil { t.Error("expected an error for truncated JSON") } } @@ -204,7 +204,7 @@ func TestComposerRewriteMetadataInvalidJSON(t *testing.T) { func TestComposerRewriteMetadataWithoutPackages(t *testing.T) { h := &ComposerHandler{proxy: testProxy(), proxyURL: "http://proxy"} for _, input := range []string{`{"other":1}`, `{"packages":[]}`} { - out, err := h.rewriteMetadata([]byte(input)) + out, _, err := h.rewriteMetadataKeeping([]byte(input)) if err != nil { t.Fatalf("%s: %v", input, err) } @@ -266,7 +266,7 @@ func TestComposerRewriteMetadataRewritesEveryPackage(t *testing.T) { "v/b":[{"version":"2.0.0","dist":{"url":"https://example.com/b.zip","type":"zip"}}], "v/c":"not a list" }}` - out, err := h.rewriteMetadata([]byte(input)) + out, _, err := h.rewriteMetadataKeeping([]byte(input)) if err != nil { t.Fatal(err) } diff --git a/internal/handler/composer_routes_test.go b/internal/handler/composer_routes_test.go index 5a65440..0ebf5ac 100644 --- a/internal/handler/composer_routes_test.go +++ b/internal/handler/composer_routes_test.go @@ -235,13 +235,16 @@ func TestComposerRoutedDownloadIgnoresDefaultRepositoryArtifact(t *testing.T) { // TestComposerRoutedMinifiedMetadataDisablesNotification checks that every // version of a routed package, as Composer expands minified metadata, has an // empty notification-url: versions that inherit their fields, versions after a -// ~dev reset, and versions after one that set its own URL and then unset it. +// ~dev reset, versions after one that set its own URL and then unset it, and +// versions with a null URL. func TestComposerRoutedMinifiedMetadataDisablesNotification(t *testing.T) { minified := `{"minified":"composer/2.0","packages":{"example/library":[` + `{"name":"example/library","version":"1.0.0","dist":{"url":"https://private.example.com/a/1.0.0.zip","type":"zip"}},` + `{"version":"1.1.0","dist":{"url":"https://private.example.com/a/1.1.0.zip","type":"zip"}},` + `{"version":"1.2.0","notification-url":"https://private.example.com/notify","dist":{"url":"https://private.example.com/a/1.2.0.zip","type":"zip"}},` + `{"version":"1.3.0","notification-url":"__unset","dist":{"url":"https://private.example.com/a/1.3.0.zip","type":"zip"}},` + + `{"version":"1.4.0","notification-url":null,"dist":{"url":"https://private.example.com/a/1.4.0.zip","type":"zip"}},` + + `{"version":"1.5.0","dist":{"url":"https://private.example.com/a/1.5.0.zip","type":"zip"}},` + `"~dev",` + `{"name":"example/library","version":"dev-main","dist":{"url":"https://private.example.com/a/main.zip","type":"zip"}}]}}` public := newComposerUpstream(t, map[string]string{}, http.StatusOK) @@ -258,6 +261,8 @@ func TestComposerRoutedMinifiedMetadataDisablesNotification(t *testing.T) { "1.1.0": "", "1.2.0": "https://private.example.com/notify", // the route's own URL is kept "1.3.0": "", + "1.4.0": "", // Composer reads null as absent + "1.5.0": "", "dev-main": "", } versions := composerVersions(t, w.Body.Bytes(), "example/library") diff --git a/internal/handler/composer_test.go b/internal/handler/composer_test.go index e6a9962..a964dfc 100644 --- a/internal/handler/composer_test.go +++ b/internal/handler/composer_test.go @@ -38,7 +38,7 @@ func TestComposerRewriteMetadata(t *testing.T) { } }` - output, err := h.rewriteMetadata([]byte(input)) + output, _, err := h.rewriteMetadataKeeping([]byte(input)) if err != nil { t.Fatalf("rewriteMetadata failed: %v", err) } @@ -93,7 +93,7 @@ func TestComposerRewriteMetadataMinifiedInheritance(t *testing.T) { } }` - output, err := h.rewriteMetadata([]byte(input)) + output, _, err := h.rewriteMetadataKeeping([]byte(input)) if err != nil { t.Fatalf("rewriteMetadata failed: %v", err) } @@ -153,7 +153,7 @@ func TestComposerRewriteMetadataMinifiedDevReset(t *testing.T) { } }` - output, err := h.rewriteMetadata([]byte(input)) + output, _, err := h.rewriteMetadataKeeping([]byte(input)) if err != nil { t.Fatalf("rewriteMetadata failed: %v", err) } @@ -214,7 +214,7 @@ func TestComposerRewriteMetadataUnset(t *testing.T) { } }` - output, err := h.rewriteMetadata([]byte(input)) + output, _, err := h.rewriteMetadataKeeping([]byte(input)) if err != nil { t.Fatalf("rewriteMetadata failed: %v", err) } @@ -288,7 +288,7 @@ func TestComposerRewriteMetadataCooldownPreservesNames(t *testing.T) { } }` - output, err := h.rewriteMetadata([]byte(input)) + output, _, err := h.rewriteMetadataKeeping([]byte(input)) if err != nil { t.Fatalf("rewriteMetadata failed: %v", err) } @@ -352,7 +352,7 @@ func TestComposerRewriteMetadataGitHubZipballFilenames(t *testing.T) { } }` - output, err := h.rewriteMetadata([]byte(input)) + output, _, err := h.rewriteMetadataKeeping([]byte(input)) if err != nil { t.Fatalf("rewriteMetadata failed: %v", err) } @@ -405,7 +405,7 @@ func TestComposerExpandMinifiedSharedDistReferences(t *testing.T) { } }` - output, err := h.rewriteMetadata([]byte(input)) + output, _, err := h.rewriteMetadataKeeping([]byte(input)) if err != nil { t.Fatalf("rewriteMetadata failed: %v", err) } @@ -505,16 +505,16 @@ func TestComposerDownloadDevVersionUsesDevMetadata(t *testing.T) { // FIXED behavior: the handler consults the ~dev file (it is first in the // candidate list for dev versions) and resolves the dist URL. - urls := h.metadataURLsForVersion(vendor, name, version) - if len(urls) == 0 || !strings.HasSuffix(urls[0], "/p2/phpmd/phpmd~dev.json") { - t.Fatalf("dev version should consult the ~dev metadata file first, got %v", urls) + files := h.metadataFilesForVersion(vendor, name, version) + if len(files) == 0 || !strings.HasSuffix(files[0].url, "/p2/phpmd/phpmd~dev.json") || files[0].cacheKey != "phpmd/phpmd~dev" { + t.Fatalf("dev version should consult the ~dev metadata file first, got %v", files) } var resolved string - for _, u := range urls { - found, err := h.findDownloadURLFromMetadata(ctx, u, pkg, version) + for _, f := range files { + found, err := h.findDownloadURLFromMetadata(ctx, f.url, pkg, version) if err != nil { - t.Fatalf("unexpected error fetching metadata %q: %v", u, err) + t.Fatalf("unexpected error fetching metadata %q: %v", f.url, err) } resolved = found.url if resolved != "" { @@ -959,7 +959,7 @@ func TestComposerRewriteMetadataCooldown(t *testing.T) { } }` - output, err := h.rewriteMetadata([]byte(input)) + output, _, err := h.rewriteMetadataKeeping([]byte(input)) if err != nil { t.Fatalf("rewriteMetadata failed: %v", err) } diff --git a/internal/handler/conan.go b/internal/handler/conan.go index 9bb4401..dddd79f 100644 --- a/internal/handler/conan.go +++ b/internal/handler/conan.go @@ -162,48 +162,10 @@ func (h *ConanHandler) shouldCacheFile(filename string) bool { // proxyCached forwards a request with metadata caching. func (h *ConanHandler) proxyCached(w http.ResponseWriter, r *http.Request) { - cacheKey := strings.TrimPrefix(r.URL.Path, "/") - cacheKey = strings.ReplaceAll(cacheKey, "/", "_") - if r.URL.RawQuery != "" { - cacheKey += "_" + r.URL.RawQuery - } + cacheKey := hashedCacheKey(h.upstreamURL, r.URL.Path, r.URL.RawQuery) upstreamURL := h.upstreamURL + r.URL.Path if r.URL.RawQuery != "" { upstreamURL += "?" + r.URL.RawQuery } h.proxy.ProxyCached(w, r, upstreamURL, "conan", cacheKey, "*/*") } - -// proxyUpstream forwards a request to conan center without caching. -func (h *ConanHandler) proxyUpstream(w http.ResponseWriter, r *http.Request) { - upstreamURL := h.upstreamURL + r.URL.Path - if r.URL.RawQuery != "" { - upstreamURL += "?" + r.URL.RawQuery - } - - h.proxy.Logger.Debug("proxying to upstream", "url", upstreamURL) - - req, err := http.NewRequestWithContext(r.Context(), http.MethodGet, upstreamURL, nil) - if err != nil { - http.Error(w, "failed to create request", http.StatusInternalServerError) - return - } - - // Copy authorization header for authenticated requests - if auth := r.Header.Get("Authorization"); auth != "" { - req.Header.Set("Authorization", auth) - } - - resp, err := h.proxy.HTTPClient.Do(req) - if err != nil { - if writeUpstreamHeld(w, err) { - return - } - h.proxy.Logger.Error("upstream request failed", "error", err) - http.Error(w, "upstream request failed", http.StatusBadGateway) - return - } - defer func() { _ = resp.Body.Close() }() - - h.proxy.relayResponse(w, r, resp, nil) -} diff --git a/internal/handler/conan_test.go b/internal/handler/conan_test.go index f2fb909..cf8038e 100644 --- a/internal/handler/conan_test.go +++ b/internal/handler/conan_test.go @@ -94,8 +94,10 @@ func TestConanPingV2(t *testing.T) { } } -func TestConanProxyUpstream(t *testing.T) { +func TestConanMetadata(t *testing.T) { + var requests atomic.Int32 upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + requests.Add(1) if r.URL.Path != "/v2/conans/search" { w.WriteHeader(http.StatusNotFound) return @@ -110,27 +112,26 @@ func TestConanProxyUpstream(t *testing.T) { })) defer upstream.Close() - h := &ConanHandler{ - proxy: conanTestProxy(), - upstreamURL: upstream.URL, - proxyURL: "http://proxy.local", + proxy, _, _, _ := setupTestProxy(t) + proxy.CacheMetadata = true + proxy.MetadataTTL = time.Hour + proxy.HTTPClient = upstream.Client() + h := NewConanHandlerWithUpstream(proxy, "http://proxy.local", upstream.URL) + routes := h.Routes() + for range 2 { + req := httptest.NewRequest(http.MethodGet, "/v2/conans/search?q=zlib", nil) + w := httptest.NewRecorder() + routes.ServeHTTP(w, req) + if w.Code != http.StatusOK || w.Body.String() != `{"results":["zlib/1.2.13"]}` { + t.Fatalf("response = %d %q", w.Code, w.Body.String()) + } } - - req := httptest.NewRequest(http.MethodGet, "/v2/conans/search?q=zlib", nil) - w := httptest.NewRecorder() - h.proxyUpstream(w, req) - - if w.Code != http.StatusOK { - t.Errorf("status = %d, want %d", w.Code, http.StatusOK) - } - - body := w.Body.String() - if !strings.Contains(body, "zlib/1.2.13") { - t.Errorf("response body does not contain expected result: %s", body) + if got := requests.Load(); got != 1 { + t.Errorf("upstream requests = %d, want 1", got) } } -func TestConanProxyUpstreamNotFound(t *testing.T) { +func TestConanMetadataNotFound(t *testing.T) { upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusNotFound) })) @@ -144,16 +145,16 @@ func TestConanProxyUpstreamNotFound(t *testing.T) { req := httptest.NewRequest(http.MethodGet, "/v2/conans/nonexistent", nil) w := httptest.NewRecorder() - h.proxyUpstream(w, req) + h.Routes().ServeHTTP(w, req) if w.Code != http.StatusNotFound { t.Errorf("status = %d, want %d", w.Code, http.StatusNotFound) } } -func TestConanProxyUpstreamCopiesHeaders(t *testing.T) { +func TestConanMetadataCopiesHeaders(t *testing.T) { upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("X-Custom-Header", "test-value") + w.Header().Set("ETag", `"metadata"`) w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusOK) _, _ = w.Write([]byte(`{}`)) @@ -168,17 +169,17 @@ func TestConanProxyUpstreamCopiesHeaders(t *testing.T) { req := httptest.NewRequest(http.MethodGet, "/v2/conans/test", nil) w := httptest.NewRecorder() - h.proxyUpstream(w, req) + h.Routes().ServeHTTP(w, req) - if w.Header().Get("X-Custom-Header") != "test-value" { - t.Errorf("X-Custom-Header = %q, want %q", w.Header().Get("X-Custom-Header"), "test-value") + if w.Header().Get("ETag") != `"metadata"` { + t.Errorf("ETag = %q, want %q", w.Header().Get("ETag"), `"metadata"`) } } -func TestConanProxyUpstreamForwardsAuthHeader(t *testing.T) { +func TestConanMetadataDoesNotForwardClientAuth(t *testing.T) { upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { auth := r.Header.Get("Authorization") - if auth != "Bearer mytoken" { + if auth != "" { w.WriteHeader(http.StatusUnauthorized) return } @@ -196,14 +197,14 @@ func TestConanProxyUpstreamForwardsAuthHeader(t *testing.T) { req := httptest.NewRequest(http.MethodGet, "/v2/conans/test", nil) req.Header.Set("Authorization", "Bearer mytoken") w := httptest.NewRecorder() - h.proxyUpstream(w, req) + h.Routes().ServeHTTP(w, req) if w.Code != http.StatusOK { t.Errorf("status = %d, want %d", w.Code, http.StatusOK) } } -func TestConanProxyUpstreamBadUpstream(t *testing.T) { +func TestConanMetadataBadUpstream(t *testing.T) { h := &ConanHandler{ proxy: conanTestProxy(), upstreamURL: "http://127.0.0.1:1", // unreachable @@ -212,7 +213,7 @@ func TestConanProxyUpstreamBadUpstream(t *testing.T) { req := httptest.NewRequest(http.MethodGet, "/v2/conans/test", nil) w := httptest.NewRecorder() - h.proxyUpstream(w, req) + h.Routes().ServeHTTP(w, req) if w.Code != http.StatusBadGateway { t.Errorf("status = %d, want %d", w.Code, http.StatusBadGateway) @@ -487,9 +488,9 @@ func TestConanRoutes(t *testing.T) { } } -func TestConanProxyUpstreamPreservesQueryString(t *testing.T) { +func TestConanMetadataPreservesQueryString(t *testing.T) { upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if r.URL.Query().Get("q") != "boost" && r.URL.Query().Get("page") != "2" { + if r.URL.Query().Get("q") != "boost" || r.URL.Query().Get("page") != "2" { w.WriteHeader(http.StatusBadRequest) return } @@ -506,14 +507,14 @@ func TestConanProxyUpstreamPreservesQueryString(t *testing.T) { req := httptest.NewRequest(http.MethodGet, "/v2/conans/search?q=boost&page=2", nil) w := httptest.NewRecorder() - h.proxyUpstream(w, req) + h.Routes().ServeHTTP(w, req) if w.Code != http.StatusOK { t.Errorf("status = %d, want %d", w.Code, http.StatusOK) } } -func TestConanProxyUpstreamLargeResponse(t *testing.T) { +func TestConanMetadataLargeResponse(t *testing.T) { largeBody := strings.Repeat("x", 1024*1024) upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) @@ -529,7 +530,7 @@ func TestConanProxyUpstreamLargeResponse(t *testing.T) { req := httptest.NewRequest(http.MethodGet, "/v2/conans/test", nil) w := httptest.NewRecorder() - h.proxyUpstream(w, req) + h.Routes().ServeHTTP(w, req) if w.Code != http.StatusOK { t.Errorf("status = %d, want %d", w.Code, http.StatusOK) @@ -564,7 +565,7 @@ func TestNewConanHandlerNoTrailingSlash(t *testing.T) { } } -func TestConanProxyUpstreamNoAuthHeaderWhenNotProvided(t *testing.T) { +func TestConanMetadataNoAuthHeaderWhenNotProvided(t *testing.T) { upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { auth := r.Header.Get("Authorization") if auth != "" { @@ -584,14 +585,14 @@ func TestConanProxyUpstreamNoAuthHeaderWhenNotProvided(t *testing.T) { req := httptest.NewRequest(http.MethodGet, "/v2/conans/test", nil) w := httptest.NewRecorder() - h.proxyUpstream(w, req) + h.Routes().ServeHTTP(w, req) if w.Code != http.StatusOK { t.Errorf("status = %d, want %d", w.Code, http.StatusOK) } } -func TestConanProxyUpstreamCopiesBody(t *testing.T) { +func TestConanMetadataCopiesBody(t *testing.T) { expected := `{"name":"zlib","version":"1.2.13","user":"_","channel":"_"}` upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") @@ -608,7 +609,7 @@ func TestConanProxyUpstreamCopiesBody(t *testing.T) { req := httptest.NewRequest(http.MethodGet, "/v2/conans/zlib/1.2.13/_/_/latest", nil) w := httptest.NewRecorder() - h.proxyUpstream(w, req) + h.Routes().ServeHTTP(w, req) if w.Code != http.StatusOK { t.Errorf("status = %d, want %d", w.Code, http.StatusOK) @@ -620,7 +621,7 @@ func TestConanProxyUpstreamCopiesBody(t *testing.T) { } } -func TestConanProxyUpstreamPreservesStatusCodes(t *testing.T) { +func TestConanMetadataPreservesStatusCodes(t *testing.T) { codes := []int{ http.StatusOK, http.StatusNotFound, @@ -641,7 +642,7 @@ func TestConanProxyUpstreamPreservesStatusCodes(t *testing.T) { req := httptest.NewRequest(http.MethodGet, "/v2/test", nil) w := httptest.NewRecorder() - h.proxyUpstream(w, req) + h.Routes().ServeHTTP(w, req) if w.Code != code { t.Errorf("status = %d, want %d", w.Code, code) diff --git a/internal/handler/conda.go b/internal/handler/conda.go index d7b8b3f..c9db7a7 100644 --- a/internal/handler/conda.go +++ b/internal/handler/conda.go @@ -1,14 +1,23 @@ package handler import ( + "bufio" + "bytes" "compress/gzip" + "crypto/sha256" + "encoding/hex" "encoding/json" + "errors" + "fmt" + "hash" "io" "net/http" "slices" "strings" + "sync" "time" + "github.com/git-pkgs/proxy/internal/jsonstream" "github.com/git-pkgs/proxy/internal/retention" "github.com/git-pkgs/purl" ) @@ -53,6 +62,11 @@ type CondaHandler struct { proxy *Proxy upstreamURL string proxyURL string + + // repodataStates holds, per metadata cache key, what is known of the + // last filtered copy of a repodata document. Guarded by repodataMu. + repodataMu sync.Mutex + repodataStates map[string]repodataState } // NewCondaHandler creates a new Conda protocol handler. @@ -77,8 +91,14 @@ func (h *CondaHandler) Routes() http.Handler { // Channel index (repodata) mux.HandleFunc("GET /{channel}/{arch}/repodata.json", h.handleRepodata) - mux.HandleFunc("GET /{channel}/{arch}/repodata.json.bz2", h.proxyCached) + mux.HandleFunc("GET /{channel}/{arch}/repodata.json.bz2", h.handleRepodataVariant) mux.HandleFunc("GET /{channel}/{arch}/current_repodata.json", h.handleRepodata) + mux.HandleFunc("GET /{channel}/{arch}/repodata_from_packages.json", h.handleRepodata) + + // Sharded repodata (CEP 16) + mux.HandleFunc("GET /{channel}/{arch}/"+condaShardIndexFile, h.handleShardIndex) + mux.HandleFunc("GET /{channel}/{arch}/shards/{filename}", h.handleShard) + mux.HandleFunc("GET /{channel}/{arch}/"+condaCooldownShardDir+"/{bucket}/{rest...}", h.handleCooldownShard) // Package downloads (cache these) mux.HandleFunc("GET /{channel}/{arch}/{filename}", h.handleDownload) @@ -92,8 +112,17 @@ func (h *CondaHandler) handleDownload(w http.ResponseWriter, r *http.Request) { arch := r.PathValue("arch") filename := r.PathValue("filename") + if strings.HasSuffix(filename, condaShardSuffix) { + h.handleShard(w, r) + return + } + // Only cache actual package files if !h.isPackageFile(filename) { + if isCondaRepodataVariant(filename) && h.cooldownEnabled() { + refuseUnfilteredRepodata(w) + return + } h.proxyUpstream(w, r) return } @@ -107,12 +136,25 @@ func (h *CondaHandler) handleDownload(w http.ResponseWriter, r *http.Request) { // Include channel in package name packageName := channel + "/" + name - h.proxy.Logger.Info("conda download request", + h.proxy.Logger.Debug("conda download request", "channel", channel, "arch", arch, "name", name, "version", version) - upstreamURL := h.upstreamURL + r.URL.Path + // Builds and subdirs of one version each have their own timestamp, so + // the check is per file and keeps no time in the shared versions row. + // Subdirs distinguish cached files with the same filename. + cacheFilename := arch + "/" + filename + if h.proxy.withholdInCooldown(w, r, downloadVersion{ + ecosystem: "conda", policyName: name, version: version, cacheName: packageName, filename: cacheFilename, + lookup: func() (time.Time, bool, bool, error) { + published, ok, err := h.publishTime(r, channel, arch, filename) + return published, ok, false, err + }, + }) { + return + } - result, err := h.proxy.GetOrFetchArtifactFromURL(r.Context(), "conda", packageName, version, filename, upstreamURL) + upstreamURL := h.upstreamURL + r.URL.Path + result, err := h.proxy.GetOrFetchArtifactFromURL(r.Context(), "conda", packageName, version, cacheFilename, upstreamURL) if err != nil { h.proxy.serveArtifactError(w, err, "failed to fetch package") return @@ -127,9 +169,15 @@ func (h *CondaHandler) isPackageFile(filename string) bool { } // parseFilename extracts name and version from a Conda package filename. +func (h *CondaHandler) parseFilename(filename string) (name, version string) { + return CondaFilenameIdentity(filename) +} + +// CondaFilenameIdentity returns the name and version a download of filename +// is cached under, or empty strings when it is not a package file name. // Conda filenames are: {name}-{version}-{build}.{ext} // e.g., "numpy-1.24.0-py311h64a7726_0.conda" -func (h *CondaHandler) parseFilename(filename string) (name, version string) { +func CondaFilenameIdentity(filename string) (name, version string) { // Remove extension base := filename for _, ext := range []string{".conda", ".tar.bz2"} { @@ -163,15 +211,90 @@ func (h *CondaHandler) parseFilename(filename string) (name, version string) { return name, version } +// isCondaRepodataVariant reports whether filename is a form of a subdir's +// repodata other than the plain JSON documents the proxy filters, such as +// repodata.json.zst, repodata.json.bz2 or repodata.jlap patches. Package +// files are told apart by the caller. +func isCondaRepodataVariant(filename string) bool { + return strings.HasPrefix(filename, "repodata") || strings.HasPrefix(filename, "current_repodata") +} + +// handleRepodataVariant serves repodata.json.bz2 from the metadata cache, +// unless cooldown is on: the proxy filters only the JSON, so a compressed +// copy would list versions still in cooldown. +func (h *CondaHandler) handleRepodataVariant(w http.ResponseWriter, r *http.Request) { + if h.cooldownEnabled() { + refuseUnfilteredRepodata(w) + return + } + h.proxyCached(w, r) +} + +// refuseUnfilteredRepodata answers 404 for a repodata variant the proxy +// can't filter. conda and mamba then fall back to repodata.json. +func refuseUnfilteredRepodata(w http.ResponseWriter) { + http.Error(w, "only repodata.json is served while cooldown is enabled", http.StatusNotFound) +} + // handleRepodata proxies repodata.json, applying cooldown filtering when enabled. +// +// With cache_metadata the document is read through the metadata cache, as +// without cooldown, so within metadata_ttl it is filtered from storage +// without asking upstream, and after it revalidated with its ETag. A stored +// copy is streamed through the filter rather than read into memory; a +// document just fetched is held compressed, as the metadata cache holds every +// document it fetches. The decompressed document, hundreds of MB for +// conda-forge, is never held whole. func (h *CondaHandler) handleRepodata(w http.ResponseWriter, r *http.Request) { - if h.proxy.Cooldown == nil || !h.proxy.Cooldown.Enabled() { + if !h.cooldownEnabled() { h.proxyCached(w, r) return } upstreamURL := h.upstreamURL + r.URL.Path + p := h.proxy + if !p.CacheMetadata || p.DB == nil || p.Storage == nil { + h.streamRepodata(w, r, upstreamURL) + return + } + cacheKey := h.metadataCacheKey(r.URL.Path) + now := time.Now() + if entry := p.freshMetadataEntry("conda", cacheKey); entry != nil { + if body, err := p.openMetadataEntry(r.Context(), "conda", cacheKey, entry); err == nil { + defer func() { _ = body.Close() }() + p.recordStreamedMetadataHit("conda", entry) + digest := entry.ContentDigest.String + if !h.repodataNotModified(w, r, cacheKey, digest, now) { + h.writeFilteredRepodata(w, upstreamURL, cacheKey, digest, body, entry.ContentEncoding.String, now) + } + return + } + } + + // The same key and encoding as proxyCached, so with and without cooldown + // the proxy keeps one copy of the document. + res := p.lookupMetadata(r.Context(), "conda", cacheKey, upstreamURL, "*/*", "gzip", nil) + if errors.Is(res.err, ErrMetadataTooLarge) { + // Too large to cache even compressed: stream it as without the cache. + p.Logger.Warn("conda repodata exceeds the metadata size limit, streaming it uncached", "url", upstreamURL) + h.streamRepodata(w, r, upstreamURL) + return + } + if res.err != nil { + p.writeMetadataFetchError(w, res.err) + return + } + markStale(w, res.stale) + if h.repodataNotModified(w, r, cacheKey, res.digest, now) { + return + } + h.writeFilteredRepodata(w, upstreamURL, cacheKey, res.digest, bytes.NewReader(res.body), res.contentEncoding, now) +} + +// streamRepodata filters repodata.json as it streams from upstream, without +// the metadata cache. +func (h *CondaHandler) streamRepodata(w http.ResponseWriter, r *http.Request, upstreamURL string) { h.proxy.Logger.Debug("fetching repodata for cooldown filtering", "url", upstreamURL) req, err := http.NewRequestWithContext(r.Context(), http.MethodGet, upstreamURL, nil) @@ -197,11 +320,21 @@ func (h *CondaHandler) handleRepodata(w http.ResponseWriter, r *http.Request) { return } - // Explicitly requesting gzip disables the transport's automatic decoding. + // Explicitly requesting gzip disables the transport's automatic decoding, + // so writeFilteredRepodata decodes it. + h.writeFilteredRepodata(w, upstreamURL, "", "", resp.Body, resp.Header.Get(headerContentEncoding), time.Now()) +} + +// writeFilteredRepodata writes repodata.json from src, decoded by +// contentEncoding, without the entries in cooldown at now. digest identifies +// the document in the metadata cache under cacheKey, and is empty when it +// isn't cached; when known, the ETag of the filtered copy is remembered for +// the next request. +func (h *CondaHandler) writeFilteredRepodata(w http.ResponseWriter, upstreamURL, cacheKey, digest string, src io.Reader, contentEncoding string, now time.Time) { // Cooldown needs JSON, so decode here and bound the decompressed size too. - var reader io.Reader = resp.Body - if strings.EqualFold(strings.TrimSpace(resp.Header.Get(headerContentEncoding)), "gzip") { - decoded, err := gzip.NewReader(resp.Body) + reader := src + if strings.EqualFold(strings.TrimSpace(contentEncoding), "gzip") { + decoded, err := gzip.NewReader(src) if err != nil { http.Error(w, "failed to decode response", http.StatusBadGateway) return @@ -209,81 +342,308 @@ func (h *CondaHandler) handleRepodata(w http.ResponseWriter, r *http.Request) { defer func() { _ = decoded.Close() }() reader = decoded } - body, err := h.proxy.ReadMetadata(reader) - if err != nil { - http.Error(w, "failed to read response", http.StatusBadGateway) - return - } - - filtered, err := h.applyCooldownFiltering(body) - if err != nil { - h.proxy.Logger.Warn("failed to filter repodata, proxying original", "error", err) - w.Header().Set(headerContentType, "application/json") - _, _ = w.Write(body) - return - } - + // conda-forge's linux-64 repodata.json is several hundred MB, so it is + // filtered as it streams rather than read through ReadMetadata. Once + // output has started, an error aborts the response so the client never + // takes a truncated or unfiltered index as complete. + out := &countingWriter{w: w} + buffered := bufio.NewWriterSize(out, repodataWriteBuffer) w.Header().Set(headerContentType, "application/json") - _, _ = w.Write(filtered) + filter := h.newRepodataFilter(now) + err := h.filterRepodataWith(io.LimitReader(reader, maxRepodataSize), buffered, filter) + if err == nil { + err = buffered.Flush() + } + if err != nil { + h.proxy.Logger.Error("failed to filter conda repodata", "url", upstreamURL, "error", err) + if out.n == 0 { + http.Error(w, "failed to read response", http.StatusBadGateway) + return + } + panic(http.ErrAbortHandler) + } + if digest != "" { + h.rememberRepodata(cacheKey, digest, filter) + } } -// condaTimestampDivisor converts Conda's millisecond timestamps to seconds. -const condaTimestampDivisor = 1000 +// repodataState is what the proxy remembers of the last filtered copy of a +// cached repodata document: which document it was made from, its ETag, and +// until when filtering that document again gives the same copy. +type repodataState struct { + digest string + etag string + // until is when the first entry left out leaves cooldown, or zero when + // none was left out. + until time.Time +} -// applyCooldownFiltering removes entries from repodata.json that were -// published too recently based on their timestamp field. -func (h *CondaHandler) applyCooldownFiltering(body []byte) ([]byte, error) { - if h.proxy.Cooldown == nil || !h.proxy.Cooldown.Enabled() { - return body, nil +// repodataNotModified sets the ETag of the filtered copy of the document +// identified by digest when the proxy knows it, and answers a conditional +// request it matches with 304, reporting whether it did. The ETag is known +// once the document has been filtered, until an entry it left out leaves +// cooldown. Filtering a large document costs seconds, and sending it +// hundreds of MB, so this is what makes revalidating clients cheap. +func (h *CondaHandler) repodataNotModified(w http.ResponseWriter, r *http.Request, cacheKey, digest string, now time.Time) bool { + if digest == "" { + return false } + h.repodataMu.Lock() + state, ok := h.repodataStates[cacheKey] + h.repodataMu.Unlock() + if !ok || state.digest != digest || (!state.until.IsZero() && !now.Before(state.until)) { + return false + } + w.Header().Set(headerETag, state.etag) + if ifNoneMatchHits(r.Header.Get("If-None-Match"), state.etag) { + w.WriteHeader(http.StatusNotModified) + return true + } + return false +} - var repodata map[string]any - if err := json.Unmarshal(body, &repodata); err != nil { +// rememberRepodata records the ETag of a filtered copy of the document +// identified by digest. The copy depends only on the document, the startup +// configuration and which entries were left out, and those stay left out +// until the first of them leaves cooldown. +func (h *CondaHandler) rememberRepodata(cacheKey, digest string, filter *repodataFilter) { + if filter.unknownUntil { + return + } + etag := keptVersionsETag(digest, "", cacheKey, []string{hex.EncodeToString(filter.withheld.Sum(nil))}) + h.repodataMu.Lock() + defer h.repodataMu.Unlock() + if h.repodataStates == nil { + h.repodataStates = make(map[string]repodataState) + } + h.repodataStates[cacheKey] = repodataState{digest: digest, etag: etag, until: filter.until} +} + +// countingWriter counts the bytes written through it, such as whether +// anything has reached the response yet. +type countingWriter struct { + w io.Writer + n int64 +} + +func (c *countingWriter) Write(p []byte) (int, error) { + n, err := c.w.Write(p) + c.n += int64(n) + return n, err +} + +// condaMaxSecondsTimestamp is the last second of year 9999. Like conda, a +// larger repodata timestamp is read as milliseconds and a smaller one as +// seconds, which some older entries use. +const condaMaxSecondsTimestamp = 253402300799 + +// condaTime returns the time a repodata timestamp names. +func condaTime(timestamp float64) time.Time { + if timestamp > condaMaxSecondsTimestamp { + return time.UnixMilli(int64(timestamp)).Truncate(time.Second) + } + return time.Unix(int64(timestamp), 0) +} + +const ( + repodataWriteBuffer = 64 << 10 + // maxRepodataSize stops a runaway upstream body. It is well above the + // largest conda-forge index, which is under 500 MB. + maxRepodataSize = 4 << 30 +) + +// filterRepodata copies repodata.json from r to w, leaving out entries in +// packages and packages.conda that are still inside their cooldown. Kept +// entries and every other member are written with their upstream bytes. +func (h *CondaHandler) filterRepodata(r io.Reader, w io.Writer) error { + return h.filterRepodataWith(r, w, h.newRepodataFilter(time.Now())) +} + +// filterRepodataWith is filterRepodata deciding by filter. +func (h *CondaHandler) filterRepodataWith(r io.Reader, w io.Writer, filter *repodataFilter) error { + return jsonstream.CopyObject(r, w, func(m *jsonstream.Member) error { + if m.Key != "packages" && m.Key != "packages.conda" { + return m.Copy() + } + return m.Object(func(entry *jsonstream.Member) error { + raw, err := entry.Raw() + if err != nil { + return err + } + if filter.inCooldown(entry.Key, raw) { + return nil + } + return entry.Write(raw) + }) + }) +} + +type repodataEntry struct { + Name string `json:"name"` + Version string `json:"version"` + Timestamp float64 `json:"timestamp"` +} + +// repodataFilter decides which repodata entries cooldown leaves out, all as +// of one time, and records what it left out, which with the document fixes +// the filtered copy. +type repodataFilter struct { + h *CondaHandler + now time.Time + // withheld hashes the filenames left out. + withheld hash.Hash + // until is when the first entry left out leaves cooldown. + until time.Time + // unknownUntil is set when an entry was left out without a time it + // leaves cooldown, so until can't be relied on. + unknownUntil bool +} + +func (h *CondaHandler) newRepodataFilter(now time.Time) *repodataFilter { + return &repodataFilter{h: h, now: now, withheld: sha256.New()} +} + +// inCooldown reports whether a repodata entry was published too recently. +// Entries without a name or timestamp are kept. +func (f *repodataFilter) inCooldown(filename string, raw []byte) bool { + var entry repodataEntry + if err := json.Unmarshal(raw, &entry); err != nil { + return false + } + if entry.Name == "" || entry.Timestamp == 0 { + return false + } + publishedAt := condaTime(entry.Timestamp) + decision := f.h.proxy.cooldown().Evaluate("conda", canonicalPackagePURL("conda", entry.Name), publishedAt, f.now) + if decision.Allowed { + return false + } + f.h.proxy.Logger.Info("cooldown: filtering conda package", + "name", entry.Name, "version", entry.Version, "filename", filename) + _, _ = fmt.Fprintf(f.withheld, "%d:%s", len(filename), filename) + switch { + case decision.AvailableAt.IsZero(): + f.unknownUntil = true + case f.until.IsZero() || decision.AvailableAt.Before(f.until): + f.until = decision.AvailableAt + } + return true +} + +// recordInCooldown reports whether a package record with a repodata +// timestamp was published too recently. Records without a name or +// timestamp are kept. +func (h *CondaHandler) recordInCooldown(filename, name, version string, timestamp float64) bool { + if name == "" || timestamp == 0 { + return false + } + publishedAt := condaTime(timestamp) + if h.proxy.cooldown().IsAllowed("conda", canonicalPackagePURL("conda", name), publishedAt) { + return false + } + h.proxy.Logger.Info("cooldown: filtering conda package", + "name", name, "version", version, "filename", filename) + return true +} + +// metadataCacheKey is the metadata cache key of a request path. +func (h *CondaHandler) metadataCacheKey(urlPath string) string { + return hashedCacheKey(h.upstreamURL, urlPath) +} + +// publishTime streams compressed repodata when it exceeds metadata_max_size. +func (h *CondaHandler) publishTime(r *http.Request, channel, arch, filename string) (time.Time, bool, error) { + repodataPath := "/" + channel + "/" + arch + "/repodata.json" + cacheKey := h.metadataCacheKey(repodataPath) + index, err := publishIndex(h.proxy, "conda\x00"+cacheKey, func() metadataResult { + return h.proxy.lookupMetadata(r.Context(), "conda", cacheKey, h.upstreamURL+repodataPath, "*/*", "gzip", nil) + }, func(res metadataResult) (map[string]time.Time, error) { + if errors.Is(res.err, ErrMetadataTooLarge) { + return h.streamRepodataIndex(r, h.upstreamURL+repodataPath) + } + if res.err != nil { + return nil, res.err + } + return h.indexRepodata(res.body, res.contentEncoding) + }) + if err != nil { + return time.Time{}, false, err + } + published, ok := index[filename] + return published, ok, nil +} + +// indexRepodata indexes a cached repodata.json body. +func (h *CondaHandler) indexRepodata(body []byte, encoding string) (map[string]time.Time, error) { + var reader io.Reader = bytes.NewReader(body) + if strings.EqualFold(strings.TrimSpace(encoding), "gzip") { + decoded, err := gzip.NewReader(reader) + if err != nil { + return nil, err + } + reader = decoded + } + return readRepodataIndex(reader) +} + +// streamRepodataIndex indexes repodata.json as it streams from upstream. +func (h *CondaHandler) streamRepodataIndex(r *http.Request, upstreamURL string) (map[string]time.Time, error) { + req, err := http.NewRequestWithContext(r.Context(), http.MethodGet, upstreamURL, nil) + if err != nil { return nil, err } - - for _, key := range []string{"packages", "packages.conda"} { - packages, ok := repodata[key].(map[string]any) - if !ok { - continue - } - - for filename, entry := range packages { - entryMap, ok := entry.(map[string]any) - if !ok { - continue - } - - ts, ok := entryMap["timestamp"].(float64) - if !ok || ts == 0 { - continue - } - - publishedAt := time.Unix(int64(ts)/condaTimestampDivisor, 0) - - name, _ := entryMap["name"].(string) - if name == "" { - continue - } - - packagePURL := canonicalPackagePURL("conda", name) - - if !h.proxy.Cooldown.IsAllowed("conda", packagePURL, publishedAt) { - version, _ := entryMap["version"].(string) - h.proxy.Logger.Info("cooldown: filtering conda package", - "name", name, "version", version, "filename", filename) - delete(packages, filename) - } - } + req.Header.Set(headerAcceptEncoding, "gzip") + resp, err := h.proxy.HTTPClient.Do(req) + if err != nil { + return nil, err } + defer func() { _ = resp.Body.Close() }() + if resp.StatusCode != http.StatusOK { + return nil, fmt.Errorf("repodata returned %d", resp.StatusCode) + } + var reader io.Reader = resp.Body + if strings.EqualFold(strings.TrimSpace(resp.Header.Get(headerContentEncoding)), "gzip") { + decoded, err := gzip.NewReader(resp.Body) + if err != nil { + return nil, err + } + defer func() { _ = decoded.Close() }() + reader = decoded + } + return readRepodataIndex(reader) +} - return json.Marshal(repodata) +// readRepodataIndex maps each package file in a repodata.json to its +// timestamp, leaving out files without one. It reads the document as it +// streams, under the same bound as filterRepodata, so the decompressed size +// is not limited by metadata_max_size. +func readRepodataIndex(r io.Reader) (map[string]time.Time, error) { + index := make(map[string]time.Time) + err := jsonstream.CopyObject(io.LimitReader(r, maxRepodataSize), io.Discard, func(m *jsonstream.Member) error { + if m.Key != "packages" && m.Key != "packages.conda" { + return m.Copy() + } + return m.Object(func(entry *jsonstream.Member) error { + raw, err := entry.Raw() + if err != nil { + return err + } + var e repodataEntry + if json.Unmarshal(raw, &e) == nil && e.Timestamp != 0 { + index[entry.Key] = condaTime(e.Timestamp) + } + return nil + }) + }) + if err != nil { + return nil, err + } + return index, nil } // proxyCached forwards a metadata request with caching. func (h *CondaHandler) proxyCached(w http.ResponseWriter, r *http.Request) { - cacheKey := strings.TrimPrefix(r.URL.Path, "/") - cacheKey = strings.ReplaceAll(cacheKey, "/", "_") + cacheKey := h.metadataCacheKey(r.URL.Path) // Large JSON indexes can exceed the metadata limit uncompressed. Conda // clients decode Content-Encoding, so cache and relay gzip verbatim. The // already-compressed repodata.json.bz2 route must stay on identity. @@ -291,7 +651,7 @@ func (h *CondaHandler) proxyCached(w http.ResponseWriter, r *http.Request) { if strings.HasSuffix(r.URL.Path, ".json") { acceptEncoding = "gzip" } - h.proxy.proxyCachedWithEncoding(w, r, h.upstreamURL+r.URL.Path, "conda", cacheKey, acceptEncoding, "*/*") + h.proxy.proxyCachedWithEncoding(w, r, h.upstreamURL+r.URL.Path, "conda", cacheKey, acceptEncoding, nil, "*/*") } // proxyUpstream forwards a request to Anaconda without caching. diff --git a/internal/handler/conda_encoding_test.go b/internal/handler/conda_encoding_test.go index b453a00..a8f3a79 100644 --- a/internal/handler/conda_encoding_test.go +++ b/internal/handler/conda_encoding_test.go @@ -3,6 +3,8 @@ package handler import ( "bytes" "encoding/json" + "fmt" + "io" "net/http" "net/http/httptest" "strings" @@ -38,7 +40,8 @@ func TestCondaRepodataGzip(t *testing.T) { if tt.mode == "cached" { proxy.MetadataTTL = time.Hour } - handler := NewCondaHandlerWithUpstream(proxy, "http://proxy.local", upstream.URL).Routes() + h := NewCondaHandlerWithUpstream(proxy, "http://proxy.local", upstream.URL) + handler := h.Routes() serve := func() *httptest.ResponseRecorder { w := httptest.NewRecorder() handler.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/conda-forge/linux-64/"+tt.filename, nil)) @@ -51,7 +54,7 @@ func TestCondaRepodataGzip(t *testing.T) { if tt.mode == "stream" { return } - entry, err := db.GetMetadataCache("conda", "conda-forge_linux-64_"+tt.filename) + entry, err := db.GetMetadataCache("conda", h.metadataCacheKey("/conda-forge/linux-64/"+tt.filename)) if err != nil { t.Fatal(err) } @@ -120,7 +123,8 @@ func TestCondaRepodataCacheSizeLimit(t *testing.T) { proxy.HTTPClient = upstream.Client() proxy.CacheMetadata = true proxy.MetadataMaxSize = tt.limit - handler := NewCondaHandlerWithUpstream(proxy, "http://proxy.local", upstream.URL).Routes() + h := NewCondaHandlerWithUpstream(proxy, "http://proxy.local", upstream.URL) + handler := h.Routes() w := httptest.NewRecorder() handler.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/conda-forge/linux-64/repodata.json", nil)) if w.Code != tt.status { @@ -130,7 +134,7 @@ func TestCondaRepodataCacheSizeLimit(t *testing.T) { if !bytes.Equal(w.Body.Bytes(), plain) || w.Header().Get(headerContentEncoding) != "" { t.Fatal("identity response was changed or mislabeled as gzip") } - } else if entry, _ := db.GetMetadataCache("conda", "conda-forge_linux-64_repodata.json"); entry != nil { + } else if entry, _ := db.GetMetadataCache("conda", h.metadataCacheKey("/conda-forge/linux-64/repodata.json")); entry != nil { t.Fatal("oversized response was cached") } }) @@ -194,7 +198,6 @@ func TestCondaRepodataCooldownRejectsInvalidGzip(t *testing.T) { }{ {"invalid header", []byte("not gzip")}, {"truncated body", compressed[:len(compressed)-4]}, - {"decoded size exceeds limit", compressed}, } { t.Run(tt.name, func(t *testing.T) { upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { @@ -205,9 +208,6 @@ func TestCondaRepodataCooldownRejectsInvalidGzip(t *testing.T) { proxy := testProxy() proxy.HTTPClient = upstream.Client() proxy.Cooldown = &cooldown.Config{Default: "3d"} - if tt.name == "decoded size exceeds limit" { - proxy.MetadataMaxSize = int64(len(compressed)) - } handler := NewCondaHandlerWithUpstream(proxy, "http://proxy.local", upstream.URL).Routes() w := httptest.NewRecorder() handler.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/conda-forge/linux-64/repodata.json", nil)) @@ -217,3 +217,99 @@ func TestCondaRepodataCooldownRejectsInvalidGzip(t *testing.T) { }) } } + +// largeRepodata builds repodata with n old and n new entries in each of +// packages and packages.conda. +func largeRepodata(n int) []byte { + old := time.Now().Add(-30 * 24 * time.Hour).UnixMilli() + recent := time.Now().UnixMilli() + var b strings.Builder + b.WriteString(`{"info":{"subdir":"linux-64"},"repodata_version":1`) + for _, key := range []string{"packages", "packages.conda"} { + fmt.Fprintf(&b, `,%q:{`, key) + for i := range 2 * n { + if i > 0 { + b.WriteByte(',') + } + ts, kind := old, "old" + if i%2 == 1 { + ts, kind = recent, "new" + } + fmt.Fprintf(&b, `"pkg-%d-%s.conda":{"name":"pkg%d","version":"1.0","timestamp":%d,"depends":["python >=3.10,<4","libgcc >=13"],"md5":"%032d"}`, + i, kind, i, ts, i) + } + b.WriteByte('}') + } + b.WriteString(`,"removed":[]}`) + return []byte(b.String()) +} + +func TestCondaRepodataCooldownStreamsPastMetadataLimit(t *testing.T) { + plain := largeRepodata(2000) + compressed := gzipPayload(t, plain) + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set(headerContentEncoding, "gzip") + _, _ = w.Write(compressed) + })) + defer upstream.Close() + + proxy := testProxy() + proxy.HTTPClient = upstream.Client() + proxy.Cooldown = &cooldown.Config{Default: "3d"} + proxy.MetadataMaxSize = int64(len(plain) / 10) + handler := NewCondaHandlerWithUpstream(proxy, "http://proxy.local", upstream.URL).Routes() + + w := httptest.NewRecorder() + handler.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/conda-forge/linux-64/repodata.json", nil)) + if w.Code != http.StatusOK { + t.Fatalf("status = %d, want 200 for repodata %d times the metadata limit", w.Code, len(plain)/int(proxy.MetadataMaxSize)) + } + var result struct { + Info map[string]any `json:"info"` + Packages map[string]json.RawMessage `json:"packages"` + Conda map[string]json.RawMessage `json:"packages.conda"` + Removed []string `json:"removed"` + } + if err := json.Unmarshal(w.Body.Bytes(), &result); err != nil { + t.Fatalf("response is not valid JSON: %v", err) + } + if len(result.Packages) != 2000 || len(result.Conda) != 2000 || result.Info["subdir"] != "linux-64" || result.Removed == nil { + t.Fatalf("got %d packages, %d conda packages, info %v", len(result.Packages), len(result.Conda), result.Info) + } + for name := range result.Packages { + if strings.HasSuffix(name, "-new.conda") { + t.Fatalf("%s is inside the cooldown but was kept", name) + } + } + want := `"pkg-0-old.conda":{"name":"pkg0","version":"1.0","timestamp":` + if !strings.Contains(w.Body.String(), want) { + t.Errorf("kept entries should keep their upstream bytes") + } +} + +func TestCondaRepodataCooldownAbortsTruncatedStream(t *testing.T) { + compressed := gzipPayload(t, largeRepodata(2000)) + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set(headerContentEncoding, "gzip") + _, _ = w.Write(compressed[:len(compressed)*3/4]) + })) + defer upstream.Close() + + proxy := testProxy() + proxy.HTTPClient = upstream.Client() + proxy.Cooldown = &cooldown.Config{Default: "3d"} + server := httptest.NewServer(NewCondaHandlerWithUpstream(proxy, "http://proxy.local", upstream.URL).Routes()) + defer server.Close() + + resp, err := server.Client().Get(server.URL + "/conda-forge/linux-64/repodata.json") + if err != nil { + t.Fatal(err) + } + defer func() { _ = resp.Body.Close() }() + if resp.StatusCode != http.StatusOK { + t.Fatalf("status = %d; want the stream to start before the upstream body breaks", resp.StatusCode) + } + if _, err := io.ReadAll(resp.Body); err == nil { + t.Fatal("read a truncated repodata response without an error") + } +} diff --git a/internal/handler/conda_repodata_bench_test.go b/internal/handler/conda_repodata_bench_test.go new file mode 100644 index 0000000..61e68bd --- /dev/null +++ b/internal/handler/conda_repodata_bench_test.go @@ -0,0 +1,59 @@ +package handler + +import ( + "bytes" + "io" + "log/slog" + "os" + "testing" + "time" + + "github.com/git-pkgs/cooldown" +) + +// repodataBenchBody reads the repodata.json named by CONDA_REPODATA_BENCH, +// such as conda-forge's noarch one, and skips the benchmark without it. +func repodataBenchBody(b *testing.B) []byte { + b.Helper() + path := os.Getenv("CONDA_REPODATA_BENCH") + if path == "" { + b.Skip("CONDA_REPODATA_BENCH names no repodata.json") + } + body, err := os.ReadFile(path) + if err != nil { + b.Fatal(err) + } + return body +} + +func BenchmarkCondaFilterRepodata(b *testing.B) { + body := repodataBenchBody(b) + policy, err := cooldown.NewPolicy(&cooldown.Config{Default: "3d"}, nil) + if err != nil { + b.Fatal(err) + } + proxy := testProxy() + proxy.Logger = slog.New(slog.DiscardHandler) + proxy.Cooldown = policy + h := NewCondaHandler(proxy, "http://proxy.example") + now := time.Now() + b.SetBytes(int64(len(body))) + b.ReportAllocs() + for b.Loop() { + if err := h.filterRepodataWith(bytes.NewReader(body), io.Discard, h.newRepodataFilter(now)); err != nil { + b.Fatal(err) + } + } +} + +func BenchmarkCondaReadRepodataIndex(b *testing.B) { + body := repodataBenchBody(b) + b.SetBytes(int64(len(body))) + b.ReportAllocs() + for b.Loop() { + index, err := readRepodataIndex(bytes.NewReader(body)) + if err != nil || len(index) == 0 { + b.Fatalf("index of %d files, %v", len(index), err) + } + } +} diff --git a/internal/handler/conda_repodata_variants_test.go b/internal/handler/conda_repodata_variants_test.go new file mode 100644 index 0000000..48f997b --- /dev/null +++ b/internal/handler/conda_repodata_variants_test.go @@ -0,0 +1,76 @@ +package handler + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "sync/atomic" + "testing" + "time" + + "github.com/git-pkgs/cooldown" +) + +// The proxy filters only the plain JSON repodata. With cooldown on, any +// other form of it would list versions still in cooldown, so it is refused +// and clients fall back to repodata.json. +func TestCondaRepodataVariantsUnderCooldown(t *testing.T) { + plain, err := json.Marshal(map[string]any{ + "packages": map[string]any{ + "old.tar.bz2": map[string]any{"name": "demo", "timestamp": time.Now().Add(-7 * 24 * time.Hour).UnixMilli()}, + "new.tar.bz2": map[string]any{"name": "demo", "timestamp": time.Now().UnixMilli()}, + }, + }) + if err != nil { + t.Fatal(err) + } + var requests atomic.Int32 + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + requests.Add(1) + _, _ = w.Write(plain) + })) + defer upstream.Close() + + variants := []string{ + "repodata.json.bz2", + "repodata.json.zst", + "repodata.jlap", + "current_repodata.json.zst", + "repodata_from_packages.json.zst", + } + for _, enabled := range []bool{true, false} { + proxy := testProxy() + proxy.HTTPClient = upstream.Client() + if enabled { + proxy.Cooldown = &cooldown.Config{Default: "3d"} + } + handler := NewCondaHandlerWithUpstream(proxy, "http://proxy.local", upstream.URL).Routes() + for _, filename := range variants { + requests.Store(0) + w := httptest.NewRecorder() + handler.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/conda-forge/linux-64/"+filename, nil)) + switch { + case enabled && (w.Code != http.StatusNotFound || requests.Load() != 0): + t.Errorf("cooldown on, %s: status %d, %d upstream requests; want 404 without asking upstream", filename, w.Code, requests.Load()) + case !enabled && (w.Code != http.StatusOK || requests.Load() != 1): + t.Errorf("cooldown off, %s: status %d, %d upstream requests; want it passed through", filename, w.Code, requests.Load()) + } + } + } + + // repodata_from_packages.json is plain JSON and is filtered like + // repodata.json. + proxy := testProxy() + proxy.HTTPClient = upstream.Client() + proxy.Cooldown = &cooldown.Config{Default: "3d"} + handler := NewCondaHandlerWithUpstream(proxy, "http://proxy.local", upstream.URL).Routes() + w := httptest.NewRecorder() + handler.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/conda-forge/linux-64/repodata_from_packages.json", nil)) + var result map[string]map[string]any + if err := json.Unmarshal(w.Body.Bytes(), &result); err != nil { + t.Fatalf("status %d, body %s: %v", w.Code, w.Body, err) + } + if len(result["packages"]) != 1 || result["packages"]["old.tar.bz2"] == nil { + t.Errorf("repodata_from_packages.json not filtered: %s", w.Body) + } +} diff --git a/internal/handler/conda_shards.go b/internal/handler/conda_shards.go new file mode 100644 index 0000000..dbfaee2 --- /dev/null +++ b/internal/handler/conda_shards.go @@ -0,0 +1,458 @@ +package handler + +import ( + "bytes" + "crypto/sha256" + "encoding/hex" + "errors" + "fmt" + "net/http" + "net/url" + "path" + "strconv" + "strings" + "sync" + "time" + + "github.com/klauspost/compress/zstd" + "github.com/vmihailenco/msgpack/v5" +) + +// Sharded repodata (CEP 16) maps each package name to the sha256 of its +// shard. With cooldown the proxy filters shards, which changes their bytes, +// but clients cache shards by hash and never fetch the same hash again. So +// the rewritten index XORs every hash with a mask that changes each hour: +// filtered shards get hashes of their own, and clients fetch them again once +// versions have left cooldown. +const ( + condaShardIndexFile = "repodata_shards.msgpack.zst" + condaShardSuffix = ".msgpack.zst" + condaCooldownShardDir = "cooldown-shards" + condaShardsSubdir = "shards/" + condaShardBucket = time.Hour + condaShardIndexFormat = 1 + condaShardHashLen = sha256.Size + // maxCondaShardSize bounds a decompressed index or shard. conda-forge's + // largest index is a few MB. + maxCondaShardSize = 256 << 20 +) + +var ( + errCondaShardLayout = errors.New("unsupported sharded repodata layout") + + condaZstd = sync.OnceValues(func() (*zstd.Decoder, error) { + return zstd.NewReader(nil, zstd.WithDecoderMaxMemory(maxCondaShardSize), zstd.WithDecoderConcurrency(0)) + }) + condaZstdEncoder = sync.OnceValues(func() (*zstd.Encoder, error) { + return zstd.NewWriter(nil) + }) +) + +func (h *CondaHandler) cooldownEnabled() bool { + return h.proxy.Cooldown != nil && h.proxy.Cooldown.Enabled() +} + +// handleShardIndex serves repodata_shards.msgpack.zst. +func (h *CondaHandler) handleShardIndex(w http.ResponseWriter, r *http.Request) { + channel, arch := r.PathValue("channel"), r.PathValue("arch") + upstreamURL := h.upstreamURL + r.URL.Path + cacheKey := h.metadataCacheKey(r.URL.Path) + + res := h.proxy.lookupMetadata(r.Context(), "conda", cacheKey, upstreamURL, "*/*", "identity", nil) + if res.err != nil { + h.proxy.writeMetadataFetchError(w, res.err) + return + } + body := res.body + + if !h.cooldownEnabled() { + index, err := decodeCondaShardIndex(body) + if err == nil { + _, err = index.shardsLayout(upstreamURL) + } + if err != nil { + h.proxy.Logger.Info("serving no sharded repodata", "url", upstreamURL, "error", err) + http.NotFound(w, r) + return + } + writeMetadataResult(w, r, res) + return + } + + now := time.Now() + bucket := strconv.FormatInt(now.Unix()/int64(condaShardBucket/time.Second), 10) + rewritten, err := rewriteCondaShardIndex(body, upstreamURL, condaShardMask(channel, arch, bucket), bucket) + if err != nil { + h.proxy.Logger.Info("serving no sharded repodata", "url", upstreamURL, "error", err) + http.NotFound(w, r) + return + } + + next := now.Truncate(condaShardBucket).Add(condaShardBucket) + maxAge := max(int(next.Sub(now)/time.Second), 1) + w.Header().Set(headerContentType, "application/octet-stream") + w.Header().Set("Cache-Control", fmt.Sprintf("public, max-age=%d", maxAge)) + _, _ = w.Write(rewritten) +} + +// handleShard serves a shard under its upstream hash. While cooldown is on, +// the index never points here, and the unfiltered shard is refused. +func (h *CondaHandler) handleShard(w http.ResponseWriter, r *http.Request) { + if h.cooldownEnabled() || !isCondaShardFile(path.Base(r.URL.Path)) { + http.NotFound(w, r) + return + } + h.proxyCached(w, r) +} + +// handleCooldownShard serves a shard named in a rewritten index, filtered by +// cooldown. +func (h *CondaHandler) handleCooldownShard(w http.ResponseWriter, r *http.Request) { + channel, arch, bucket := r.PathValue("channel"), r.PathValue("arch"), r.PathValue("bucket") + dir, file := path.Split(r.PathValue("rest")) + if _, err := strconv.ParseUint(bucket, 10, 64); err != nil || (dir != "" && dir != condaShardsSubdir) || !isCondaShardFile(file) { + http.NotFound(w, r) + return + } + + masked, _ := hex.DecodeString(strings.TrimSuffix(file, condaShardSuffix)) + mask := condaShardMask(channel, arch, bucket) + for i := range masked { + masked[i] ^= mask[i] + } + upstreamPath := "/" + channel + "/" + arch + "/" + dir + hex.EncodeToString(masked) + condaShardSuffix + + body, _, err := h.proxy.fetchOrCacheMetadata(r.Context(), "conda", h.metadataCacheKey(upstreamPath), h.upstreamURL+upstreamPath, "identity", nil, "*/*") + if err != nil { + h.proxy.writeMetadataFetchError(w, err) + return + } + + if h.cooldownEnabled() { + body, err = h.filterCondaShard(body) + if err != nil { + h.proxy.Logger.Error("failed to filter conda shard", "path", upstreamPath, "error", err) + http.Error(w, "failed to filter shard", http.StatusBadGateway) + return + } + } + w.Header().Set(headerContentType, "application/octet-stream") + _, _ = w.Write(body) +} + +func isCondaShardFile(name string) bool { + hash, ok := strings.CutSuffix(name, condaShardSuffix) + if !ok || len(hash) != 2*condaShardHashLen { + return false + } + _, err := hex.DecodeString(hash) + return err == nil && strings.ToLower(hash) == hash +} + +// condaShardMask is XORed with shard hashes in a rewritten index. It keeps +// filtered shards apart from upstream ones in client caches, which are keyed +// by hash alone. +func condaShardMask(channel, arch, bucket string) [condaShardHashLen]byte { + return sha256.Sum256([]byte("git-pkgs proxy conda cooldown shard\x00" + channel + "\x00" + arch + "\x00" + bucket)) +} + +// msgpackEntry is one member of a msgpack map, kept in its upstream order +// with its value undecoded. +type msgpackEntry struct { + key string + value msgpack.RawMessage +} + +func decodeMsgpackMap(b []byte) ([]msgpackEntry, error) { + dec := msgpack.NewDecoder(bytes.NewReader(b)) + n, err := dec.DecodeMapLen() + if err != nil { + return nil, err + } + if n < 0 { + return nil, errors.New("expected a msgpack map") + } + entries := make([]msgpackEntry, 0, n) + for range n { + key, err := dec.DecodeString() + if err != nil { + return nil, err + } + value, err := dec.DecodeRaw() + if err != nil { + return nil, err + } + entries = append(entries, msgpackEntry{key: key, value: value}) + } + return entries, nil +} + +func encodeMsgpackMap(entries []msgpackEntry) ([]byte, error) { + var buf bytes.Buffer + enc := msgpack.NewEncoder(&buf) + if err := enc.EncodeMapLen(len(entries)); err != nil { + return nil, err + } + for _, e := range entries { + if err := enc.EncodeString(e.key); err != nil { + return nil, err + } + if err := enc.Encode(e.value); err != nil { + return nil, err + } + } + return buf.Bytes(), nil +} + +func lookupMsgpackEntry(entries []msgpackEntry, key string) (int, bool) { + for i, e := range entries { + if e.key == key { + return i, true + } + } + return -1, false +} + +func decompressCondaShard(body []byte) ([]byte, error) { + dec, err := condaZstd() + if err != nil { + return nil, err + } + return dec.DecodeAll(body, nil) +} + +func compressCondaShard(body []byte) ([]byte, error) { + enc, err := condaZstdEncoder() + if err != nil { + return nil, err + } + return enc.EncodeAll(body, nil), nil +} + +// condaShardIndex is a decoded repodata_shards.msgpack.zst. +type condaShardIndex struct { + top []msgpackEntry + info []msgpackEntry +} + +func decodeCondaShardIndex(body []byte) (*condaShardIndex, error) { + raw, err := decompressCondaShard(body) + if err != nil { + return nil, err + } + top, err := decodeMsgpackMap(raw) + if err != nil { + return nil, err + } + i, ok := lookupMsgpackEntry(top, "version") + if !ok { + return nil, errors.New("sharded index has no version") + } + var version int + if err := msgpack.Unmarshal(top[i].value, &version); err != nil || version != condaShardIndexFormat { + return nil, fmt.Errorf("unsupported sharded index version %v", top[i].value) + } + i, ok = lookupMsgpackEntry(top, "info") + if !ok { + return nil, errors.New("sharded index has no info") + } + info, err := decodeMsgpackMap(top[i].value) + if err != nil { + return nil, err + } + return &condaShardIndex{top: top, info: info}, nil +} + +func (idx *condaShardIndex) infoString(key string) (string, error) { + i, ok := lookupMsgpackEntry(idx.info, key) + if !ok { + return "", nil + } + var s string + err := msgpack.Unmarshal(idx.info[i].value, &s) + return s, err +} + +// shardsLayout checks that packages and shards sit where the proxy routes +// them, below the subdir of indexURL, and returns the shards directory +// relative to the subdir: "" or "shards/". Clients resolve base_url and +// shards_base_url against the proxy's URL, so only relative paths stay on +// the proxy: a scheme or host leads clients around it, a leading / outside +// its mount. +func (idx *condaShardIndex) shardsLayout(indexURL string) (string, error) { + base, err := url.Parse(indexURL) + if err != nil { + return "", err + } + subdir := base.ResolveReference(&url.URL{Path: "./"}).String() + resolve := func(ref string) (string, error) { + if ref == "" { + return subdir, nil + } + u, err := url.Parse(ref) + if err != nil { + return "", err + } + if u.Scheme != "" || u.Host != "" || strings.HasPrefix(u.Path, "/") { + return "", errCondaShardLayout + } + return base.ResolveReference(u).String(), nil + } + + baseURL, err := idx.infoString("base_url") + if err != nil { + return "", err + } + if resolved, err := resolve(baseURL); err != nil || resolved != subdir { + return "", fmt.Errorf("%w: base_url %q", errCondaShardLayout, baseURL) + } + + shardsBaseURL, err := idx.infoString("shards_base_url") + if err != nil { + return "", err + } + resolved, err := resolve(shardsBaseURL) + rel, ok := strings.CutPrefix(resolved, subdir) + if err != nil || !ok || (rel != "" && rel != condaShardsSubdir) { + return "", fmt.Errorf("%w: shards_base_url %q", errCondaShardLayout, shardsBaseURL) + } + return rel, nil +} + +// rewriteCondaShardIndex masks every shard hash and points shards_base_url +// at the cooldown shard route for bucket. +func rewriteCondaShardIndex(body []byte, indexURL string, mask [condaShardHashLen]byte, bucket string) ([]byte, error) { + idx, err := decodeCondaShardIndex(body) + if err != nil { + return nil, err + } + layout, err := idx.shardsLayout(indexURL) + if err != nil { + return nil, err + } + + shardsBase, err := msgpack.Marshal("./" + condaCooldownShardDir + "/" + bucket + "/" + layout) + if err != nil { + return nil, err + } + if i, ok := lookupMsgpackEntry(idx.info, "shards_base_url"); ok { + idx.info[i].value = shardsBase + } else { + idx.info = append(idx.info, msgpackEntry{key: "shards_base_url", value: shardsBase}) + } + info, err := encodeMsgpackMap(idx.info) + if err != nil { + return nil, err + } + i, _ := lookupMsgpackEntry(idx.top, "info") + idx.top[i].value = info + + i, ok := lookupMsgpackEntry(idx.top, "shards") + if !ok { + return nil, errors.New("sharded index has no shards") + } + shards, err := decodeMsgpackMap(idx.top[i].value) + if err != nil { + return nil, err + } + for j := range shards { + var hash []byte + if err := msgpack.Unmarshal(shards[j].value, &hash); err != nil || len(hash) != condaShardHashLen { + return nil, fmt.Errorf("shard hash for %q is not a sha256", shards[j].key) + } + for k := range hash { + hash[k] ^= mask[k] + } + if shards[j].value, err = msgpack.Marshal(hash); err != nil { + return nil, err + } + } + if idx.top[i].value, err = encodeMsgpackMap(shards); err != nil { + return nil, err + } + + raw, err := encodeMsgpackMap(idx.top) + if err != nil { + return nil, err + } + return compressCondaShard(raw) +} + +// condaShardRecord holds the fields cooldown needs from a shard record. +// Timestamps are an integer or a float, in seconds or milliseconds as +// condaTime reads them. +type condaShardRecord struct { + Name string `msgpack:"name"` + Version string `msgpack:"version"` + Timestamp any `msgpack:"timestamp"` +} + +// filterCondaShard leaves out records in packages and packages.conda that +// are still inside their cooldown. Kept records keep their upstream bytes. +func (h *CondaHandler) filterCondaShard(body []byte) ([]byte, error) { + raw, err := decompressCondaShard(body) + if err != nil { + return nil, err + } + top, err := decodeMsgpackMap(raw) + if err != nil { + return nil, err + } + for i := range top { + if top[i].key != "packages" && top[i].key != "packages.conda" { + continue + } + records, err := decodeMsgpackMap(top[i].value) + if err != nil { + return nil, err + } + kept := records[:0] + for _, rec := range records { + var fields condaShardRecord + if err := msgpack.Unmarshal(rec.value, &fields); err != nil { + return nil, fmt.Errorf("record %q: %w", rec.key, err) + } + if h.recordInCooldown(rec.key, fields.Name, fields.Version, msgpackNumber(fields.Timestamp)) { + continue + } + kept = append(kept, rec) + } + if top[i].value, err = encodeMsgpackMap(kept); err != nil { + return nil, err + } + } + out, err := encodeMsgpackMap(top) + if err != nil { + return nil, err + } + return compressCondaShard(out) +} + +// msgpackNumber returns a decoded msgpack integer or float as float64, and 0 +// for anything else. +func msgpackNumber(v any) float64 { + switch n := v.(type) { + case int8: + return float64(n) + case int16: + return float64(n) + case int32: + return float64(n) + case int64: + return float64(n) + case uint8: + return float64(n) + case uint16: + return float64(n) + case uint32: + return float64(n) + case uint64: + return float64(n) + case float32: + return float64(n) + case float64: + return n + default: + return 0 + } +} diff --git a/internal/handler/conda_shards_test.go b/internal/handler/conda_shards_test.go new file mode 100644 index 0000000..27b0ad7 --- /dev/null +++ b/internal/handler/conda_shards_test.go @@ -0,0 +1,289 @@ +package handler + +import ( + "bytes" + "crypto/sha256" + "encoding/hex" + "net/http" + "net/http/httptest" + "sort" + "strings" + "testing" + "time" + + "github.com/git-pkgs/cooldown" + "github.com/vmihailenco/msgpack/v5" +) + +func zstdMsgpack(t *testing.T, v any) []byte { + t.Helper() + raw, err := msgpack.Marshal(v) + if err != nil { + t.Fatal(err) + } + out, err := compressCondaShard(raw) + if err != nil { + t.Fatal(err) + } + return out +} + +func decodeZstdMsgpack(t *testing.T, body []byte, v any) { + t.Helper() + raw, err := decompressCondaShard(body) + if err != nil { + t.Fatal(err) + } + if err := msgpack.Unmarshal(raw, v); err != nil { + t.Fatal(err) + } +} + +type shardFixture struct { + upstream *httptest.Server + shardHash string + requests []string +} + +// newShardUpstream serves a sharded index for conda-forge/noarch with one +// shard for testpkg, holding an old and a recent build. +func newShardUpstream(t *testing.T, info map[string]any) *shardFixture { + t.Helper() + now := time.Now() + shard := zstdMsgpack(t, map[string]any{ + "packages": map[string]any{ + "testpkg-1.0.0-0.tar.bz2": map[string]any{ + "name": "testpkg", "version": "1.0.0", "timestamp": now.Add(-7 * 24 * time.Hour).UnixMilli(), + "sha256": bytes.Repeat([]byte{1}, 32), + }, + }, + "packages.conda": map[string]any{ + "testpkg-1.0.0-0.conda": map[string]any{ + "name": "testpkg", "version": "1.0.0", "timestamp": now.Add(-7 * 24 * time.Hour).UnixMilli(), + }, + "testpkg-2.0.0-0.conda": map[string]any{ + "name": "testpkg", "version": "2.0.0", "timestamp": now.Add(-time.Hour).UnixMilli(), + }, + }, + "removed": []string{"testpkg-0.1.0-0.tar.bz2"}, + }) + sum := sha256.Sum256(shard) + f := &shardFixture{shardHash: hex.EncodeToString(sum[:])} + + layout := "" + if s, _ := info["shards_base_url"].(string); strings.Contains(s, "shards/") { + layout = "shards/" + } + var index []byte + f.upstream = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + f.requests = append(f.requests, r.URL.Path) + switch r.URL.Path { + case "/conda-forge/noarch/" + condaShardIndexFile: + _, _ = w.Write(index) + case "/conda-forge/noarch/" + layout + f.shardHash + condaShardSuffix: + _, _ = w.Write(shard) + default: + http.NotFound(w, r) + } + })) + t.Cleanup(f.upstream.Close) + + // {upstream} in an info value stands for the upstream's URL, {host} for + // its host. + placeholders := strings.NewReplacer("{upstream}", f.upstream.URL, "{host}", strings.TrimPrefix(f.upstream.URL, "http://")) + for k, v := range info { + if s, ok := v.(string); ok { + info[k] = placeholders.Replace(s) + } + } + index = zstdMsgpack(t, map[string]any{ + "version": 1, + "info": info, + "shards": map[string]any{"testpkg": sum[:]}, + }) + return f +} + +func shardTestHandler(f *shardFixture, cooldownDefault string) http.Handler { + proxy := testProxy() + if cooldownDefault != "" { + proxy.Cooldown = &cooldown.Config{Default: cooldownDefault} + } + return NewCondaHandlerWithUpstream(proxy, "http://proxy.local", f.upstream.URL).Routes() +} + +func serveShardRequest(h http.Handler, path string) *httptest.ResponseRecorder { + w := httptest.NewRecorder() + h.ServeHTTP(w, httptest.NewRequest(http.MethodGet, path, nil)) + return w +} + +type shardRecords struct { + Packages map[string]map[string]any `msgpack:"packages"` + PackagesConda map[string]map[string]any `msgpack:"packages.conda"` + Removed []string `msgpack:"removed"` +} + +func (s shardRecords) filenames() []string { + var names []string + for k := range s.Packages { + names = append(names, k) + } + for k := range s.PackagesConda { + names = append(names, k) + } + sort.Strings(names) + return names +} + +type shardIndex struct { + Version int `msgpack:"version"` + Info map[string]any `msgpack:"info"` + Shards map[string][]byte `msgpack:"shards"` +} + +func TestCondaShardsWithoutCooldown(t *testing.T) { + for _, shardsBaseURL := range []string{"", "./shards/"} { + t.Run(shardsBaseURL, func(t *testing.T) { + f := newShardUpstream(t, map[string]any{"base_url": "", "shards_base_url": shardsBaseURL, "subdir": "noarch"}) + h := shardTestHandler(f, "") + + w := serveShardRequest(h, "/conda-forge/noarch/"+condaShardIndexFile) + if w.Code != http.StatusOK { + t.Fatalf("index status = %d", w.Code) + } + var index shardIndex + decodeZstdMsgpack(t, w.Body.Bytes(), &index) + if got := hex.EncodeToString(index.Shards["testpkg"]); got != f.shardHash { + t.Fatalf("index hash = %s, want upstream %s", got, f.shardHash) + } + if index.Info["shards_base_url"] != shardsBaseURL { + t.Fatalf("shards_base_url = %v, want %q", index.Info["shards_base_url"], shardsBaseURL) + } + + dir := strings.TrimPrefix(shardsBaseURL, "./") + w = serveShardRequest(h, "/conda-forge/noarch/"+dir+f.shardHash+condaShardSuffix) + if w.Code != http.StatusOK { + t.Fatalf("shard status = %d", w.Code) + } + var shard shardRecords + decodeZstdMsgpack(t, w.Body.Bytes(), &shard) + if len(shard.filenames()) != 3 { + t.Fatalf("records = %v, want all 3", shard.filenames()) + } + }) + } +} + +func TestCondaShardsWithCooldown(t *testing.T) { + f := newShardUpstream(t, map[string]any{"base_url": "", "shards_base_url": "./shards/", "subdir": "noarch", "created_at": "2026-01-01T00:00:00Z"}) + h := shardTestHandler(f, "3d") + + w := serveShardRequest(h, "/conda-forge/noarch/"+condaShardIndexFile) + if w.Code != http.StatusOK { + t.Fatalf("index status = %d", w.Code) + } + if !strings.HasPrefix(w.Header().Get("Cache-Control"), "public, max-age=") { + t.Errorf("Cache-Control = %q", w.Header().Get("Cache-Control")) + } + var index shardIndex + decodeZstdMsgpack(t, w.Body.Bytes(), &index) + masked := hex.EncodeToString(index.Shards["testpkg"]) + if masked == f.shardHash || len(masked) != 64 { + t.Fatalf("index hash = %s, want a masked hash", masked) + } + if index.Info["created_at"] != "2026-01-01T00:00:00Z" || index.Info["subdir"] != "noarch" { + t.Errorf("info lost fields: %v", index.Info) + } + shardsBaseURL, _ := index.Info["shards_base_url"].(string) + if !strings.HasPrefix(shardsBaseURL, "./"+condaCooldownShardDir+"/") || !strings.HasSuffix(shardsBaseURL, "/shards/") { + t.Fatalf("shards_base_url = %q", shardsBaseURL) + } + + w = serveShardRequest(h, "/conda-forge/noarch/"+strings.TrimPrefix(shardsBaseURL, "./")+masked+condaShardSuffix) + if w.Code != http.StatusOK { + t.Fatalf("shard status = %d: %s", w.Code, w.Body) + } + var shard shardRecords + decodeZstdMsgpack(t, w.Body.Bytes(), &shard) + want := []string{"testpkg-1.0.0-0.conda", "testpkg-1.0.0-0.tar.bz2"} + if got := shard.filenames(); strings.Join(got, ",") != strings.Join(want, ",") { + t.Fatalf("records = %v, want %v", got, want) + } + if len(shard.Removed) != 1 { + t.Errorf("removed = %v, want it kept", shard.Removed) + } + if _, ok := shard.Packages["testpkg-1.0.0-0.tar.bz2"]["sha256"].([]byte); !ok { + t.Errorf("sha256 is no longer binary: %T", shard.Packages["testpkg-1.0.0-0.tar.bz2"]["sha256"]) + } + + // The unfiltered shard stays out of reach while cooldown is on. + w = serveShardRequest(h, "/conda-forge/noarch/shards/"+f.shardHash+condaShardSuffix) + if w.Code != http.StatusNotFound { + t.Fatalf("plain shard status = %d, want 404", w.Code) + } +} + +func TestCondaCooldownShardRejectsBadPaths(t *testing.T) { + f := newShardUpstream(t, map[string]any{"base_url": "", "shards_base_url": ""}) + h := shardTestHandler(f, "3d") + hash := strings.Repeat("a", 64) + condaShardSuffix + for _, p := range []string{ + "/conda-forge/noarch/cooldown-shards/abc/" + hash, + "/conda-forge/noarch/cooldown-shards/1/other/" + hash, + "/conda-forge/noarch/cooldown-shards/1/" + strings.Repeat("A", 64) + condaShardSuffix, + "/conda-forge/noarch/cooldown-shards/1/x.msgpack.zst", + } { + if w := serveShardRequest(h, p); w.Code != http.StatusNotFound { + t.Errorf("%s: status = %d, want 404", p, w.Code) + } + } + if len(f.requests) != 0 { + t.Errorf("upstream was asked for %v", f.requests) + } +} + +func TestCondaShardIndexUnsupportedLayout(t *testing.T) { + for name, info := range map[string]map[string]any{ + "packages elsewhere": {"base_url": "https://cdn.example.com/conda-forge/noarch/", "shards_base_url": ""}, + "shards elsewhere": {"base_url": "", "shards_base_url": "https://cdn.example.com/shards/"}, + "nested shards": {"base_url": "", "shards_base_url": "./a/b/"}, + "packages upstream": {"base_url": "{upstream}/conda-forge/noarch/", "shards_base_url": ""}, + "shards upstream": {"base_url": "", "shards_base_url": "{upstream}/conda-forge/noarch/"}, + "no scheme upstream": {"base_url": "//{host}/conda-forge/noarch/", "shards_base_url": ""}, + "root-relative": {"base_url": "/conda-forge/noarch/", "shards_base_url": ""}, + "root-relative shards": {"base_url": "", "shards_base_url": "/conda-forge/noarch/shards/"}, + } { + t.Run(name, func(t *testing.T) { + f := newShardUpstream(t, info) + for _, cd := range []string{"", "3d"} { + w := serveShardRequest(shardTestHandler(f, cd), "/conda-forge/noarch/"+condaShardIndexFile) + if w.Code != http.StatusNotFound { + t.Errorf("cooldown %q: status = %d, want 404 so clients use repodata.json", cd, w.Code) + } + } + }) + } +} + +func TestCondaShardIndexUnknownVersion(t *testing.T) { + index := zstdMsgpack(t, map[string]any{"version": 2, "info": map[string]any{}, "shards": map[string]any{}}) + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _, _ = w.Write(index) + })) + defer upstream.Close() + + proxy := testProxy() + proxy.Cooldown = &cooldown.Config{Default: "3d"} + h := NewCondaHandlerWithUpstream(proxy, "http://proxy.local", upstream.URL).Routes() + if w := serveShardRequest(h, "/conda-forge/noarch/"+condaShardIndexFile); w.Code != http.StatusNotFound { + t.Fatalf("status = %d, want 404", w.Code) + } +} + +func TestCondaShardMaskDependsOnBucket(t *testing.T) { + a := condaShardMask("conda-forge", "noarch", "1") + if a == condaShardMask("conda-forge", "noarch", "2") || a == condaShardMask("conda-forge", "linux-64", "1") { + t.Fatal("mask must change with bucket and subdir") + } +} diff --git a/internal/handler/conda_subdir_test.go b/internal/handler/conda_subdir_test.go new file mode 100644 index 0000000..1a81e48 --- /dev/null +++ b/internal/handler/conda_subdir_test.go @@ -0,0 +1,61 @@ +package handler + +import ( + "net/http" + "net/http/httptest" + "sync/atomic" + "testing" + + "github.com/git-pkgs/registries/fetch" +) + +// The same conda filename can hold different bytes in each subdir, so each +// subdir must get its own cache entry. +func TestCondaDownloadCachesPerSubdir(t *testing.T) { + const filename = "python_abi-3.11-4_cp311.conda" + packages := map[string]string{ + "/conda-forge/linux-64/" + filename: "linux-64 bytes", + "/conda-forge/osx-arm64/" + filename: "osx-arm64 bytes", + } + + var available atomic.Bool + available.Store(true) + var requests atomic.Int32 + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + data, ok := packages[r.URL.Path] + if !available.Load() || !ok { + http.NotFound(w, r) + return + } + requests.Add(1) + _, _ = w.Write([]byte(data)) + })) + defer upstream.Close() + + proxy, _, _, _ := setupTestProxy(t) + fetcher := fetch.NewFetcher(fetch.WithHTTPClient(upstream.Client()), fetch.WithMaxRetries(0)) + proxy.Fetcher = fetcher + t.Cleanup(func() { _ = fetcher.Close() }) + routes := NewCondaHandlerWithUpstream(proxy, "http://proxy.local", upstream.URL).Routes() + + get := func(path string) string { + w := httptest.NewRecorder() + routes.ServeHTTP(w, httptest.NewRequest(http.MethodGet, path, nil)) + if w.Code != http.StatusOK { + t.Fatalf("%s: status = %d: %s", path, w.Code, w.Body.String()) + } + return w.Body.String() + } + + for _, round := range []string{"fetch", "cached"} { + for path, want := range packages { + if got := get(path); got != want { + t.Errorf("%s %s: body = %q, want %q", round, path, got, want) + } + } + available.Store(false) + } + if got := requests.Load(); got != 2 { + t.Errorf("upstream requests = %d, want 2 (one per subdir)", got) + } +} diff --git a/internal/handler/conda_test.go b/internal/handler/conda_test.go index 567bb6f..f6c37c6 100644 --- a/internal/handler/conda_test.go +++ b/internal/handler/conda_test.go @@ -1,10 +1,15 @@ package handler import ( + "bytes" "encoding/json" + "fmt" "log/slog" + "maps" "net/http" "net/http/httptest" + "slices" + "strings" "testing" "time" @@ -105,7 +110,7 @@ func TestCondaCooldownFiltering(t *testing.T) { proxyURL: "http://localhost:8080", } - filtered, err := h.applyCooldownFiltering(body) + filtered, err := filterRepodataBytes(h, body) if err != nil { t.Fatal(err) } @@ -132,6 +137,45 @@ func TestCondaCooldownFiltering(t *testing.T) { } } +// TestCondaCooldownSecondTimestamps checks that a timestamp in seconds, +// which some repodata entries carry, is read as seconds, as conda does, in +// both the filter and the download index. +func TestCondaCooldownSecondTimestamps(t *testing.T) { + recent := time.Now().Add(-time.Hour) + body := fmt.Sprintf(`{"packages":{"seconds-1.0-0.tar.bz2":{"name":"seconds","version":"1.0","timestamp":%d},`+ + `"millis-1.0-0.tar.bz2":{"name":"millis","version":"1.0","timestamp":%d}}}`, recent.Unix(), recent.UnixMilli()) + + proxy := testProxy() + proxy.Cooldown = &cooldown.Config{Default: "3d"} + h := &CondaHandler{proxy: proxy, proxyURL: "http://localhost:8080"} + filtered, err := filterRepodataBytes(h, []byte(body)) + if err != nil { + t.Fatal(err) + } + var result struct { + Packages map[string]json.RawMessage `json:"packages"` + } + if err := json.Unmarshal(filtered, &result); err != nil { + t.Fatal(err) + } + if len(result.Packages) != 0 { + t.Errorf("packages = %v, want both left out", slices.Sorted(maps.Keys(result.Packages))) + } + + index, err := readRepodataIndex(strings.NewReader(body)) + if err != nil { + t.Fatal(err) + } + if len(index) != 2 { + t.Fatalf("index has %d entries, want 2", len(index)) + } + for filename, published := range index { + if published.Unix() != recent.Unix() { + t.Errorf("%s published at %v, want %v", filename, published, recent) + } + } +} + func TestCondaCooldownFilteringWithPackageOverride(t *testing.T) { now := time.Now() recentTimestamp := float64(now.Add(-2 * time.Hour).UnixMilli()) @@ -164,7 +208,7 @@ func TestCondaCooldownFilteringWithPackageOverride(t *testing.T) { proxyURL: "http://localhost:8080", } - filtered, err := h.applyCooldownFiltering(body) + filtered, err := filterRepodataBytes(h, body) if err != nil { t.Fatal(err) } @@ -208,7 +252,7 @@ func TestCondaCooldownFilteringNoTimestamp(t *testing.T) { proxyURL: "http://localhost:8080", } - filtered, err := h.applyCooldownFiltering(body) + filtered, err := filterRepodataBytes(h, body) if err != nil { t.Fatal(err) } @@ -336,3 +380,9 @@ func TestCondaRetentionKey(t *testing.T) { t.Error("condaRetentionKey(nil) accepted") } } + +func filterRepodataBytes(h *CondaHandler, body []byte) ([]byte, error) { + var out bytes.Buffer + err := h.filterRepodata(bytes.NewReader(body), &out) + return out.Bytes(), err +} diff --git a/internal/handler/container.go b/internal/handler/container.go index 55f1715..40f5d0f 100644 --- a/internal/handler/container.go +++ b/internal/handler/container.go @@ -15,6 +15,7 @@ import ( "github.com/git-pkgs/proxy/internal/retention" "github.com/git-pkgs/purl" + "golang.org/x/sync/singleflight" ) const ( @@ -114,6 +115,10 @@ type ContainerHandler struct { // refusalsFull is set once the refusals set reached its limit and that // was logged. refusalsFull bool + + // manifestFlight shares one upstream exchange among concurrent + // requests for the same manifest. + manifestFlight singleflight.Group } type containerRegistry struct { @@ -121,14 +126,6 @@ type containerRegistry struct { registryURL string } -// NewContainerHandler creates a new container registry protocol handler. -// Named registries are selected with the repository prefix -// upstream/{name}/, leaving unprefixed requests compatible with the Docker Hub -// mirror behavior. -func NewContainerHandler(proxy *Proxy, proxyURL string, namedRegistries ...map[string]string) *ContainerHandler { - return newContainerHandler(proxy, proxyURL, dockerHubRegistry, namedRegistries...) -} - // NewContainerHandlerWithRegistry creates a container handler with a custom // default registry and optional named registries. func NewContainerHandlerWithRegistry( @@ -356,7 +353,7 @@ func (h *ContainerHandler) Routes() http.Handler { case path == "" || path == "/": // Version check: GET /v2/ h.handleVersionCheck(w, r) - case strings.HasSuffix(path, "/blobs/"+r.URL.Query().Get("digest")) || strings.Contains(path, "/blobs/sha256:"): + case strings.HasSuffix(path, "/blobs/"+r.URL.Query().Get("digest")) || strings.Contains(path, "/blobs/sha256:") || strings.Contains(path, "/blobs/sha512:"): // Blob download: GET /v2/{name}/blobs/{digest} h.handleBlobDownload(w, r, path) case manifestPathPattern.MatchString(path): @@ -401,10 +398,14 @@ func (h *ContainerHandler) handleBlobDownload(w http.ResponseWriter, r *http.Req return } - h.proxy.Logger.Info("container blob request", "name", upstreamName, "digest", digest) + h.proxy.Logger.Debug("container blob request", "name", upstreamName, "digest", digest) filename := digest cached, err := h.proxy.GetCachedArtifact(r.Context(), "oci", cacheName, digest, filename) + if errors.Is(err, ErrVersionDenied) { + h.containerError(w, http.StatusForbidden, "DENIED", err.Error()) + return + } if err != nil { h.proxy.Logger.Error("failed to check blob cache", "error", err) h.containerError(w, http.StatusInternalServerError, "INTERNAL_ERROR", "failed to check blob cache") @@ -479,14 +480,17 @@ func (h *ContainerHandler) handleManifest(w http.ResponseWriter, r *http.Request return } - registryURL, upstreamName, _, ok := h.registryForRequest(r, name) + registryURL, upstreamName, cacheName, ok := h.registryForRequest(r, name) if !ok { h.containerError(w, http.StatusNotFound, "NAME_UNKNOWN", "unknown upstream registry") return } - h.proxy.Logger.Info("container manifest request", "name", upstreamName, "reference", reference) - h.serveManifest(w, r, registryURL, upstreamName, reference) + h.proxy.Logger.Debug("container manifest request", "name", upstreamName, "reference", reference) + if h.manifestDenied(w, cacheName, reference) { + return + } + h.serveManifest(w, r, registryURL, upstreamName, cacheName, reference) } // handleTagsList caches tag list responses for offline OCI pulls. @@ -688,7 +692,7 @@ func (h *ContainerHandler) containerError(w http.ResponseWriter, status int, cod } // blobPathPattern matches blob paths: {name}/blobs/{digest} -var blobPathPattern = regexp.MustCompile(`^(.+)/blobs/(sha256:[a-f0-9]+)$`) +var blobPathPattern = regexp.MustCompile(`^(.+)/blobs/(sha256:[a-f0-9]{64}|sha512:[a-f0-9]{128})$`) // parseBlobPath extracts repository name and digest from a blob path. func (h *ContainerHandler) parseBlobPath(path string) (name, digest string) { diff --git a/internal/handler/container_manifest.go b/internal/handler/container_manifest.go index 902ad3a..6d129d0 100644 --- a/internal/handler/container_manifest.go +++ b/internal/handler/container_manifest.go @@ -49,100 +49,41 @@ type cachedContainerManifest struct { fetchedAt time.Time } -func (h *ContainerHandler) serveManifest(w http.ResponseWriter, r *http.Request, registryURL, name, reference string) { +// serveManifest serves a manifest unless the denylist names the digest it +// resolves to under cacheName, the name blobs are stored under. +func (h *ContainerHandler) serveManifest(w http.ResponseWriter, r *http.Request, registryURL, name, cacheName, reference string) { accept := containerManifestAccept(r) - cacheAccept := normalizeContainerManifestAccept(accept) - cached, fromFallback := h.loadContainerManifestForAccept(r.Context(), registryURL, name, reference, accept, cacheAccept) - - immutable := manifestDigestReferencePattern.MatchString(reference) - if cached != nil && (immutable || h.containerManifestFresh(cached)) { - writeContainerManifest(w, r, cached, false) + req := manifestRequest{ + registryURL: registryURL, + name: name, + reference: reference, + accept: accept, + cacheAccept: normalizeContainerManifestAccept(accept), + method: r.Method, + } + cached, _ := h.loadContainerManifestForAccept(r.Context(), registryURL, name, reference, req.accept, req.cacheAccept) + if cached != nil && (req.immutable() || h.containerManifestFresh(cached)) { + h.writeManifest(w, r, cacheName, cached, false) return } - upstreamURL := fmt.Sprintf("%s/v2/%s/manifests/%s", registryURL, name, reference) - req, err := http.NewRequestWithContext(r.Context(), r.Method, upstreamURL, nil) - if err != nil { - h.containerError(w, http.StatusInternalServerError, "INTERNAL_ERROR", "failed to create request") - return + outcome := h.coalescedManifest(r.Context(), req) + switch { + case outcome.manifest != nil: + h.writeManifest(w, r, cacheName, outcome.manifest, false) + case outcome.relay != nil: + outcome.relay.write(h.proxy, w, r) + case outcome.digestInvalid: + h.containerError(w, http.StatusBadGateway, "DIGEST_INVALID", "manifest digest verification failed") + default: + h.serveStaleManifestOrError(w, r, cacheName, reference, cached, outcome.err) } - req.Header.Set("Accept", accept) - if cached != nil && cached.etag != "" { - req.Header.Set("If-None-Match", cached.etag) - } - - resp, err := h.proxy.HTTPClient.Do(req) - if err != nil { - h.serveStaleManifestOrError(w, r, reference, cached, err) - return - } - defer func() { _ = resp.Body.Close() }() - - if resp.StatusCode == http.StatusNotModified && cached != nil { - cached.fetchedAt = time.Now() - if fromFallback { - // The shared entry holds another representation for other - // clients; only this client's own entries are refreshed. - h.storeContainerManifestLegacyEntries(r.Context(), registryURL, name, reference, accept, cacheAccept, cached) - } else { - h.storeContainerManifestForAccept(r.Context(), registryURL, name, reference, accept, cacheAccept, cached) - } - writeContainerManifest(w, r, cached, false) - return - } - if resp.StatusCode != http.StatusOK { - if shouldServeStaleManifest(resp.StatusCode) && (cached != nil || referrersTagPattern.MatchString(reference)) { - h.serveStaleManifestOrError(w, r, reference, cached, fmt.Errorf("upstream status %d", resp.StatusCode)) - return - } - h.proxy.relayResponse(w, r, resp, copyContainerManifestHeaders) - return - } - - if r.Method == http.MethodHead { - h.proxy.relayResponse(w, r, resp, copyContainerManifestHeaders) - return - } - - body, err := h.proxy.ReadMetadata(resp.Body) - if err != nil { - h.serveStaleManifestOrError(w, r, reference, cached, fmt.Errorf("reading manifest: %w", err)) - return - } - computedDigest := sha256Digest(body) - contentDigest := resp.Header.Get("Docker-Content-Digest") - for _, expected := range []string{reference, contentDigest} { - if strings.HasPrefix(expected, "sha256:") && expected != computedDigest { - h.proxy.Logger.Error("upstream manifest failed digest verification", - "name", name, "reference", reference, "expected", expected, "actual", computedDigest) - h.containerError(w, http.StatusBadGateway, "DIGEST_INVALID", "manifest digest verification failed") - return - } - } - if contentDigest == "" { - contentDigest = computedDigest - } - - manifest := &cachedContainerManifest{ - body: body, - contentType: resp.Header.Get(headerContentType), - contentDigest: contentDigest, - etag: resp.Header.Get(headerETag), - size: int64(len(body)), - lastModified: parseHTTPTime(resp.Header.Get(headerLastModified)), - fetchedAt: time.Now(), - } - h.storeContainerManifestForAccept(r.Context(), registryURL, name, reference, accept, cacheAccept, manifest) - if manifest.contentDigest != reference && manifestDigestReferencePattern.MatchString(manifest.contentDigest) { - h.storeContainerManifestForAccept(r.Context(), registryURL, name, manifest.contentDigest, accept, cacheAccept, manifest) - } - writeContainerManifest(w, r, manifest, false) } -func (h *ContainerHandler) serveStaleManifestOrError(w http.ResponseWriter, r *http.Request, reference string, cached *cachedContainerManifest, err error) { +func (h *ContainerHandler) serveStaleManifestOrError(w http.ResponseWriter, r *http.Request, cacheName, reference string, cached *cachedContainerManifest, err error) { if cached != nil { h.proxy.Logger.Warn("upstream manifest fetch failed, serving stale cache", "error", err) - writeContainerManifest(w, r, cached, true) + h.writeManifest(w, r, cacheName, cached, true) return } if referrersTagPattern.MatchString(reference) { @@ -157,6 +98,25 @@ func (h *ContainerHandler) serveStaleManifestOrError(w http.ResponseWriter, r *h h.containerError(w, http.StatusBadGateway, "INTERNAL_ERROR", "failed to fetch from upstream") } +// manifestDenied writes a 403 and reports true when the denylist names +// reference, a tag or digest, under the repository's cache name. +func (h *ContainerHandler) manifestDenied(w http.ResponseWriter, cacheName, reference string) bool { + if reference == "" || !h.proxy.versionDenied("oci", cacheName, reference) { + return false + } + h.containerError(w, http.StatusForbidden, "DENIED", + ErrVersionDenied.Error()+": "+canonicalVersionPURL("oci", cacheName, reference)) + return true +} + +// writeManifest writes manifest unless the denylist names its digest. +func (h *ContainerHandler) writeManifest(w http.ResponseWriter, r *http.Request, cacheName string, manifest *cachedContainerManifest, stale bool) { + if h.manifestDenied(w, cacheName, manifest.contentDigest) { + return + } + writeContainerManifest(w, r, manifest, stale) +} + func (h *ContainerHandler) containerManifestFresh(manifest *cachedContainerManifest) bool { return h.proxy.MetadataTTL > 0 && !manifest.fetchedAt.IsZero() && time.Since(manifest.fetchedAt) < h.proxy.MetadataTTL } @@ -276,6 +236,7 @@ func (h *ContainerHandler) loadContainerManifest(ctx context.Context, cacheKey s if err != nil { return nil, err } + h.proxy.recordMetadataRead(entry) manifest := &cachedContainerManifest{body: body, size: int64(len(body))} if entry.ContentType.Valid { @@ -315,7 +276,10 @@ func writeContainerManifest(w http.ResponseWriter, r *http.Request, manifest *ca if manifest.contentType != "" { w.Header().Set(headerContentType, manifest.contentType) } - w.Header().Set(headerContentLength, strconv.FormatInt(manifest.size, 10)) + // A manifest known only from an upstream HEAD may lack a size. + if manifest.size >= 0 { + w.Header().Set(headerContentLength, strconv.FormatInt(manifest.size, 10)) + } if manifest.contentDigest != "" { w.Header().Set("Docker-Content-Digest", manifest.contentDigest) } diff --git a/internal/handler/container_manifest_fetch.go b/internal/handler/container_manifest_fetch.go new file mode 100644 index 0000000..7568671 --- /dev/null +++ b/internal/handler/container_manifest_fetch.go @@ -0,0 +1,366 @@ +package handler + +import ( + "bytes" + "context" + "fmt" + "io" + "net/http" + "strconv" + "strings" + "time" + + "github.com/git-pkgs/proxy/internal/metrics" +) + +// manifestRequest is one client manifest request as the upstream sees it. +type manifestRequest struct { + registryURL string + name string + reference string + accept string + cacheAccept string + method string +} + +func (req manifestRequest) immutable() bool { + return manifestDigestReferencePattern.MatchString(req.reference) +} + +// coalesceKey identifies requests that can share one upstream exchange. The +// normalized Accept is part of it because registries answer a tag with an +// index or a single manifest depending on it, and the method because a HEAD +// never fetches a manifest body the client did not ask for. +func (req manifestRequest) coalesceKey() string { + return strings.Join([]string{containerManifestCacheEcosystem, req.method, req.registryURL, req.name, req.reference, req.cacheAccept}, "\x00") +} + +func (req manifestRequest) url(reference string) string { + return fmt.Sprintf("%s/v2/%s/manifests/%s", req.registryURL, req.name, reference) +} + +// manifestOutcome is what callers sharing a manifest request write. Exactly +// one of manifest, relay and digestInvalid is set; otherwise err is the +// upstream failure, answered from the caller's stale copy if it has one. +type manifestOutcome struct { + manifest *cachedContainerManifest + relay *capturedResponse + digestInvalid bool + err error +} + +// capturedResponse is an upstream response other than a manifest, such as a +// 404 or 401, read in full so every caller sharing the request can relay it. +// A body that could not be read to the end is relayed up to that point and +// then fails the same way, so clients still see the truncation. +type capturedResponse struct { + status int + header http.Header + body []byte + readErr error + trailer http.Header +} + +func (h *ContainerHandler) captureResponse(resp *http.Response) *capturedResponse { + captured := &capturedResponse{status: resp.StatusCode, header: resp.Header.Clone()} + if resp.Request != nil && resp.Request.Method == http.MethodHead { + return captured + } + limit := h.proxy.MetadataMaxSize + if limit <= 0 { + limit = defaultMetadataMaxSize + } + captured.body, captured.readErr = io.ReadAll(io.LimitReader(resp.Body, limit+1)) + if captured.readErr == nil && int64(len(captured.body)) > limit { + captured.body, captured.readErr = captured.body[:limit], ErrMetadataTooLarge + } + captured.trailer = resp.Trailer.Clone() + return captured +} + +type failingReader struct{ err error } + +func (f failingReader) Read([]byte) (int, error) { return 0, f.err } + +func (c *capturedResponse) write(p *Proxy, w http.ResponseWriter, r *http.Request) { + var body io.Reader = bytes.NewReader(c.body) + if c.readErr != nil { + body = io.MultiReader(body, failingReader{c.readErr}) + } + resp := &http.Response{ + StatusCode: c.status, + Header: c.header.Clone(), + Trailer: c.trailer.Clone(), + Body: io.NopCloser(body), + } + p.relayResponse(w, r, resp, copyContainerManifestHeaders) +} + +// coalescedManifest runs the upstream part of a manifest request once for +// concurrent callers with the same key. Like coalesceMetadata, it runs on a +// context detached from the first caller, and each waiter still leaves when +// its own context ends. The result is a whole manifest with its headers, +// which a metadataResult does not carry, hence the separate group. +func (h *ContainerHandler) coalescedManifest(ctx context.Context, req manifestRequest) manifestOutcome { + results := h.manifestFlight.DoChan(req.coalesceKey(), func() (any, error) { + return h.fetchManifest(context.WithoutCancel(ctx), req), nil + }) + select { + case <-ctx.Done(): + return manifestOutcome{err: ctx.Err()} + case res := <-results: + outcome, ok := res.Val.(manifestOutcome) + if !ok { + return manifestOutcome{err: errSharedFetchAbandoned} + } + return outcome + } +} + +// fetchManifest answers a manifest request that the cache could not. Other +// instances sharing the database take turns through a fetch lease, so a tag +// that expired everywhere at once is revalidated once. +func (h *ContainerHandler) fetchManifest(ctx context.Context, req manifestRequest) (outcome manifestOutcome) { + usable := func(m *cachedContainerManifest) bool { + return m != nil && (req.immutable() || h.containerManifestFresh(m)) + } + // A shared request that finished since the caller looked has refreshed + // the entry already. + cached, fromFallback := h.loadContainerManifestForAccept(ctx, req.registryURL, req.name, req.reference, req.accept, req.cacheAccept) + if usable(cached) { + return manifestOutcome{manifest: cached} + } + + // Without a TTL nothing another instance stores is fresh, so there is + // nothing to wait for. + if req.immutable() || h.proxy.MetadataTTL > 0 { + var stored *cachedContainerManifest + release, lease, err := h.proxy.awaitFetchLease(ctx, metrics.CacheKindMetadata, req.coalesceKey(), func() bool { + stored, _ = h.loadContainerManifestForAccept(ctx, req.registryURL, req.name, req.reference, req.accept, req.cacheAccept) + return usable(stored) + }) + if err != nil { + return manifestOutcome{err: err} + } + switch lease { + case leaseStored: + return manifestOutcome{manifest: stored} + case leaseFailed: + if cached != nil { + return manifestOutcome{err: errFetchFailedElsewhere} + } + case leaseFetch: + } + defer func() { release(outcome.err != nil) }() + } + + switch { + case req.method == http.MethodHead: + return h.headManifest(ctx, req, cached, fromFallback) + case req.immutable(): + return h.getManifest(ctx, req, req.reference, cached, fromFallback) + default: + return h.revalidateTag(ctx, req, cached, fromFallback) + } +} + +// revalidateTag answers a GET for a tag that is stale or not cached. Docker +// Hub counts manifest GETs against its pull limit but not HEADs, so a stale +// tag is resolved with a HEAD first and the manifest fetched by digest only +// when it is not cached yet. A registry whose HEAD gives no digest gets the +// GET for the tag, as before. A tag never seen is fetched with one GET: a +// HEAD first would only add a round trip. +func (h *ContainerHandler) revalidateTag(ctx context.Context, req manifestRequest, cached *cachedContainerManifest, fromFallback bool) manifestOutcome { + if cached == nil { + return h.getManifest(ctx, req, req.reference, nil, false) + } + resp, err := h.requestManifest(ctx, http.MethodHead, req, req.reference, "") + if err != nil { + return manifestOutcome{err: err} + } + _ = resp.Body.Close() + + digest := resp.Header.Get("Docker-Content-Digest") + switch { + case resp.StatusCode == http.StatusOK && manifestDigestReferencePattern.MatchString(digest): + if outcome, ok := h.tagFromCachedDigest(ctx, req, cached, fromFallback, resp, digest); ok { + return outcome + } + if outcome := h.getManifest(ctx, req, digest, nil, false); outcome.manifest != nil { + return outcome + } + // The tag may have moved again, or the registry may not serve + // manifests by digest to this client; ask for the tag itself. + case shouldServeStaleManifest(resp.StatusCode): + return manifestOutcome{err: fmt.Errorf("upstream status %d", resp.StatusCode)} + } + return h.getManifest(ctx, req, req.reference, cached, fromFallback) +} + +// headManifest answers a client HEAD. When the digest upstream names is +// cached, the tag entry is pointed at it, so the next GET is a cache hit. +// Otherwise the upstream headers are passed on and nothing is stored. +func (h *ContainerHandler) headManifest(ctx context.Context, req manifestRequest, cached *cachedContainerManifest, fromFallback bool) manifestOutcome { + resp, err := h.requestManifest(ctx, http.MethodHead, req, req.reference, "") + if err != nil { + return manifestOutcome{err: err} + } + _ = resp.Body.Close() + + digest := resp.Header.Get("Docker-Content-Digest") + switch { + case resp.StatusCode == http.StatusOK && manifestDigestReferencePattern.MatchString(digest): + if req.immutable() && digestMismatch(req.reference, digest) { + h.proxy.Logger.Error("upstream manifest HEAD names another digest", + "name", req.name, "reference", req.reference, "upstream", digest) + return manifestOutcome{digestInvalid: true} + } + if !req.immutable() { + if outcome, ok := h.tagFromCachedDigest(ctx, req, cached, fromFallback, resp, digest); ok { + return outcome + } + } + size := int64(-1) + if value := resp.Header.Get(headerContentLength); value != "" { + if parsed, err := strconv.ParseInt(value, 10, 64); err == nil { + size = parsed + } + } + return manifestOutcome{manifest: &cachedContainerManifest{ + contentType: resp.Header.Get(headerContentType), + contentDigest: digest, + etag: resp.Header.Get(headerETag), + size: size, + lastModified: parseHTTPTime(resp.Header.Get(headerLastModified)), + }} + case shouldServeStaleManifest(resp.StatusCode) && (cached != nil || referrersTagPattern.MatchString(req.reference)): + return manifestOutcome{err: fmt.Errorf("upstream status %d", resp.StatusCode)} + } + return manifestOutcome{relay: h.captureResponse(resp)} +} + +// digestMismatch reports whether two digests of the same algorithm differ. +// Digests of different algorithms can't be compared without the body. +func digestMismatch(requested, upstream string) bool { + reqAlg, reqHex, _ := strings.Cut(requested, ":") + upAlg, upHex, _ := strings.Cut(upstream, ":") + return reqAlg == upAlg && !strings.EqualFold(reqHex, upHex) +} + +// tagFromCachedDigest answers a tag from the cache once a HEAD named the +// digest it points to: the cached tag entry if the tag did not move, or the +// manifest stored under the new digest. It reports false when neither is +// cached. +func (h *ContainerHandler) tagFromCachedDigest(ctx context.Context, req manifestRequest, cached *cachedContainerManifest, fromFallback bool, resp *http.Response, digest string) (manifestOutcome, bool) { + if cached != nil && cached.contentDigest == digest { + cached.fetchedAt = time.Now() + h.refreshManifest(ctx, req, cached, fromFallback) + return manifestOutcome{manifest: cached}, true + } + + stored, err := h.loadContainerManifest(ctx, h.containerManifestSharedCacheKey(req.registryURL, req.name, digest, req.cacheAccept)) + if err != nil || stored == nil || stored.contentDigest != digest || !containerManifestCacheCompatible(req.accept, stored) { + return manifestOutcome{}, false + } + moved := *stored + moved.fetchedAt = time.Now() + if etag := resp.Header.Get(headerETag); etag != "" { + moved.etag = etag + } + if lastModified := parseHTTPTime(resp.Header.Get(headerLastModified)); !lastModified.IsZero() { + moved.lastModified = lastModified + } + h.storeContainerManifestForAccept(ctx, req.registryURL, req.name, req.reference, req.accept, req.cacheAccept, &moved) + return manifestOutcome{manifest: &moved}, true +} + +// refreshManifest stores cached again with its new fetch time. +func (h *ContainerHandler) refreshManifest(ctx context.Context, req manifestRequest, cached *cachedContainerManifest, fromFallback bool) { + if fromFallback { + // The shared entry holds another representation for other + // clients; only this client's own entries are refreshed. + h.storeContainerManifestLegacyEntries(ctx, req.registryURL, req.name, req.reference, req.accept, req.cacheAccept, cached) + return + } + h.storeContainerManifestForAccept(ctx, req.registryURL, req.name, req.reference, req.accept, req.cacheAccept, cached) +} + +// getManifest GETs fetchRef, the requested reference or the digest a tag +// resolved to, and stores the manifest under the requested reference and +// its digest. cached, if set, is revalidated with its ETag. +func (h *ContainerHandler) getManifest(ctx context.Context, req manifestRequest, fetchRef string, cached *cachedContainerManifest, fromFallback bool) manifestOutcome { + etag := "" + if cached != nil { + etag = cached.etag + } + resp, err := h.requestManifest(ctx, http.MethodGet, req, fetchRef, etag) + if err != nil { + return manifestOutcome{err: err} + } + defer func() { _ = resp.Body.Close() }() + + if resp.StatusCode == http.StatusNotModified && cached != nil { + cached.fetchedAt = time.Now() + h.refreshManifest(ctx, req, cached, fromFallback) + return manifestOutcome{manifest: cached} + } + if resp.StatusCode != http.StatusOK { + if shouldServeStaleManifest(resp.StatusCode) && (cached != nil || referrersTagPattern.MatchString(req.reference)) { + return manifestOutcome{err: fmt.Errorf("upstream status %d", resp.StatusCode)} + } + return manifestOutcome{relay: h.captureResponse(resp)} + } + + body, err := h.proxy.ReadMetadata(resp.Body) + if err != nil { + return manifestOutcome{err: fmt.Errorf("reading manifest: %w", err)} + } + contentDigest := resp.Header.Get("Docker-Content-Digest") + // The references fetched and stored under, and the digest the upstream + // says the manifest has, are all cache keys, so each digest among them + // must be the manifest's own. One the proxy can't compute is refused + // rather than cached unchecked. + for _, expected := range []string{req.reference, fetchRef, contentDigest} { + if !strings.Contains(expected, ":") { + continue + } + if err := verifyDigest(expected, body); err != nil { + h.proxy.Logger.Error("upstream manifest failed digest verification", + "name", req.name, "reference", req.reference, "expected", expected, "error", err) + return manifestOutcome{digestInvalid: true} + } + } + if contentDigest == "" { + contentDigest = sha256Digest(body) + } + + manifest := &cachedContainerManifest{ + body: body, + contentType: resp.Header.Get(headerContentType), + contentDigest: contentDigest, + etag: resp.Header.Get(headerETag), + size: int64(len(body)), + lastModified: parseHTTPTime(resp.Header.Get(headerLastModified)), + fetchedAt: time.Now(), + } + h.storeContainerManifestForAccept(ctx, req.registryURL, req.name, req.reference, req.accept, req.cacheAccept, manifest) + if manifest.contentDigest != req.reference && manifestDigestReferencePattern.MatchString(manifest.contentDigest) { + h.storeContainerManifestForAccept(ctx, req.registryURL, req.name, manifest.contentDigest, req.accept, req.cacheAccept, manifest) + } + return manifestOutcome{manifest: manifest} +} + +// requestManifest sends one manifest request upstream with the client's +// Accept header. The registry client adds credentials and follows bearer +// challenges for HEAD as for GET. +func (h *ContainerHandler) requestManifest(ctx context.Context, method string, req manifestRequest, reference, etag string) (*http.Response, error) { + upstream, err := http.NewRequestWithContext(ctx, method, req.url(reference), nil) + if err != nil { + return nil, fmt.Errorf("creating manifest request: %w", err) + } + upstream.Header.Set("Accept", req.accept) + if etag != "" { + upstream.Header.Set("If-None-Match", etag) + } + return h.proxy.HTTPClient.Do(upstream) +} diff --git a/internal/handler/container_manifest_revalidate_test.go b/internal/handler/container_manifest_revalidate_test.go new file mode 100644 index 0000000..abe0fc5 --- /dev/null +++ b/internal/handler/container_manifest_revalidate_test.go @@ -0,0 +1,422 @@ +package handler + +import ( + "io" + "net/http" + "net/http/httptest" + "strconv" + "strings" + "sync" + "testing" + "time" +) + +const revalidateRepo = "/v2/library/app/manifests/" + +// countingRegistry serves manifests by tag and digest and counts GET and HEAD +// requests per reference, since Docker Hub counts only GETs as pulls. +type countingRegistry struct { + server *httptest.Server + + mu sync.Mutex + docs map[string]string // by digest + tags map[string]string // tag -> digest + gets map[string]int + heads map[string]int + headAccept string + // headDigest is false for a registry whose HEAD has no + // Docker-Content-Digest. + headDigest bool + // hold delays each response until holdFor requests arrived, or + // holdTimeout passed, so concurrent callers overlap upstream. + holdFor int + holdTimeout time.Duration + arrived int + release chan struct{} +} + +func newCountingRegistry(t *testing.T) *countingRegistry { + t.Helper() + registry := &countingRegistry{ + docs: make(map[string]string), + tags: make(map[string]string), + gets: make(map[string]int), + heads: make(map[string]int), + headDigest: true, + release: make(chan struct{}), + } + registry.server = httptest.NewServer(http.HandlerFunc(registry.serve)) + t.Cleanup(registry.server.Close) + return registry +} + +func (c *countingRegistry) serve(w http.ResponseWriter, r *http.Request) { + reference, ok := strings.CutPrefix(r.URL.Path, revalidateRepo) + if !ok { + http.NotFound(w, r) + return + } + c.mu.Lock() + if r.Method == http.MethodHead { + c.heads[reference]++ + c.headAccept = r.Header.Get("Accept") + } else { + c.gets[reference]++ + } + hold := c.holdFor > 0 + if hold { + c.arrived++ + if c.arrived == c.holdFor { + close(c.release) + } + } + digest, isTag := c.tags[reference] + if !isTag { + digest = reference + } + body, found := c.docs[digest] + headDigest := c.headDigest + c.mu.Unlock() + + if hold { + select { + case <-c.release: + case <-time.After(c.holdTimeout): + } + } + if !found { + http.NotFound(w, r) + return + } + etag := `"` + digest + `"` + w.Header().Set("Content-Type", ociManifestMediaType) + w.Header().Set("ETag", etag) + if r.Method != http.MethodHead || headDigest { + w.Header().Set("Docker-Content-Digest", digest) + } + if r.Header.Get("If-None-Match") == etag { + w.WriteHeader(http.StatusNotModified) + return + } + w.Header().Set("Content-Length", strconv.Itoa(len(body))) + if r.Method != http.MethodHead { + _, _ = io.WriteString(w, body) + } +} + +// add stores a manifest and returns its digest. +func (c *countingRegistry) add(body string) string { + digest := sha256Digest([]byte(body)) + c.mu.Lock() + c.docs[digest] = body + c.mu.Unlock() + return digest +} + +// pointLatest points the latest tag at digest. +func (c *countingRegistry) pointLatest(digest string) { + c.mu.Lock() + c.tags["latest"] = digest + c.mu.Unlock() +} + +// counts returns the GETs and HEADs seen so far, all references together. +func (c *countingRegistry) counts() (gets, heads int) { + c.mu.Lock() + defer c.mu.Unlock() + for _, n := range c.gets { + gets += n + } + for _, n := range c.heads { + heads += n + } + return gets, heads +} + +func (c *countingRegistry) getsOf(reference string) int { + c.mu.Lock() + defer c.mu.Unlock() + return c.gets[reference] +} + +func newRevalidateTestHandler(t *testing.T, registry *countingRegistry) *ContainerHandler { + t.Helper() + proxy, _, _, _ := setupTestProxy(t) + proxy.HTTPClient = registry.server.Client() + proxy.MetadataTTL = time.Hour + return &ContainerHandler{proxy: proxy, registryURL: registry.server.URL, proxyURL: "http://localhost:8080"} +} + +// ageLatest moves the cached entry of the latest tag past the TTL. +func ageLatest(t *testing.T, h *ContainerHandler) { + t.Helper() + key := h.containerManifestSharedCacheKey(h.registryURL, "library/app", "latest", normalizeContainerManifestAccept(dockerManifestAccept)) + entry, err := h.proxy.DB.GetMetadataCache(containerManifestCacheEcosystem, key) + if err != nil || entry == nil { + t.Fatalf("cached tag row = %v, %v, want one", entry, err) + } + entry.FetchedAt.Time = time.Now().Add(-2 * time.Hour) + if err := h.proxy.DB.UpsertMetadataCache(entry); err != nil { + t.Fatalf("ageing cached tag: %v", err) + } +} + +func pullManifest(t *testing.T, h *ContainerHandler, method, reference string) *httptest.ResponseRecorder { + t.Helper() + request := httptest.NewRequest(method, "/library/app/manifests/"+reference, nil) + request.Header.Set("Accept", dockerManifestAccept) + response := httptest.NewRecorder() + h.Routes().ServeHTTP(response, request) + if response.Code != http.StatusOK { + t.Fatalf("%s %s status = %d: %s", method, reference, response.Code, response.Body.String()) + } + return response +} + +func manifestDoc(n string) string { + return `{"schemaVersion":2,"mediaType":"application/vnd.oci.image.manifest.v1+json","annotations":{"n":"` + n + `"}}` +} + +func TestContainerHandler_StaleTagUnchangedRevalidatesWithHead(t *testing.T) { + registry := newCountingRegistry(t) + digest := registry.add(manifestDoc("a")) + registry.pointLatest(digest) + h := newRevalidateTestHandler(t, registry) + + pullManifest(t, h, http.MethodGet, "latest") + ageLatest(t, h) + response := pullManifest(t, h, http.MethodGet, "latest") + + if response.Body.String() != manifestDoc("a") { + t.Errorf("body = %q, want the cached manifest", response.Body.String()) + } + if gets, heads := registry.counts(); gets != 1 || heads != 1 { + t.Errorf("upstream GETs = %d, HEADs = %d; want 1 GET for the first pull and 1 HEAD to revalidate", gets, heads) + } + registry.mu.Lock() + headAccept := registry.headAccept + registry.mu.Unlock() + if headAccept != dockerManifestAccept { + t.Errorf("HEAD Accept = %q, want the client's %q", headAccept, dockerManifestAccept) + } + // The HEAD refreshed the entry, so the next pull stays local. + pullManifest(t, h, http.MethodGet, "latest") + if gets, heads := registry.counts(); gets != 1 || heads != 1 { + t.Errorf("after a fresh pull: GETs = %d, HEADs = %d, want 1 and 1", gets, heads) + } +} + +func TestContainerHandler_StaleTagMovedToCachedDigestNeedsNoGet(t *testing.T) { + registry := newCountingRegistry(t) + first := registry.add(manifestDoc("a")) + second := registry.add(manifestDoc("b")) + registry.pointLatest(first) + h := newRevalidateTestHandler(t, registry) + + pullManifest(t, h, http.MethodGet, "latest") + pullManifest(t, h, http.MethodGet, second) + registry.pointLatest(second) + ageLatest(t, h) + + response := pullManifest(t, h, http.MethodGet, "latest") + if response.Body.String() != manifestDoc("b") { + t.Errorf("body = %q, want the manifest the tag moved to", response.Body.String()) + } + if got := response.Header().Get("Docker-Content-Digest"); got != second { + t.Errorf("Docker-Content-Digest = %q, want %q", got, second) + } + if gets, heads := registry.counts(); gets != 2 || heads != 1 { + t.Errorf("upstream GETs = %d, HEADs = %d; want only the 2 setup GETs and 1 HEAD", gets, heads) + } +} + +func TestContainerHandler_StaleTagMovedToNewDigestGetsByDigest(t *testing.T) { + registry := newCountingRegistry(t) + first := registry.add(manifestDoc("a")) + registry.pointLatest(first) + h := newRevalidateTestHandler(t, registry) + + pullManifest(t, h, http.MethodGet, "latest") + second := registry.add(manifestDoc("b")) + registry.pointLatest(second) + ageLatest(t, h) + + response := pullManifest(t, h, http.MethodGet, "latest") + if response.Body.String() != manifestDoc("b") { + t.Errorf("body = %q, want the manifest the tag moved to", response.Body.String()) + } + if got := registry.getsOf("latest"); got != 1 { + t.Errorf("GETs of the tag = %d, want only the first pull's", got) + } + if got := registry.getsOf(second); got != 1 { + t.Errorf("GETs of the new digest = %d, want 1", got) + } + if _, heads := registry.counts(); heads != 1 { + t.Errorf("HEADs = %d, want 1", heads) + } + // Both the tag and the digest are now cached. + pullManifest(t, h, http.MethodGet, "latest") + pullManifest(t, h, http.MethodGet, second) + if gets, heads := registry.counts(); gets != 2 || heads != 1 { + t.Errorf("after cached pulls: GETs = %d, HEADs = %d, want 2 and 1", gets, heads) + } +} + +func TestContainerHandler_ConcurrentStaleTagRevalidatesOnce(t *testing.T) { + const pulls = 8 + registry := newCountingRegistry(t) + digest := registry.add(manifestDoc("a")) + registry.pointLatest(digest) + h := newRevalidateTestHandler(t, registry) + + pullManifest(t, h, http.MethodGet, "latest") + ageLatest(t, h) + setupGets, setupHeads := registry.counts() + registry.mu.Lock() + // Hold upstream answers until every pull reached upstream, or long + // enough that a coalesced request is the only one. + registry.holdFor = pulls + registry.holdTimeout = 300 * time.Millisecond + registry.mu.Unlock() + + var wg sync.WaitGroup + for range pulls { + wg.Go(func() { + request := httptest.NewRequest(http.MethodGet, "/library/app/manifests/latest", nil) + request.Header.Set("Accept", dockerManifestAccept) + response := httptest.NewRecorder() + h.Routes().ServeHTTP(response, request) + if response.Code != http.StatusOK || response.Body.String() != manifestDoc("a") { + t.Errorf("concurrent pull = %d %q", response.Code, response.Body.String()) + } + }) + } + wg.Wait() + + gets, heads := registry.counts() + if requests := gets - setupGets + heads - setupHeads; requests != 1 { + t.Errorf("upstream requests for %d concurrent pulls = %d, want 1", pulls, requests) + } +} + +func TestContainerHandler_StaleTagHeadWithoutDigestFallsBackToGet(t *testing.T) { + registry := newCountingRegistry(t) + first := registry.add(manifestDoc("a")) + registry.pointLatest(first) + registry.headDigest = false + h := newRevalidateTestHandler(t, registry) + + pullManifest(t, h, http.MethodGet, "latest") + second := registry.add(manifestDoc("b")) + registry.pointLatest(second) + ageLatest(t, h) + + response := pullManifest(t, h, http.MethodGet, "latest") + if response.Body.String() != manifestDoc("b") { + t.Errorf("body = %q, want the manifest the tag moved to", response.Body.String()) + } + if got := registry.getsOf("latest"); got != 2 { + t.Errorf("GETs of the tag = %d, want 2: the HEAD gave no digest", got) + } +} + +func TestContainerHandler_ClientHeadPointsTagAtCachedDigest(t *testing.T) { + registry := newCountingRegistry(t) + first := registry.add(manifestDoc("a")) + second := registry.add(manifestDoc("b")) + registry.pointLatest(first) + h := newRevalidateTestHandler(t, registry) + + pullManifest(t, h, http.MethodGet, "latest") + pullManifest(t, h, http.MethodGet, second) + registry.pointLatest(second) + ageLatest(t, h) + + head := pullManifest(t, h, http.MethodHead, "latest") + if got := head.Header().Get("Docker-Content-Digest"); got != second { + t.Errorf("HEAD Docker-Content-Digest = %q, want %q", got, second) + } + // The HEAD moved the cached tag, so the GET that follows it in a pull + // is a cache hit. + gets, heads := registry.counts() + response := pullManifest(t, h, http.MethodGet, "latest") + if response.Body.String() != manifestDoc("b") { + t.Errorf("body = %q, want the manifest the tag moved to", response.Body.String()) + } + if afterGets, afterHeads := registry.counts(); afterGets != gets || afterHeads != heads { + t.Errorf("GET after HEAD went upstream: GETs %d -> %d, HEADs %d -> %d", gets, afterGets, heads, afterHeads) + } +} + +func TestContainerHandler_ClientHeadOfUncachedDigestIsNotStored(t *testing.T) { + registry := newCountingRegistry(t) + first := registry.add(manifestDoc("a")) + registry.pointLatest(first) + h := newRevalidateTestHandler(t, registry) + + pullManifest(t, h, http.MethodGet, "latest") + second := registry.add(manifestDoc("b")) + registry.pointLatest(second) + ageLatest(t, h) + + head := pullManifest(t, h, http.MethodHead, "latest") + if got := head.Header().Get("Docker-Content-Digest"); got != second { + t.Errorf("HEAD Docker-Content-Digest = %q, want %q", got, second) + } + if got := head.Header().Get("Content-Length"); got != strconv.Itoa(len(manifestDoc("b"))) { + t.Errorf("HEAD Content-Length = %q, want the upstream manifest size", got) + } + if gets, _ := registry.counts(); gets != 1 { + t.Errorf("GETs = %d, want 1: a client HEAD must not cost a pull", gets) + } +} + +func TestContainerHandler_ConcurrentDigestMissFetchesOnce(t *testing.T) { + const pulls = 8 + registry := newCountingRegistry(t) + digest := registry.add(manifestDoc("a")) + registry.holdFor = pulls + registry.holdTimeout = 300 * time.Millisecond + h := newRevalidateTestHandler(t, registry) + + var wg sync.WaitGroup + for range pulls { + wg.Go(func() { + request := httptest.NewRequest(http.MethodGet, "/library/app/manifests/"+digest, nil) + request.Header.Set("Accept", dockerManifestAccept) + response := httptest.NewRecorder() + h.Routes().ServeHTTP(response, request) + if response.Code != http.StatusOK || response.Body.String() != manifestDoc("a") { + t.Errorf("concurrent pull = %d %q", response.Code, response.Body.String()) + } + }) + } + wg.Wait() + + if got := registry.getsOf(digest); got != 1 { + t.Errorf("upstream GETs for %d concurrent pulls by digest = %d, want 1", pulls, got) + } +} + +func TestContainerHandler_StaleTagDeletedUpstreamRelaysNotFound(t *testing.T) { + registry := newCountingRegistry(t) + registry.pointLatest(registry.add(manifestDoc("a"))) + h := newRevalidateTestHandler(t, registry) + + pullManifest(t, h, http.MethodGet, "latest") + registry.mu.Lock() + delete(registry.tags, "latest") + registry.mu.Unlock() + ageLatest(t, h) + + request := httptest.NewRequest(http.MethodGet, "/library/app/manifests/latest", nil) + request.Header.Set("Accept", dockerManifestAccept) + response := httptest.NewRecorder() + h.Routes().ServeHTTP(response, request) + if response.Code != http.StatusNotFound { + t.Fatalf("status = %d, want the upstream 404", response.Code) + } + if !strings.Contains(response.Body.String(), "not found") { + t.Errorf("body = %q, want the upstream error body", response.Body.String()) + } +} diff --git a/internal/handler/container_metadata.go b/internal/handler/container_metadata.go index 1168ebd..9e1b24a 100644 --- a/internal/handler/container_metadata.go +++ b/internal/handler/container_metadata.go @@ -57,5 +57,6 @@ func (h *ContainerHandler) loadContainerMetadata(ctx context.Context, ecosystem, if err != nil { return nil, nil, err } + h.proxy.recordMetadataRead(entry) return entry, body, nil } diff --git a/internal/handler/container_mirror.go b/internal/handler/container_mirror.go index cb98a97..f19ac73 100644 --- a/internal/handler/container_mirror.go +++ b/internal/handler/container_mirror.go @@ -11,7 +11,11 @@ import ( "regexp" "slices" "strings" + "sync" + "sync/atomic" "time" + + "golang.org/x/sync/errgroup" ) const ( @@ -19,6 +23,9 @@ const ( maxMirrorIndexDepth = 2 // mirrorErrorBodyLimit bounds how much of an error response is quoted. mirrorErrorBodyLimit = 200 + // mirrorBlobConcurrency is how many blobs of one manifest are fetched at + // once, as many as a Docker pull fetches by default. + mirrorBlobConcurrency = 3 dockerReferenceTypeAnnotation = "vnd.docker.reference.type" dockerReferenceDigestAnnotation = "vnd.docker.reference.digest" @@ -29,7 +36,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}$`) + mirrorDigestPattern = regexp.MustCompile(`^(sha256:[a-f0-9]{64}|sha512:[a-f0-9]{128})$`) ) // dockerHubMirrorAliases are registry hosts that name Docker Hub in image @@ -325,7 +332,7 @@ func (m *imageMirror) requestTag(ctx context.Context, method, tag, accept string // mirrorManifest stores the manifest for reference through the handler's own // manifest route, then follows what it references. It returns the manifest -// digest. +// sha256 digest. func (m *imageMirror) mirrorManifest(ctx context.Context, reference string, depth int) (string, error) { cacheAccept := normalizeContainerManifestAccept(containerManifestAccept(&http.Request{Header: http.Header{}})) before, _ := m.h.loadContainerManifestForAccept(ctx, m.registryURL, m.upstreamName, reference, cacheAccept, cacheAccept) @@ -353,6 +360,9 @@ func (m *imageMirror) mirrorManifest(ctx context.Context, reference string, dept if before == nil || before.contentDigest != digest { m.result.Fetched++ } + // Tags resolve to sha256 digests, so a manifest asked for by another + // digest is tracked by its sha256 too. + digest = sha256Digest(response.body.Bytes()) if m.seen[digest] { return digest, nil } @@ -439,6 +449,7 @@ func (m *imageMirror) mirrorBlobs(ctx context.Context, manifest *ociManifest) er if manifest.Config != nil { blobs = append([]ociDescriptor{*manifest.Config}, blobs...) } + var digests []string for _, blob := range blobs { if len(blob.URLs) > 0 || strings.Contains(blob.MediaType, "nondistributable") || strings.Contains(blob.MediaType, "foreign") { m.result.Warnings = append(m.result.Warnings, fmt.Sprintf("skipped non-distributable layer %s", blob.Digest)) @@ -451,37 +462,65 @@ func (m *imageMirror) mirrorBlobs(ctx context.Context, manifest *ociManifest) er continue } m.seen[blob.Digest] = true - if err := m.mirrorBlob(ctx, blob.Digest); err != nil { - return err - } + digests = append(digests, blob.Digest) } - return nil + + // Large layers take most of the time, so they are fetched side by side. + // A failure starts no further blobs but lets those in flight finish + // rather than cancelling them: a client pull may share their fetch, and + // they would have to be fetched again next run. + var mu sync.Mutex + var failed atomic.Bool + var g errgroup.Group + g.SetLimit(mirrorBlobConcurrency) + for _, digest := range digests { + g.Go(func() error { + if failed.Load() { + return nil + } + size, fetched, err := m.mirrorBlob(ctx, digest) + if err != nil { + failed.Store(true) + return err + } + if !fetched { + return nil + } + mu.Lock() + m.result.Fetched++ + m.result.Bytes += size + mu.Unlock() + return nil + }) + } + return g.Wait() } -// mirrorBlob stores a blob under the same identity handleBlobDownload uses. -func (m *imageMirror) mirrorBlob(ctx context.Context, digest string) error { +// mirrorBlob stores a blob under the same identity handleBlobDownload uses, +// and returns its size when it had to be fetched. +func (m *imageMirror) mirrorBlob(ctx context.Context, digest string) (int64, bool, error) { proxy := m.h.proxy - cached, err := proxy.GetCachedArtifact(ctx, "oci", m.cacheName, digest, digest) + cached, err := proxy.HasCachedArtifact(ctx, "oci", m.cacheName, digest, digest) if err != nil { - return fmt.Errorf("blob %s: %w", digest, err) + return 0, false, fmt.Errorf("blob %s: %w", digest, err) } - if cached != nil { - if cached.Reader != nil { - _ = cached.Reader.Close() + if cached { + // Not a cache hit, so LRU eviction still sees the image as unused, + // but retention keeps it while the schedule does. + if err := proxy.MarkMirrored("oci", m.cacheName, digest, digest); err != nil { + return 0, false, fmt.Errorf("blob %s: %w", digest, err) } - return nil + return 0, false, nil } result, err := proxy.GetOrFetchArtifactFromURLWithDigest(ctx, "oci", m.cacheName, digest, digest, fmt.Sprintf("%s/v2/%s/blobs/%s", m.registryURL, m.upstreamName, digest), digest) if err != nil { - return fmt.Errorf("blob %s: %w", digest, err) + return 0, false, fmt.Errorf("blob %s: %w", digest, err) } if result.Reader != nil { _ = result.Reader.Close() } - m.result.Fetched++ - m.result.Bytes += result.Artifact.Size - return nil + return result.Artifact.Size, true, nil } // mirrorResponse collects the handler's manifest response in memory. diff --git a/internal/handler/container_mirror_test.go b/internal/handler/container_mirror_test.go index 332851a..34af48c 100644 --- a/internal/handler/container_mirror_test.go +++ b/internal/handler/container_mirror_test.go @@ -2,15 +2,21 @@ package handler import ( "context" + "crypto/sha512" + "database/sql" + "encoding/hex" "encoding/json" "io" "net/http" "net/http/httptest" "net/url" + "slices" "strconv" "strings" + "sync" "sync/atomic" "testing" + "time" "github.com/git-pkgs/registries/fetch" ) @@ -18,8 +24,10 @@ import ( // fakeImageRegistry serves manifests and blobs of a small multi-arch image, // a single-arch image and a moved tag. It fails with 503 once offline. type fakeImageRegistry struct { - server *httptest.Server - offline atomic.Bool + server *httptest.Server + offline atomic.Bool + // mu guards manifests against a test changing it while blobs are served. + mu sync.RWMutex manifests map[string]fakeManifest blobs map[string]string blobGets atomic.Int32 @@ -29,6 +37,9 @@ type fakeImageRegistry struct { truncateManifests atomic.Bool // onBlob, if set, runs before a blob is served. onBlob func(path string) + // sha512Digests makes manifests requested by a sha512 digest name that + // digest in Docker-Content-Digest, as registries do. + sha512Digests bool } type fakeImage struct { @@ -116,9 +127,15 @@ func newFakeImageRegistry(t *testing.T) (*fakeImageRegistry, fakeImage) { http.Error(w, "offline", http.StatusServiceUnavailable) return } - if doc, ok := r.manifests[req.URL.Path]; ok { + r.mu.RLock() + doc, ok := r.manifests[req.URL.Path] + r.mu.RUnlock() + if ok { w.Header().Set("Content-Type", doc.contentType) w.Header().Set("Docker-Content-Digest", sha256Digest([]byte(doc.body))) + if _, ref, _ := strings.Cut(req.URL.Path, "/manifests/"); r.sha512Digests && strings.HasPrefix(ref, "sha512:") { + w.Header().Set("Docker-Content-Digest", ref) + } if req.Method == http.MethodGet && !strings.Contains(req.URL.Path, "/manifests/sha256:") { r.tagGets.Add(1) } @@ -431,7 +448,9 @@ func TestMirrorImageKeepsTagMovedByPullDuringWalk(t *testing.T) { var once atomic.Bool registry.onBlob = func(string) { if once.CompareAndSwap(false, true) { + registry.mu.Lock() registry.manifests["/v2/team/app/manifests/single"] = moved + registry.mu.Unlock() if response := pull(t, h, "/team/app/manifests/single", dockerManifestAccept); response.Code != http.StatusOK { t.Errorf("client pull during the walk: status %d", response.Code) } @@ -450,3 +469,217 @@ func TestMirrorImageKeepsTagMovedByPullDuringWalk(t *testing.T) { t.Errorf("offline tag points to %s, want the newer target %s", sha256Digest(response.Body.Bytes()), image.amd64Digest) } } + +func TestMirrorImageCountsNoCacheHits(t *testing.T) { + registry, _ := newFakeImageRegistry(t) + proxy := newMirrorTestProxy(t, registry) + h := NewContainerHandlerWithRegistry(proxy, "http://proxy.example", registry.server.URL) + ref := ImageRef{Name: "team/app", References: []string{"multi"}} + + if _, err := h.MirrorImage(context.Background(), ref, nil); err != nil { + t.Fatalf("first MirrorImage: %v", err) + } + var hits int + var lastAccess sql.NullString + if err := proxy.DB.QueryRow("SELECT COALESCE(SUM(hit_count), 0), MAX(last_accessed_at) FROM artifacts").Scan(&hits, &lastAccess); err != nil { + t.Fatal(err) + } + if _, err := h.MirrorImage(context.Background(), ref, nil); err != nil { + t.Fatalf("second MirrorImage: %v", err) + } + var hitsAfter int + var lastAccessAfter sql.NullString + if err := proxy.DB.QueryRow("SELECT COALESCE(SUM(hit_count), 0), MAX(last_accessed_at) FROM artifacts").Scan(&hitsAfter, &lastAccessAfter); err != nil { + t.Fatal(err) + } + if hitsAfter != hits || lastAccessAfter != lastAccess { + t.Errorf("second run changed hits %d -> %d and last access %v -> %v, want no change", hits, hitsAfter, lastAccess, lastAccessAfter) + } +} + +// A scheduled image that no client pulls keeps its blobs: a mirror run that +// finds them cached holds them back from retention, though not from LRU +// eviction, which TestMirrorImageCountsNoCacheHits covers. +func TestMirrorImageKeepsCachedBlobsFromRetention(t *testing.T) { + registry, _ := newFakeImageRegistry(t) + proxy := newMirrorTestProxy(t, registry) + h := NewContainerHandlerWithRegistry(proxy, "http://proxy.example", registry.server.URL) + ref := ImageRef{Name: "team/app", References: []string{"multi"}} + + if _, err := h.MirrorImage(context.Background(), ref, nil); err != nil { + t.Fatalf("first MirrorImage: %v", err) + } + old := time.Now().Add(-30 * 24 * time.Hour).UTC() + if _, err := proxy.DB.Exec(proxy.DB.Rebind("UPDATE artifacts SET fetched_at = ?, last_accessed_at = ?"), old, old); err != nil { + t.Fatal(err) + } + cutoff := time.Now().Add(-14 * 24 * time.Hour) + maxID, err := proxy.DB.MaxArtifactID() + if err != nil { + t.Fatal(err) + } + if candidates, err := proxy.DB.GetRetentionCandidates(0, maxID, cutoff); err != nil || len(candidates) == 0 { + t.Fatalf("before the second run: %d candidates, err %v; want the aged blobs", len(candidates), err) + } + + if _, err := h.MirrorImage(context.Background(), ref, nil); err != nil { + t.Fatalf("second MirrorImage: %v", err) + } + candidates, err := proxy.DB.GetRetentionCandidates(0, maxID, cutoff) + if err != nil { + t.Fatal(err) + } + if len(candidates) != 0 { + t.Errorf("after the second run %d blobs are retention candidates, want none", len(candidates)) + } +} + +func TestMirrorImageRefetchesBlobMissingFromStorage(t *testing.T) { + registry, image := newFakeImageRegistry(t) + proxy := newMirrorTestProxy(t, registry) + h := NewContainerHandlerWithRegistry(proxy, "http://proxy.example", registry.server.URL) + ref := ImageRef{Name: "team/app", References: []string{"multi"}} + + if _, err := h.MirrorImage(context.Background(), ref, nil); err != nil { + t.Fatalf("first MirrorImage: %v", err) + } + var path string + if err := proxy.DB.QueryRow("SELECT storage_path FROM artifacts WHERE filename = ?", image.amd64Layer).Scan(&path); err != nil { + t.Fatal(err) + } + if err := proxy.Storage.Delete(context.Background(), path); err != nil { + t.Fatal(err) + } + gets := registry.blobGets.Load() + if _, err := h.MirrorImage(context.Background(), ref, nil); err != nil { + t.Fatalf("second MirrorImage: %v", err) + } + if got := registry.blobGets.Load() - gets; got != 1 { + t.Errorf("second run fetched %d blobs, want the one missing from storage", got) + } +} + +func TestMirrorImageFetchesBlobsConcurrently(t *testing.T) { + registry, _ := newFakeImageRegistry(t) + proxy := newMirrorTestProxy(t, registry) + h := NewContainerHandlerWithRegistry(proxy, "http://proxy.example", registry.server.URL) + + // "single" has a config and a layer blob. Each request waits until the + // other is in flight too, or gives up after a while. + var inFlight atomic.Int32 + var concurrent atomic.Bool + both := make(chan struct{}) + var once sync.Once + registry.onBlob = func(string) { + defer inFlight.Add(-1) + if inFlight.Add(1) >= 2 { + concurrent.Store(true) + once.Do(func() { close(both) }) + } + select { + case <-both: + case <-time.After(2 * time.Second): + } + } + result, err := h.MirrorImage(context.Background(), ImageRef{Name: "team/app", References: []string{"single"}}, nil) + if err != nil { + t.Fatalf("MirrorImage: %v", err) + } + if !concurrent.Load() { + t.Error("blobs were fetched one after another, want them fetched concurrently") + } + if result.Fetched != 3 { + t.Errorf("fetched = %d, want the manifest and its two blobs", result.Fetched) + } +} + +// TestMirrorImageBlobFailureKeepsOtherFetches checks that a blob failing +// doesn't cancel the blobs already being fetched: their fetch may be shared +// with a client pull, which would fail with it, and the next run would have +// to fetch them again. +func TestMirrorImageBlobFailureKeepsOtherFetches(t *testing.T) { + registry, image := newFakeImageRegistry(t) + proxy := newMirrorTestProxy(t, registry) + h := NewContainerHandlerWithRegistry(proxy, "http://proxy.example", registry.server.URL) + + // The config blob is gone upstream; the layer is still being sent when + // its 404 arrives. + for path := range registry.blobs { + if !strings.HasSuffix(path, image.singleLayer) { + delete(registry.blobs, path) + } + } + registry.onBlob = func(string) { time.Sleep(300 * time.Millisecond) } + + if _, err := h.MirrorImage(context.Background(), ImageRef{Name: "team/app", References: []string{"single"}}, nil); err == nil { + t.Fatal("MirrorImage succeeded with a blob missing upstream") + } + registry.offline.Store(true) + if response := pull(t, h, "/team/app/blobs/"+image.singleLayer, ""); response.Code != http.StatusOK { + t.Errorf("layer fetched alongside the failing blob: status %d, want it cached", response.Code) + } +} + +func TestMirrorImageAcceptsSHA512Blobs(t *testing.T) { + registry, image := newFakeImageRegistry(t) + const layer = "sha512 layer" + sum := sha512.Sum512([]byte(layer)) + layerDigest := "sha512:" + hex.EncodeToString(sum[:]) + body, err := json.Marshal(map[string]any{ + "schemaVersion": 2, "mediaType": ociManifestMediaType, + "config": map[string]any{"mediaType": "application/vnd.oci.image.config.v1+json", "digest": image.singleLayer}, + "layers": []map[string]any{{"mediaType": "application/vnd.oci.image.layer.v1.tar+gzip", "digest": layerDigest}}, + }) + if err != nil { + t.Fatal(err) + } + registry.mu.Lock() + registry.manifests["/v2/team/app/manifests/sha512"] = fakeManifest{contentType: ociManifestMediaType, body: string(body)} + registry.blobs["/v2/team/app/blobs/"+layerDigest] = layer + registry.mu.Unlock() + + proxy := newMirrorTestProxy(t, registry) + h := NewContainerHandlerWithRegistry(proxy, "http://proxy.example", registry.server.URL) + if _, err := h.MirrorImage(context.Background(), ImageRef{Name: "team/app", References: []string{"sha512"}}, nil); err != nil { + t.Fatalf("MirrorImage: %v", err) + } + cached, err := proxy.GetCachedArtifact(t.Context(), "oci", "team/app", layerDigest, layerDigest) + if err != nil || cached == nil { + t.Fatalf("sha512 layer not cached: %v, %v", cached, err) + } + if cached.Reader != nil { + _ = cached.Reader.Close() + } +} + +// TestMirrorImageSHA512ReferenceMatchesTag checks that mirroring a tag +// pinned by a sha512 digest compares it with the tag's manifest by sha512, +// so an unmoved tag is neither reported as moved nor counted twice. +func TestMirrorImageSHA512ReferenceMatchesTag(t *testing.T) { + mirror := func(t *testing.T, sha512Ref bool) ImageResult { + registry, image := newFakeImageRegistry(t) + reference := image.singleDigest + if sha512Ref { + body := registry.manifests["/v2/team/app/manifests/single"].body + sum := sha512.Sum512([]byte(body)) + reference = "sha512:" + hex.EncodeToString(sum[:]) + registry.manifests["/v2/team/app/manifests/"+reference] = registry.manifests["/v2/team/app/manifests/single"] + registry.sha512Digests = true + } + proxy := newMirrorTestProxy(t, registry) + h := NewContainerHandlerWithRegistry(proxy, "http://proxy.example", registry.server.URL) + result, err := h.MirrorImage(context.Background(), ImageRef{Name: "team/app", References: []string{reference, "single"}}, nil) + if err != nil { + t.Fatalf("MirrorImage: %v", err) + } + return result + } + want := mirror(t, false) + got := mirror(t, true) + if !slices.Equal(got.Warnings, want.Warnings) { + t.Errorf("warnings = %v, want %v as for a sha256 reference", got.Warnings, want.Warnings) + } + if got.Fetched != want.Fetched { + t.Errorf("fetched = %d, want %d as for a sha256 reference", got.Fetched, want.Fetched) + } +} diff --git a/internal/handler/container_referrers.go b/internal/handler/container_referrers.go index 37261c5..94904f8 100644 --- a/internal/handler/container_referrers.go +++ b/internal/handler/container_referrers.go @@ -55,7 +55,7 @@ func (h *ContainerHandler) handleReferrers(w http.ResponseWriter, r *http.Reques return } - h.proxy.Logger.Info("container referrers request", "name", upstreamName, "digest", digest) + h.proxy.Logger.Debug("container referrers request", "name", upstreamName, "digest", digest) h.serveReferrers(w, r, registryURL, upstreamName, digest) } diff --git a/internal/handler/container_referrers_test.go b/internal/handler/container_referrers_test.go index 9201f62..77ef5c8 100644 --- a/internal/handler/container_referrers_test.go +++ b/internal/handler/container_referrers_test.go @@ -475,7 +475,7 @@ func TestContainerHandler_ReferrersFollowsNamespace(t *testing.T) { proxy, _, _, _ := setupTestProxy(t) proxy.HTTPClient = upstream.Client() proxy.MetadataTTL = time.Hour - h := NewContainerHandler(proxy, "http://proxy.example.test", map[string]string{"test": upstream.URL}) + h := NewContainerHandlerWithRegistry(proxy, "http://proxy.example.test", "", map[string]string{"test": upstream.URL}) routes := http.StripPrefix("/v2", h.Routes()) host := strings.TrimPrefix(upstream.URL, "http://") target := "/v2/owner/img/referrers/" + testReferrersSubject diff --git a/internal/handler/container_tags.go b/internal/handler/container_tags.go index 6142590..cca97b6 100644 --- a/internal/handler/container_tags.go +++ b/internal/handler/container_tags.go @@ -151,6 +151,7 @@ func (h *ContainerHandler) loadContainerTags(ctx context.Context, cacheKey strin if err != nil { return nil, err } + h.proxy.recordMetadataRead(entry) tags := &cachedContainerTags{body: body, contentType: contentTypeJSON, size: int64(len(body))} if entry.ContentType.Valid { diff --git a/internal/handler/container_test.go b/internal/handler/container_test.go index f00a7b5..9ba1535 100644 --- a/internal/handler/container_test.go +++ b/internal/handler/container_test.go @@ -1,6 +1,8 @@ package handler import ( + "crypto/sha512" + "encoding/hex" "encoding/json" "io" "net/http" @@ -10,11 +12,17 @@ import ( "testing" "time" + "github.com/git-pkgs/proxy/internal/database" upstreamhttp "github.com/git-pkgs/proxy/internal/httpclient" "github.com/git-pkgs/purl" "github.com/git-pkgs/registries/fetch" ) +var ( + testSHA256Digest = "sha256:" + strings.Repeat("ab", 32) + testSHA512Digest = "sha512:" + strings.Repeat("cd", 64) +) + func TestContainerHandler_parseBlobPath(t *testing.T) { h := &ContainerHandler{} @@ -24,19 +32,29 @@ func TestContainerHandler_parseBlobPath(t *testing.T) { wantDigest string }{ { - path: "library/nginx/blobs/sha256:abc123def456", + path: "library/nginx/blobs/" + testSHA256Digest, wantName: "library/nginx", - wantDigest: "sha256:abc123def456", + wantDigest: testSHA256Digest, }, { - path: "myorg/myrepo/blobs/sha256:0123456789abcdef", - wantName: "myorg/myrepo", - wantDigest: "sha256:0123456789abcdef", - }, - { - path: "deep/nested/repo/name/blobs/sha256:fedcba9876543210", + path: "deep/nested/repo/name/blobs/" + testSHA256Digest, wantName: "deep/nested/repo/name", - wantDigest: "sha256:fedcba9876543210", + wantDigest: testSHA256Digest, + }, + { + path: "myorg/myrepo/blobs/" + testSHA512Digest, + wantName: "myorg/myrepo", + wantDigest: testSHA512Digest, + }, + { + path: "library/nginx/blobs/sha256:abc123def456", + wantName: "", + wantDigest: "", + }, + { + path: "library/nginx/blobs/sha512:" + strings.Repeat("a", 64), + wantName: "", + wantDigest: "", }, { path: "invalid/path", @@ -277,7 +295,7 @@ func TestContainerHandler_TagsListRewritesRelativePaginationLinkForNamedRegistry proxy, _, _, _ := setupTestProxy(t) proxy.HTTPClient = upstream.Client() - h := NewContainerHandler(proxy, "http://proxy.example.test", map[string]string{"test": upstream.URL}) + h := NewContainerHandlerWithRegistry(proxy, "http://proxy.example.test", "", map[string]string{"test": upstream.URL}) routes := http.StripPrefix("/v2", h.Routes()) first := httptest.NewRecorder() @@ -326,7 +344,7 @@ func TestContainerHandler_NamedOCIRegistryServesHelmArtifacts(t *testing.T) { fetcher := fetch.NewFetcher(fetch.WithHTTPClient(upstream.Client()), fetch.WithMaxRetries(0)) proxy.Fetcher = fetcher t.Cleanup(func() { _ = fetcher.Close() }) - h := NewContainerHandler(proxy, "http://proxy.example", map[string]string{"ghcr": upstream.URL}) + h := NewContainerHandlerWithRegistry(proxy, "http://proxy.example", "", map[string]string{"ghcr": upstream.URL}) manifestResponse := httptest.NewRecorder() h.Routes().ServeHTTP(manifestResponse, @@ -723,6 +741,7 @@ func TestContainerHandler_BlobHead_CacheHitSkipsUpstreamAndAuth(t *testing.T) { } req := httptest.NewRequest(http.MethodHead, "/library/nginx/blobs/"+digest, nil) + req = req.WithContext(ServingHead(req.Context())) w := httptest.NewRecorder() h.Routes().ServeHTTP(w, req) @@ -746,7 +765,7 @@ func TestContainerHandler_BlobHead_CacheHitSkipsUpstreamAndAuth(t *testing.T) { } } -func TestContainerHandler_BlobHead_DirectServeRedirects(t *testing.T) { +func TestContainerHandler_BlobHead_DirectServeAnswersFromCache(t *testing.T) { proxy, db, store, fetcher := setupTestProxy(t) digest := "sha256:abc123def456abc123def456abc123def456abc123def456abc123def456abcd" seedPackage(t, db, store, "oci", "library/nginx", digest, digest, "cached blob") @@ -760,14 +779,21 @@ func TestContainerHandler_BlobHead_DirectServeRedirects(t *testing.T) { } req := httptest.NewRequest(http.MethodHead, "/library/nginx/blobs/"+digest, nil) + req = req.WithContext(ServingHead(req.Context())) w := httptest.NewRecorder() h.Routes().ServeHTTP(w, req) - if w.Code != http.StatusFound { - t.Fatalf("status = %d, want %d", w.Code, http.StatusFound) + if w.Code != http.StatusOK { + t.Fatalf("status = %d, want %d", w.Code, http.StatusOK) } - if got := w.Header().Get("Location"); got != store.signedURL { - t.Errorf("Location = %q, want %q", got, store.signedURL) + if got := w.Header().Get("Location"); got != "" { + t.Errorf("Location = %q, want empty", got) + } + if got := w.Header().Get("Docker-Content-Digest"); got != digest { + t.Errorf("Docker-Content-Digest = %q, want %q", got, digest) + } + if got := w.Header().Get("Content-Length"); got != "11" { + t.Errorf("Content-Length = %q, want %q", got, "11") } wantETag := `"` + sha256Hex("cached blob") + `"` if got := w.Header().Get("ETag"); got != wantETag { @@ -900,38 +926,82 @@ func TestContainerHandler_ManifestDigestMismatchIsNotCached(t *testing.T) { } } -func TestContainerHandler_ManifestNonSHA256DigestReferenceIsProxied(t *testing.T) { +// TestContainerHandler_ManifestDigestsAreVerified checks that a sha512 +// digest, in the reference or in Docker-Content-Digest, is verified like a +// sha256 one, and that a digest the proxy can't compute is refused rather +// than cached unverified. +func TestContainerHandler_ManifestDigestsAreVerified(t *testing.T) { manifest := `{"schemaVersion":2}` - sha512Reference := "sha512:" + strings.Repeat("a", 128) - sha512Header := "sha512:" + strings.Repeat("b", 128) - upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { - w.Header().Set("Content-Type", "application/vnd.oci.image.manifest.v1+json") - w.Header().Set("Docker-Content-Digest", sha512Header) - _, _ = io.WriteString(w, manifest) - })) - defer upstream.Close() + sum := sha512.Sum512([]byte(manifest)) + sha512Digest := "sha512:" + hex.EncodeToString(sum[:]) + otherSHA512 := "sha512:" + strings.Repeat("b", 128) + unsupported := "sha1:" + strings.Repeat("c", 40) - proxy, _, _, _ := setupTestProxy(t) - proxy.HTTPClient = upstream.Client() - h := &ContainerHandler{proxy: proxy, registryURL: upstream.URL} + tests := []struct { + name, reference, header string + wantOK bool + }{ + {"sha512 reference", sha512Digest, sha512Digest, true}, + {"sha512 reference without header", sha512Digest, "", true}, + {"tag with sha512 header", "latest", sha512Digest, true}, + {"mismatched sha512 reference", otherSHA512, "", false}, + {"tag with mismatched sha512 header", "latest", otherSHA512, false}, + {"unsupported reference", unsupported, "", false}, + {"tag with unsupported header", "latest", unsupported, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "application/vnd.oci.image.manifest.v1+json") + if tt.header != "" { + w.Header().Set("Docker-Content-Digest", tt.header) + } + _, _ = io.WriteString(w, manifest) + })) + defer upstream.Close() - for _, reference := range []string{sha512Reference, "latest"} { - t.Run(reference, func(t *testing.T) { + proxy, db, _, _ := setupTestProxy(t) + proxy.HTTPClient = upstream.Client() + h := &ContainerHandler{proxy: proxy, registryURL: upstream.URL} + req := httptest.NewRequest(http.MethodGet, "/library/nginx/manifests/"+tt.reference, nil) w := httptest.NewRecorder() - h.Routes().ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/library/nginx/manifests/"+reference, nil)) + h.Routes().ServeHTTP(w, req) + + if !tt.wantOK { + if w.Code != http.StatusBadGateway { + t.Fatalf("status = %d, want %d; body: %s", w.Code, http.StatusBadGateway, w.Body.String()) + } + requireManifestNotCached(t, h, db, upstream.URL, req, tt.reference, tt.header) + return + } if w.Code != http.StatusOK { t.Fatalf("status = %d, want %d; body: %s", w.Code, http.StatusOK, w.Body.String()) } if got := w.Body.String(); got != manifest { t.Errorf("body = %q, want %q", got, manifest) } - if got := w.Header().Get("Docker-Content-Digest"); got != sha512Header { - t.Errorf("Docker-Content-Digest = %q, want %q", got, sha512Header) - } }) } } +func requireManifestNotCached(t *testing.T, h *ContainerHandler, db *database.DB, upstreamURL string, req *http.Request, keys ...string) { + t.Helper() + accept := normalizeContainerManifestAccept(containerManifestAccept(req)) + for _, key := range keys { + if key == "" { + continue + } + entry, err := db.GetMetadataCache(containerManifestCacheEcosystem, + h.containerManifestSharedCacheKey(upstreamURL, "library/nginx", key, accept)) + if err != nil { + t.Fatalf("checking manifest cache: %v", err) + } + if entry != nil { + t.Errorf("manifest was cached under unverified %s", key) + } + } +} + func TestContainerHandler_ManifestTagWithInvalidDigestIsNotAliased(t *testing.T) { manifest := `{"schemaVersion":2}` invalidDigest := sha256Digest([]byte("different manifest")) @@ -1317,7 +1387,7 @@ func TestContainerHandler_ManifestByTag_StaleHeadChecksUpstream(t *testing.T) { } func TestContainerHandler_Routes_VersionCheck(t *testing.T) { - h := NewContainerHandler(nil, "http://localhost:8080") + h := NewContainerHandlerWithRegistry(nil, "http://localhost:8080", "") handler := h.Routes() if handler == nil { @@ -1429,3 +1499,52 @@ func TestContainerHandler_ManifestHonoursSeparateAcceptHeaders(t *testing.T) { t.Errorf("offline body = %q, want the cached manifest", w.Body.String()) } } + +func TestContainerHandler_BlobSHA512(t *testing.T) { + proxy, _, _, fetcher := setupTestProxy(t) + const blob = "sha512 layer" + fetcher.artifact = &fetch.Artifact{ + Body: io.NopCloser(strings.NewReader(blob)), + ContentType: "application/octet-stream", + } + sum := sha512.Sum512([]byte(blob)) + digest := "sha512:" + hex.EncodeToString(sum[:]) + h := &ContainerHandler{proxy: proxy, registryURL: "https://registry.example.test"} + + w := httptest.NewRecorder() + h.Routes().ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/library/app/blobs/"+digest, nil)) + + if w.Code != http.StatusOK { + t.Fatalf("status = %d, want %d; body: %s", w.Code, http.StatusOK, w.Body.String()) + } + if w.Body.String() != blob { + t.Errorf("body = %q, want %q", w.Body.String(), blob) + } + if got := w.Header().Get("Docker-Content-Digest"); got != digest { + t.Errorf("Docker-Content-Digest = %q, want %q", got, digest) + } +} + +func TestContainerHandler_HeadManifestByDigestChecksUpstreamDigest(t *testing.T) { + requested := sha256Digest([]byte("requested")) + other := sha256Digest([]byte("other")) + registry := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", ociManifestMediaType) + w.Header().Set("Docker-Content-Digest", other) + w.Header().Set("Content-Length", "5") + })) + defer registry.Close() + proxy, _, _, _ := setupTestProxy(t) + proxy.HTTPClient = registry.Client() + h := &ContainerHandler{proxy: proxy, registryURL: registry.URL} + + w := httptest.NewRecorder() + h.Routes().ServeHTTP(w, httptest.NewRequest(http.MethodHead, "/library/app/manifests/"+requested, nil)) + + if w.Code != http.StatusBadGateway { + t.Fatalf("status = %d, want %d", w.Code, http.StatusBadGateway) + } + if got := w.Header().Get("Docker-Content-Digest"); got == other { + t.Errorf("Docker-Content-Digest = %q, the upstream's other digest", got) + } +} diff --git a/internal/handler/cooldown_expiry.go b/internal/handler/cooldown_expiry.go new file mode 100644 index 0000000..c31ace8 --- /dev/null +++ b/internal/handler/cooldown_expiry.go @@ -0,0 +1,167 @@ +package handler + +import ( + "sync" + "time" + + "github.com/git-pkgs/cooldown" + "github.com/git-pkgs/proxy/internal/packageurl" +) + +// A rewrite made with cooldown on stays right until a version it held back +// leaves cooldown: versions it let through stay allowed as time passes, and +// new versions upstream change the document and so the cache key. So the +// cached rewrite expires when the earliest version it withheld becomes +// available, instead of after a fixed time. +// +// Handlers ask cooldown through Proxy.cooldown, which tells every rewrite +// running at that moment when a withheld version becomes available. A +// rewrite may hear of versions another rewrite withheld at the same time; +// that only makes it expire earlier than it has to, never later. + +// maxCooldownRewriteTTL is the longest a rewrite made with cooldown on is +// served, even when it held nothing back. +const maxCooldownRewriteTTL = 24 * time.Hour + +// minCooldownRewriteTTL is the shortest cap on a rewrite made with cooldown +// on, however short the cooldown. +const minCooldownRewriteTTL = time.Minute + +// cooldownRewriteTTL returns the longest a rewrite made with cooldown on is +// served: the shortest cooldown configured, between a minute and a day. It +// only matters when a rewrite held nothing back, or held back a version +// whose availability is unknown. +func (p *Proxy) cooldownRewriteTTL() time.Duration { + ttl := p.ShortestCooldown + switch { + case ttl <= 0 || ttl > maxCooldownRewriteTTL: + return maxCooldownRewriteTTL + case ttl < minCooldownRewriteTTL: + return minCooldownRewriteTTL + } + return ttl +} + +// cooldownWatch holds the rewrites running with cooldown on. +type cooldownWatch struct { + mu sync.Mutex + active map[*cooldownRecorder]struct{} +} + +// cooldownRecorder collects when the versions withheld during one rewrite +// become available. +type cooldownRecorder struct { + // earliest is when the first withheld version becomes available, or + // zero if none was withheld. + earliest time.Time + // unknown is set when a version was withheld without a time it becomes + // available. + unknown bool +} + +// watchCooldown starts recording the versions cooldown holds back for a +// rewrite about to run. unwatchCooldown ends it. +func (p *Proxy) watchCooldown() *cooldownRecorder { + rec := &cooldownRecorder{} + w := &p.cooldownWatch + w.mu.Lock() + defer w.mu.Unlock() + if w.active == nil { + w.active = make(map[*cooldownRecorder]struct{}) + } + w.active[rec] = struct{}{} + return rec +} + +func (p *Proxy) unwatchCooldown(rec *cooldownRecorder) { + w := &p.cooldownWatch + w.mu.Lock() + defer w.mu.Unlock() + delete(w.active, rec) +} + +// cooldownExpiry returns when a rewrite that started at start and recorded +// into rec should expire: when the first version it held back leaves +// cooldown, and no later than cooldownRewriteTTL after start. +func (p *Proxy) cooldownExpiry(rec *cooldownRecorder, start time.Time) time.Time { + w := &p.cooldownWatch + w.mu.Lock() + earliest, unknown := rec.earliest, rec.unknown + w.mu.Unlock() + + limit := start.Add(p.cooldownRewriteTTL()) + if unknown || earliest.IsZero() || earliest.After(limit) { + return limit + } + return earliest +} + +// withheld tells the running rewrites that a version is held back until +// availableAt, zero when that is unknown. +func (p *Proxy) withheld(availableAt time.Time) { + w := &p.cooldownWatch + w.mu.Lock() + defer w.mu.Unlock() + for rec := range w.active { + switch { + case availableAt.IsZero(): + rec.unknown = true + case rec.earliest.IsZero() || availableAt.Before(rec.earliest): + rec.earliest = availableAt + } + } +} + +// cooldown returns the proxy's cooldown policy, telling the running rewrites +// about each version it holds back. Handlers use it rather than p.Cooldown. +func (p *Proxy) cooldown() CooldownPolicy { //nolint:ireturn // nil when cooldown is not configured, as p.Cooldown is + if p.Cooldown == nil { + return nil + } + return recordingCooldown{p: p} +} + +// recordingCooldown is the proxy's cooldown policy, reporting the versions it +// holds back to the running rewrites. +type recordingCooldown struct { + p *Proxy +} + +func (r recordingCooldown) IsAllowed(ecosystem, packagePURL string, publishedAt time.Time) bool { + packagePURL = packageurl.PolicyPackageKey(packagePURL) + if r.p.Cooldown.IsAllowed(ecosystem, packagePURL, publishedAt) { + return true + } + r.p.withheld(r.availableAt(ecosystem, packagePURL, publishedAt)) + return false +} + +func (r recordingCooldown) Evaluate(ecosystem, packagePURL string, publishedAt, evaluatedAt time.Time) cooldown.Decision { + packagePURL = packageurl.PolicyPackageKey(packagePURL) + d := r.p.Cooldown.Evaluate(ecosystem, packagePURL, publishedAt, evaluatedAt) + if !d.Allowed { + r.p.withheld(d.AvailableAt) + } + return d +} + +func (r recordingCooldown) For(ecosystem, packagePURL string) time.Duration { + return r.p.Cooldown.For(ecosystem, packageurl.PolicyPackageKey(packagePURL)) +} + +func (r recordingCooldown) Enabled() bool { + return r.p.Cooldown.Enabled() +} + +// availableAt is when a version IsAllowed held back leaves cooldown, or zero +// when that is unknown. +func (r recordingCooldown) availableAt(ecosystem, packagePURL string, publishedAt time.Time) time.Time { + if publishedAt.IsZero() { + return time.Time{} + } + d := r.For(ecosystem, packagePURL) + if d <= 0 { + return time.Time{} + } + return publishedAt.Add(d) +} diff --git a/internal/handler/cooldown_expiry_test.go b/internal/handler/cooldown_expiry_test.go new file mode 100644 index 0000000..fd55845 --- /dev/null +++ b/internal/handler/cooldown_expiry_test.go @@ -0,0 +1,178 @@ +package handler + +import ( + "context" + "net/http" + "os" + "path/filepath" + "regexp" + "strings" + "testing" + "time" + + "github.com/git-pkgs/cooldown" +) + +// TestCachedRewrite_ExpiresWhenWithheldVersionIsAvailable checks that a +// rewrite which held a version back is cached until that version leaves +// cooldown, and no longer. +func TestCachedRewrite_ExpiresWhenWithheldVersionIsAvailable(t *testing.T) { + proxy, _, _, _ := setupTestProxy(t) + clock := &testClock{t: time.Now()} + proxy.now = clock.now + proxy.SetMetadataRewriteCacheSize(1 << 20) + proxy.Cooldown = &cooldown.Config{Default: "3d"} + purl := canonicalPackagePURL("npm", "left-pad") + // One version is 3d-5h old: it leaves cooldown in five hours. + published := clock.now().Add(-72*time.Hour + 5*time.Hour) + + var calls int + var rewrite keepingRewrite = func(b []byte) ([]byte, []string, error) { + calls++ + if proxy.cooldown().IsAllowed("npm", purl, published) { + return b, []string{"1.0.0", "1.1.0"}, nil + } + return b, []string{"1.0.0"}, nil + } + get := func() { + if _, err := proxy.cachedRewrite(context.Background(), "npm", "http://proxy", "left-pad", []byte("doc"), "", rewrite); err != nil { + t.Fatal(err) + } + } + + get() + clock.advance(5*time.Hour - time.Minute) + get() + if calls != 1 { + t.Errorf("rewrites before the withheld version is available = %d, want 1", calls) + } + clock.advance(time.Minute) + get() + if calls != 2 { + t.Errorf("rewrites once the withheld version is available = %d, want 2", calls) + } +} + +// TestCachedRewrite_NothingWithheldCachedForCap checks that a rewrite which +// held nothing back is cached for cooldownRewriteTTL. +func TestCachedRewrite_NothingWithheldCachedForCap(t *testing.T) { + proxy, _, _, _ := setupTestProxy(t) + clock := &testClock{t: time.Date(2026, 10, 10, 12, 0, 0, 0, time.UTC)} + proxy.now = clock.now + proxy.SetMetadataRewriteCacheSize(1 << 20) + proxy.Cooldown = &cooldown.Config{Default: "2h"} + proxy.ShortestCooldown = 2 * time.Hour + var r countingRewrite + + get := func() { + _, _ = proxy.cachedRewrite(context.Background(), "npm", "http://proxy", "left-pad", []byte("doc"), "", r.keeping) + } + get() + clock.advance(2*time.Hour - time.Second) + get() + if got := r.calls.Load(); got != 1 { + t.Errorf("rewrites within the cap = %d, want 1", got) + } + clock.advance(time.Second) + get() + if got := r.calls.Load(); got != 2 { + t.Errorf("rewrites after the cap = %d, want 2", got) + } +} + +// TestCooldownExpiry checks how one rewrite's recorded decisions set its +// expiry, including decisions made for other rewrites running at the same +// time, which may only make it expire earlier. +func TestCooldownExpiry(t *testing.T) { + p := &Proxy{Cooldown: &cooldown.Config{Default: "3d"}, ShortestCooldown: 72 * time.Hour} + // IsAllowed compares with the wall clock, so the times are relative to it. + start := time.Now() + limit := start.Add(24 * time.Hour) + purl := canonicalPackagePURL("npm", "left-pad") + + rec := p.watchCooldown() + if got := p.cooldownExpiry(rec, start); !got.Equal(limit) { + t.Errorf("nothing withheld: expiry = %v, want the cap %v", got, limit) + } + + other := p.watchCooldown() + p.cooldown().IsAllowed("npm", purl, start.Add(-60*time.Hour)) // available in 12h + p.unwatchCooldown(other) + p.cooldown().IsAllowed("npm", purl, start.Add(-66*time.Hour)) // available in 6h, after other ended + if got, want := p.cooldownExpiry(rec, start), start.Add(6*time.Hour); !got.Equal(want) { + t.Errorf("rec expiry = %v, want the earliest availability %v", got, want) + } + if got, want := p.cooldownExpiry(other, start), start.Add(12*time.Hour); !got.Equal(want) { + t.Errorf("other expiry = %v, want %v: decisions after it ended don't count", got, want) + } + + p.cooldown().Evaluate("npm", purl, start.Add(-71*time.Hour), start) // available in 1h + if got, want := p.cooldownExpiry(rec, start), start.Add(time.Hour); !got.Equal(want) { + t.Errorf("after Evaluate: expiry = %v, want %v", got, want) + } + p.unwatchCooldown(rec) + if len(p.cooldownWatch.active) != 0 { + t.Errorf("%d recorders left after unwatch", len(p.cooldownWatch.active)) + } +} + +// TestHandlersAskCooldownThroughRecorder checks that handlers make cooldown +// decisions through Proxy.cooldown. A decision made on Proxy.Cooldown +// directly would not reach the rewrites running, so a cached rewrite could +// keep hiding a version past its cooldown. +func TestHandlersAskCooldownThroughRecorder(t *testing.T) { + direct := regexp.MustCompile(`\.Cooldown\.(IsAllowed|Evaluate)\(|Cooldown:\s+\w+(\.\w+)*\.Cooldown\b`) + files, err := filepath.Glob("*.go") + if err != nil { + t.Fatal(err) + } + for _, f := range files { + if strings.HasSuffix(f, "_test.go") || f == "cooldown_expiry.go" { + continue + } + src, err := os.ReadFile(f) + if err != nil { + t.Fatal(err) + } + for i, line := range strings.Split(string(src), "\n") { + if direct.MatchString(line) { + t.Errorf("%s:%d asks Proxy.Cooldown directly; use Proxy.cooldown(): %s", f, i+1, strings.TrimSpace(line)) + } + } + } +} + +// TestHandlerRewriteExpiresWithWithheldVersion checks, through the handlers, +// that a cached rewrite expires when the version cooldown held back from it +// becomes available. +func TestHandlerRewriteExpiresWithWithheldVersion(t *testing.T) { + for _, c := range validatorCases { + t.Run(c.ecosystem, func(t *testing.T) { + u := cooldownUpstream(t) // the newest version was published 2h ago + proxy, _, clock := validatorProxyWithDB(t, u, time.Hour) + // Cooldown compares with the wall clock, so the proxy's clock + // follows it here. + clock.t = time.Now() + proxy.Cooldown = &cooldown.Config{Default: "3h"} + proxy.ShortestCooldown = 3 * time.Hour + handler := c.handler(proxy, u) + + if rec := serve(handler, c.path, nil); rec.Code != http.StatusOK { + t.Fatalf("status %d", rec.Code) + } + proxy.rewrites.mu.Lock() + defer proxy.rewrites.mu.Unlock() + if len(proxy.rewrites.entries) != 1 { + t.Fatalf("%d cached rewrites, want 1", len(proxy.rewrites.entries)) + } + for _, el := range proxy.rewrites.entries { + expires := el.Value.(*rewriteEntry).expires + // Published 2h ago with a 3h cooldown: available in an hour, + // to the second the publish time was given in. + if want := time.Now().Add(time.Hour); expires.Before(want.Add(-2*time.Second)) || expires.After(want.Add(time.Second)) { + t.Errorf("rewrite expires %v, want about %v when the withheld version is available", expires, want) + } + } + }) + } +} diff --git a/internal/handler/cooldown_fail_closed.go b/internal/handler/cooldown_fail_closed.go new file mode 100644 index 0000000..0dd2c36 --- /dev/null +++ b/internal/handler/cooldown_fail_closed.go @@ -0,0 +1,47 @@ +package handler + +import "net/http" + +// cooldownApplies reports whether cooldown withholds new versions of the +// package, taking package overrides and exemptions into account. +func (p *Proxy) cooldownApplies(ecosystem, name string) bool { + return p.cooldownEnabled() && p.cooldown().For(ecosystem, canonicalPackagePURL(ecosystem, name)) > 0 +} + +// mustFilterMetadata reports whether the package's metadata may have +// versions to withhold, by cooldown or by the denylist, and so must not be +// served as upstream sent it. +func (p *Proxy) mustFilterMetadata(ecosystem, name string) bool { + return p.cooldownApplies(ecosystem, name) || + len(p.Denylist.Versions(canonicalPackagePURL(ecosystem, name))) != 0 +} + +// writeCooldownLookupError answers a metadata request whose publish times +// couldn't be read: 503 with Retry-After when the rate limit gate held the +// request, 502 otherwise. +func (p *Proxy) writeCooldownLookupError(w http.ResponseWriter, ecosystem, name string, err error) { + if writeUpstreamHeld(w, err) { + return + } + p.Logger.Warn("cooldown: could not read publish times", + "ecosystem", ecosystem, "package", name, "error", err) + http.Error(w, "failed to check cooldown", http.StatusBadGateway) +} + +// serveCachedDespiteCooldownError serves a download from the cache when its +// publish time couldn't be read, and reports whether it did. A cached file was +// already let through once, so the proxy keeps serving it while the upstream +// is unreachable; only a cache miss fails. +func (p *Proxy) serveCachedDespiteCooldownError(w http.ResponseWriter, r *http.Request, ecosystem, name, version, filename string, lookupErr error) bool { + if p.versionDenied(ecosystem, name, version) { + return false + } + cached, err := p.GetCachedArtifact(r.Context(), ecosystem, name, version, filename) + if err != nil || cached == nil { + return false + } + p.Logger.Warn("cooldown: could not read publish times, serving cached file", + "ecosystem", ecosystem, "package", name, "version", version, "error", lookupErr) + ServeArtifactRequest(w, r, cached) + return true +} diff --git a/internal/handler/cooldown_fail_closed_test.go b/internal/handler/cooldown_fail_closed_test.go new file mode 100644 index 0000000..dc7cb98 --- /dev/null +++ b/internal/handler/cooldown_fail_closed_test.go @@ -0,0 +1,313 @@ +package handler + +import ( + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/git-pkgs/cooldown" + registryclient "github.com/git-pkgs/registries/client" + "github.com/git-pkgs/registries/fetch" +) + +// holdPaths returns a client that answers requests for the given paths with +// the rate limit gate's HeldError and sends the rest to upstream. +func holdPaths(paths ...string) *http.Client { + held := ®istryclient.HeldError{Host: "upstream.example", Until: time.Now().Add(30 * time.Second), RetryAfter: 30 * time.Second} + return &http.Client{Transport: roundTripperFunc(func(r *http.Request) (*http.Response, error) { + for _, p := range paths { + if r.URL.Path == p { + return nil, held + } + } + return http.DefaultTransport.RoundTrip(r) + })} +} + +func serveGet(t *testing.T, h http.Handler, path string) *httptest.ResponseRecorder { + t.Helper() + w := httptest.NewRecorder() + h.ServeHTTP(w, httptest.NewRequest(http.MethodGet, path, nil)) + return w +} + +func wantStatus(t *testing.T, w *httptest.ResponseRecorder, status int, leaked string) { + t.Helper() + if w.Code != status { + t.Errorf("status = %d, want %d: %s", w.Code, status, w.Body.String()) + } + if status == http.StatusServiceUnavailable && w.Header().Get("Retry-After") == "" { + t.Error("503 without Retry-After") + } + if leaked != "" && strings.Contains(w.Body.String(), leaked) { + t.Errorf("response lists %q, which cooldown should have withheld", leaked) + } +} + +func TestGemCooldownFailsClosed(t *testing.T) { + index := "---\n1.0.0 |checksum:abc\n2.0.0 |checksum:def\n" + versionsStatus := http.StatusInternalServerError + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if strings.HasPrefix(r.URL.Path, "/api/v1/versions/") { + w.WriteHeader(versionsStatus) + return + } + _, _ = io.WriteString(w, index) + })) + defer upstream.Close() + + t.Run("versions API fails", func(t *testing.T) { + proxy, _, _, _ := setupTestProxy(t) + proxy.Cooldown = &cooldown.Config{Default: "3d"} + h := NewGemHandlerWithUpstream(proxy, "http://proxy.test", upstream.URL) + wantStatus(t, serveGet(t, h.Routes(), "/info/testgem"), http.StatusBadGateway, "2.0.0") + }) + + t.Run("versions API held by rate limit", func(t *testing.T) { + proxy, _, _, _ := setupTestProxy(t) + proxy.Cooldown = &cooldown.Config{Default: "3d"} + proxy.HTTPClient = holdPaths("/api/v1/versions/testgem.json") + h := NewGemHandlerWithUpstream(proxy, "http://proxy.test", upstream.URL) + wantStatus(t, serveGet(t, h.Routes(), "/info/testgem"), http.StatusServiceUnavailable, "2.0.0") + }) + + t.Run("exempt package needs no times", func(t *testing.T) { + proxy, _, _, _ := setupTestProxy(t) + proxy.Cooldown = &cooldown.Config{Default: "3d", Packages: map[string]string{"pkg:gem/testgem": "0"}} + h := NewGemHandlerWithUpstream(proxy, "http://proxy.test", upstream.URL) + w := serveGet(t, h.Routes(), "/info/testgem") + if w.Code != http.StatusOK || w.Body.String() != index { + t.Errorf("status = %d, body = %q; want the index unchanged", w.Code, w.Body.String()) + } + }) +} + +func TestHexCooldownFailsClosed(t *testing.T) { + now := time.Now() + proto := buildHexSigned(buildHexPackage("testpkg", []string{testVersion100, "2.0.0"})) + apiJSON, _ := json.Marshal(hexPackageAPI{Releases: []hexRelease{ + {Version: testVersion100, InsertedAt: now.Add(-7 * 24 * time.Hour).Format(time.RFC3339Nano)}, + {Version: "2.0.0", InsertedAt: now.Add(-time.Hour).Format(time.RFC3339Nano)}, + }}) + + newUpstream := func(t *testing.T, packageBody []byte, apiStatus int) *httptest.Server { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/packages/testpkg": + _, _ = w.Write(packageBody) + case "/api/packages/testpkg": + w.WriteHeader(apiStatus) + _, _ = w.Write(apiJSON) + default: + w.WriteHeader(http.StatusNotFound) + } + })) + t.Cleanup(srv.Close) + return srv + } + handler := func(t *testing.T, srv *httptest.Server, client *http.Client) http.Handler { + proxy, _, _, _ := setupTestProxy(t) + proxy.Cooldown = &cooldown.Config{Default: "3d"} + if client != nil { + proxy.HTTPClient = client + } + return NewHexHandlerWithUpstreams(proxy, "http://proxy.test", srv.URL, srv.URL).Routes() + } + + t.Run("API fails", func(t *testing.T) { + srv := newUpstream(t, proto, http.StatusInternalServerError) + wantStatus(t, serveGet(t, handler(t, srv, nil), "/packages/testpkg"), http.StatusBadGateway, "") + }) + + t.Run("API held by rate limit", func(t *testing.T) { + srv := newUpstream(t, proto, http.StatusOK) + w := serveGet(t, handler(t, srv, holdPaths("/api/packages/testpkg")), "/packages/testpkg") + wantStatus(t, w, http.StatusServiceUnavailable, "") + }) + + t.Run("package can't be filtered", func(t *testing.T) { + srv := newUpstream(t, []byte("not gzip 2.0.0"), http.StatusOK) + wantStatus(t, serveGet(t, handler(t, srv, nil), "/packages/testpkg"), http.StatusBadGateway, "2.0.0") + }) + + t.Run("filtered", func(t *testing.T) { + srv := newUpstream(t, proto, http.StatusOK) + w := serveGet(t, handler(t, srv, nil), "/packages/testpkg") + if w.Code != http.StatusOK { + t.Fatalf("status = %d, want 200", w.Code) + } + }) +} + +func TestPyPICooldownFailsClosed(t *testing.T) { + simple := `{"meta":{"api-version":"1.4"},"name":"ruff","files":[` + + `{"filename":"ruff-1.0.0.tar.gz","url":"https://files.pythonhosted.org/packages/ab/ruff-1.0.0.tar.gz"},` + + `{"filename":"ruff-2.0.0.tar.gz","url":"https://files.pythonhosted.org/packages/cd/ruff-2.0.0.tar.gz"}]}` + + tests := []struct { + name string + json func(*http.Request) (*http.Response, error) + status int + }{ + {"JSON API fails", func(r *http.Request) (*http.Response, error) { + return &http.Response{StatusCode: http.StatusInternalServerError, Body: http.NoBody, Request: r}, nil + }, http.StatusBadGateway}, + {"JSON API held by rate limit", func(*http.Request) (*http.Response, error) { + return nil, ®istryclient.HeldError{Host: "pypi.test", RetryAfter: 30 * time.Second} + }, http.StatusServiceUnavailable}, + {"JSON has no releases", func(r *http.Request) (*http.Response, error) { + return pypiHTTPResponse(r, "application/json", `{"info":{}}`), nil + }, http.StatusBadGateway}, + {"JSON API doesn't know the package", func(r *http.Request) (*http.Response, error) { + return &http.Response{StatusCode: http.StatusNotFound, Body: http.NoBody, Request: r}, nil + }, http.StatusOK}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + h, proxy := setupPyPIHandler(t, func(r *http.Request) (*http.Response, error) { + if r.URL.Path == "/pypi/ruff/json" { + return tt.json(r) + } + return pypiHTTPResponse(r, pypiSimpleJSON, simple), nil + }) + proxy.Cooldown = &cooldown.Config{Default: "7d"} + + req := httptest.NewRequest(http.MethodGet, "/simple/ruff/", nil) + req.Header.Set("Accept", uvPyPIAccept) + w := httptest.NewRecorder() + h.Routes().ServeHTTP(w, req) + leaked := "ruff-2.0.0" + if tt.status == http.StatusOK { + leaked = "" + } + wantStatus(t, w, tt.status, leaked) + }) + } +} + +func TestPyPIDownloadCooldownFailsClosed(t *testing.T) { + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusInternalServerError) + })) + defer upstream.Close() + + proxy, _, _, fetcher := setupTestProxy(t) + proxy.Cooldown = &cooldown.Config{Default: "7d"} + fetcher.artifact = &fetch.Artifact{Body: io.NopCloser(strings.NewReader("sdist")), ContentType: "application/octet-stream"} + h := &PyPIHandler{proxy: proxy, upstreamURL: upstream.URL, proxyURL: "http://localhost"} + + w := serveGet(t, h.Routes(), "/packages/packages/ab/cd/ef0123456789/newpkg-2.0.0.tar.gz") + wantStatus(t, w, http.StatusBadGateway, "") + if fetcher.fetchCalled { + t.Error("fetched a file whose publish time couldn't be checked") + } +} + +func TestNPMDownloadCooldownFailsClosed(t *testing.T) { + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusInternalServerError) + })) + defer upstream.Close() + + proxy, _, _, fetcher := setupTestProxy(t) + proxy.Cooldown = &cooldown.Config{Default: "7d"} + fetcher.artifact = &fetch.Artifact{Body: io.NopCloser(strings.NewReader("tarball")), ContentType: "application/octet-stream"} + h := NewNPMHandler(proxy, "http://proxy.test", upstream.URL) + + w := serveGet(t, h.Routes(), "/leftpad/-/leftpad-2.0.0.tgz") + wantStatus(t, w, http.StatusBadGateway, "") + if fetcher.fetchCalled { + t.Error("fetched a tarball whose publish time couldn't be checked") + } +} + +// TestDownloadCooldownErrorServesCachedFile checks that a file already in the +// cache is still served when its publish time can't be read, while an uncached +// one fails. +func TestDownloadCooldownErrorServesCachedFile(t *testing.T) { + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusInternalServerError) + })) + defer upstream.Close() + + tests := []struct { + ecosystem, name, version, filename, path string + handler func(*Proxy) http.Handler + }{ + {"pypi", "newpkg", "2.0.0", "newpkg-2.0.0.tar.gz", "/packages/packages/ab/cd/ef0123456789/newpkg-2.0.0.tar.gz", + func(p *Proxy) http.Handler { + return (&PyPIHandler{proxy: p, upstreamURL: upstream.URL, downloadURL: upstream.URL, proxyURL: "http://localhost"}).Routes() + }}, + {"npm", "leftpad", "2.0.0", "leftpad-2.0.0.tgz", "/leftpad/-/leftpad-2.0.0.tgz", + func(p *Proxy) http.Handler { return NewNPMHandler(p, "http://proxy.test", upstream.URL).Routes() }}, + } + for _, tt := range tests { + t.Run(tt.ecosystem, func(t *testing.T) { + proxy, db, store, fetcher := setupTestProxy(t) + proxy.Cooldown = &cooldown.Config{Default: "7d"} + h := tt.handler(proxy) + + seedPackage(t, db, store, tt.ecosystem, tt.name, tt.version, tt.filename, "cached file") + w := serveGet(t, h, tt.path) + wantStatus(t, w, http.StatusOK, "") + if w.Body.String() != "cached file" { + t.Errorf("body = %q, want the cached file", w.Body.String()) + } + + other := strings.ReplaceAll(tt.path, "2.0.0", "3.0.0") + wantStatus(t, serveGet(t, h, other), http.StatusBadGateway, "") + if fetcher.fetchCalled { + t.Error("fetched a file whose publish time couldn't be checked") + } + }) + } +} + +// TestCooldownRewriteFailureFailsClosed checks that a metadata document the +// cooldown rewrite can't parse is refused rather than passed on, and still +// passed on when cooldown doesn't apply. +func TestCooldownRewriteFailureFailsClosed(t *testing.T) { + const broken = `{"name": "pkg", "versions": [ 2.0.0` + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set(headerContentType, contentTypeJSON) + _, _ = io.WriteString(w, broken) + })) + defer upstream.Close() + + tests := []struct { + name string + purl string + handler func(*Proxy) http.Handler + path string + }{ + {"npm", "pkg:npm/pkg", func(p *Proxy) http.Handler { return NewNPMHandler(p, "http://proxy.test", upstream.URL).Routes() }, "/pkg"}, + {"composer", "pkg:composer/vendor/pkg", func(p *Proxy) http.Handler { + return NewComposerHandlerWithUpstreams(p, "http://proxy.test", upstream.URL, upstream.URL).Routes() + }, "/p2/vendor/pkg.json"}, + {"pub", "pkg:pub/pkg", func(p *Proxy) http.Handler { + return NewPubHandlerWithUpstream(p, "http://proxy.test", upstream.URL).Routes() + }, "/api/packages/pkg"}, + {"pypi json", "pkg:pypi/pkg", func(p *Proxy) http.Handler { + return NewPyPIHandlerWithUpstreams(p, "http://proxy.test", upstream.URL, "").Routes() + }, "/pypi/pkg/json"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + proxy, _, _, _ := setupTestProxy(t) + proxy.Cooldown = &cooldown.Config{Default: "7d"} + wantStatus(t, serveGet(t, tt.handler(proxy), tt.path), http.StatusBadGateway, "2.0.0") + }) + t.Run(tt.name+" exempt", func(t *testing.T) { + proxy, _, _, _ := setupTestProxy(t) + proxy.Cooldown = &cooldown.Config{Default: "7d", Packages: map[string]string{tt.purl: "0"}} + w := serveGet(t, tt.handler(proxy), tt.path) + if w.Code != http.StatusOK { + t.Errorf("status = %d, want 200 for a package cooldown doesn't apply to", w.Code) + } + }) + } +} diff --git a/internal/handler/cooldown_metadata_cache_test.go b/internal/handler/cooldown_metadata_cache_test.go new file mode 100644 index 0000000..1eb4a86 --- /dev/null +++ b/internal/handler/cooldown_metadata_cache_test.go @@ -0,0 +1,644 @@ +package handler + +import ( + "bytes" + "compress/gzip" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "fmt" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + "time" + + "github.com/git-pkgs/cooldown" +) + +// cooldownCountingUpstream serves fixed documents by path with ETags, answers a +// matching If-None-Match with 304, and counts what it was asked. Setting +// down makes it answer 500, and closing gate holds requests until opened. +type cooldownCountingUpstream struct { + *httptest.Server + mu sync.Mutex + docs map[string][]byte + gzipped map[string]bool + requests map[string]int + notModified map[string]int + down map[string]bool + gate chan struct{} +} + +func newCooldownCountingUpstream(t *testing.T) *cooldownCountingUpstream { + t.Helper() + u := &cooldownCountingUpstream{ + docs: map[string][]byte{}, gzipped: map[string]bool{}, + requests: map[string]int{}, notModified: map[string]int{}, down: map[string]bool{}, + } + u.Server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + u.mu.Lock() + u.requests[r.URL.Path]++ + gate := u.gate + doc, ok := u.docs[r.URL.Path] + down := u.down[r.URL.Path] + gz := u.gzipped[r.URL.Path] + u.mu.Unlock() + if gate != nil { + <-gate + } + switch { + case down: + w.WriteHeader(http.StatusInternalServerError) + return + case !ok: + w.WriteHeader(http.StatusNotFound) + return + } + sum := sha256.Sum256(doc) + etag := `"` + hex.EncodeToString(sum[:8]) + `"` + w.Header().Set("ETag", etag) + if r.Header.Get("If-None-Match") == etag { + u.mu.Lock() + u.notModified[r.URL.Path]++ + u.mu.Unlock() + w.WriteHeader(http.StatusNotModified) + return + } + if gz && strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") { + w.Header().Set("Content-Encoding", "gzip") + zw := gzip.NewWriter(w) + _, _ = zw.Write(doc) + _ = zw.Close() + return + } + _, _ = w.Write(doc) + })) + t.Cleanup(u.Close) + return u +} + +func (u *cooldownCountingUpstream) set(path string, doc []byte) { + u.mu.Lock() + defer u.mu.Unlock() + u.docs[path] = doc +} + +func (u *cooldownCountingUpstream) setDown(path string, down bool) { + u.mu.Lock() + defer u.mu.Unlock() + u.down[path] = down +} + +func (u *cooldownCountingUpstream) counts(path string) (requests, notModified int) { + u.mu.Lock() + defer u.mu.Unlock() + return u.requests[path], u.notModified[path] +} + +// cooldownCacheProxy returns a proxy with cooldown and the metadata cache on. +func cooldownCacheProxy(t *testing.T, u *cooldownCountingUpstream) *Proxy { + t.Helper() + proxy, _, _, _ := setupTestProxy(t) + proxy.HTTPClient = u.Client() + config := &cooldown.Config{Default: "3d"} + // Config parses itself on first use, which isn't safe to race. + config.Enabled() + proxy.Cooldown = config + proxy.CacheMetadata = true + proxy.MetadataTTL = time.Hour + return proxy +} + +// expireCachedMetadata moves a metadata cache row's fetch time past the TTL. +func expireCachedMetadata(t *testing.T, proxy *Proxy, ecosystem, key string) { + t.Helper() + entry, err := proxy.DB.GetMetadataCache(ecosystem, key) + if err != nil || entry == nil { + t.Fatalf("metadata entry %s/%s: %v", ecosystem, key, err) + } + entry.FetchedAt.Time = time.Now().Add(-2 * proxy.MetadataTTL) + if err := proxy.DB.UpsertMetadataCache(entry); err != nil { + t.Fatalf("expiring metadata entry: %v", err) + } +} + +func getWith(t *testing.T, h http.Handler, path string, header http.Header) *httptest.ResponseRecorder { + t.Helper() + req := httptest.NewRequest(http.MethodGet, path, nil) + for k, vv := range header { + req.Header[k] = vv + } + w := httptest.NewRecorder() + h.ServeHTTP(w, req) + return w +} + +const ( + gemInfoPath = "/info/testgem" + gemVersionsPath = "/api/v1/versions/testgem.json" +) + +func gemVersionsJSON(t *testing.T, versions map[string]time.Duration) []byte { + t.Helper() + var list []gemVersion + for number, age := range versions { + list = append(list, gemVersion{Number: number, Platform: "ruby", CreatedAt: time.Now().Add(-age).Format(time.RFC3339)}) + } + b, err := json.Marshal(list) + if err != nil { + t.Fatal(err) + } + return b +} + +// gemCacheSetup serves testgem with 1.0.0 published a week ago and 2.0.0 an +// hour ago. +func gemCacheSetup(t *testing.T) (*cooldownCountingUpstream, *Proxy, http.Handler) { + t.Helper() + u := newCooldownCountingUpstream(t) + u.set(gemInfoPath, []byte("---\n1.0.0 |checksum:a\n2.0.0 |checksum:b\n")) + u.set(gemVersionsPath, gemVersionsJSON(t, map[string]time.Duration{"1.0.0": 7 * 24 * time.Hour, "2.0.0": time.Hour})) + proxy := cooldownCacheProxy(t, u) + return u, proxy, NewGemHandlerWithUpstream(proxy, "http://proxy.test", u.URL).Routes() +} + +const gemFiltered = "---\n1.0.0 |checksum:a\n" + +func TestGemCooldownServesFromMetadataCache(t *testing.T) { + u, _, h := gemCacheSetup(t) + for i := range 3 { + w := getWith(t, h, gemInfoPath, nil) + if w.Code != http.StatusOK || w.Body.String() != gemFiltered { + t.Fatalf("request %d: status %d, body %q", i, w.Code, w.Body) + } + } + for _, path := range []string{gemInfoPath, gemVersionsPath} { + if n, _ := u.counts(path); n != 1 { + t.Errorf("%s requested %d times, want 1 within the TTL", path, n) + } + } +} + +func TestGemCooldownRevalidatesAfterTTL(t *testing.T) { + u, proxy, h := gemCacheSetup(t) + getWith(t, h, gemInfoPath, nil) + expireCachedMetadata(t, proxy, "gem", "info/testgem") + expireCachedMetadata(t, proxy, "gem", "api/v1/versions/testgem.json") + + w := getWith(t, h, gemInfoPath, nil) + if w.Code != http.StatusOK || w.Body.String() != gemFiltered { + t.Fatalf("status %d, body %q", w.Code, w.Body) + } + for _, path := range []string{gemInfoPath, gemVersionsPath} { + if n, nm := u.counts(path); n != 2 || nm != 1 { + t.Errorf("%s: %d requests, %d answered 304; want 2 and 1", path, n, nm) + } + } +} + +func TestGemCooldownConcurrentRequestsShareFetch(t *testing.T) { + u, proxy, h := gemCacheSetup(t) + u.gate = make(chan struct{}) + var release sync.Once + t.Cleanup(func() { release.Do(func() { close(u.gate) }) }) + + const clients = 5 + var wg sync.WaitGroup + codes := make([]int, clients) + bodies := make([]string, clients) + for i := range clients { + wg.Go(func() { + w := getWith(t, h, gemInfoPath, nil) + codes[i], bodies[i] = w.Code, w.Body.String() + }) + } + waitForMetadataWaiters(t, proxy, metadataCoalesceKey("gem", "info/testgem", u.URL+gemInfoPath, "*/*", "identity", false), clients-1) + waitForMetadataWaiters(t, proxy, metadataCoalesceKey("gem", "api/v1/versions/testgem.json", u.URL+gemVersionsPath, contentTypeJSON, "", true), clients-1) + release.Do(func() { close(u.gate) }) + wg.Wait() + + for i := range clients { + if codes[i] != http.StatusOK || bodies[i] != gemFiltered { + t.Errorf("client %d: status %d, body %q", i, codes[i], bodies[i]) + } + } + for _, path := range []string{gemInfoPath, gemVersionsPath} { + if n, _ := u.counts(path); n != 1 { + t.Errorf("%s requested %d times, want 1", path, n) + } + } +} + +func TestGemCooldownStaleCopyIsFiltered(t *testing.T) { + u, proxy, h := gemCacheSetup(t) + getWith(t, h, gemInfoPath, nil) + expireCachedMetadata(t, proxy, "gem", "info/testgem") + expireCachedMetadata(t, proxy, "gem", "api/v1/versions/testgem.json") + u.setDown(gemInfoPath, true) + u.setDown(gemVersionsPath, true) + + w := getWith(t, h, gemInfoPath, nil) + if w.Code != http.StatusOK || w.Body.String() != gemFiltered { + t.Fatalf("status %d, body %q; want the stale copy, filtered", w.Code, w.Body) + } + if got := w.Header().Get("Warning"); got != staleWarning { + t.Errorf("Warning = %q, want %q", got, staleWarning) + } +} + +func TestGemCooldownFailsClosedWithoutTimes(t *testing.T) { + u, _, h := gemCacheSetup(t) + u.setDown(gemVersionsPath, true) + + w := getWith(t, h, gemInfoPath, nil) + if w.Code != http.StatusBadGateway || strings.Contains(w.Body.String(), "1.0.0") { + t.Fatalf("status %d, body %q; want 502 without the index", w.Code, w.Body) + } + // The index alone was cached; it must not be served unfiltered either. + w = getWith(t, h, gemInfoPath, nil) + if w.Code != http.StatusBadGateway { + t.Fatalf("second request: status %d, want 502", w.Code) + } +} + +func TestGemCooldownClientRevalidates(t *testing.T) { + _, _, h := gemCacheSetup(t) + first := getWith(t, h, gemInfoPath, nil) + etag := first.Header().Get("ETag") + if etag == "" { + t.Fatal("filtered index served without an ETag") + } + w := getWith(t, h, gemInfoPath, http.Header{"If-None-Match": {etag}}) + if w.Code != http.StatusNotModified { + t.Fatalf("status %d, want 304", w.Code) + } +} + +// The index can be fetched again while the versions API response is still +// within its TTL. A version published in between is then in the index but +// has no publish time, and must not be let through for that. +func TestGemCooldownRefreshesTimesOlderThanIndex(t *testing.T) { + for _, timesDown := range []bool{false, true} { + name := "times refreshed" + if timesDown { + name = "times upstream down" + } + t.Run(name, func(t *testing.T) { + u, proxy, h := gemCacheSetup(t) + getWith(t, h, gemInfoPath, nil) + + u.set(gemInfoPath, []byte("---\n1.0.0 |checksum:a\n2.0.0 |checksum:b\n3.0.0 |checksum:c\n")) + u.set(gemVersionsPath, gemVersionsJSON(t, map[string]time.Duration{ + "1.0.0": 7 * 24 * time.Hour, "2.0.0": time.Hour, "3.0.0": time.Minute, + })) + u.setDown(gemVersionsPath, timesDown) + expireCachedMetadata(t, proxy, "gem", "info/testgem") + + w := getWith(t, h, gemInfoPath, nil) + if w.Code != http.StatusOK || w.Body.String() != gemFiltered { + t.Fatalf("status %d, body %q; want %q", w.Code, w.Body, gemFiltered) + } + if n, _ := u.counts(gemVersionsPath); n != 2 { + t.Errorf("versions API requested %d times, want 2", n) + } + if got := w.Header().Get("Warning"); (got != "") != timesDown { + t.Errorf("Warning = %q with times upstream down = %v", got, timesDown) + } + }) + } +} + +const ( + hexPackagePath = "/packages/testpkg" + hexAPIPath = "/api/packages/testpkg" +) + +func hexAPIJSON(t *testing.T, releases map[string]time.Duration) []byte { + t.Helper() + var api hexPackageAPI + for version, age := range releases { + api.Releases = append(api.Releases, hexRelease{Version: version, InsertedAt: time.Now().Add(-age).Format(time.RFC3339Nano)}) + } + b, err := json.Marshal(api) + if err != nil { + t.Fatal(err) + } + return b +} + +func hexCacheSetup(t *testing.T, recent time.Duration) (*cooldownCountingUpstream, *Proxy, http.Handler, []byte) { + t.Helper() + u := newCooldownCountingUpstream(t) + signed := buildHexSigned(buildHexPackage("testpkg", []string{testVersion100, "2.0.0"})) + u.set(hexPackagePath, signed) + u.set(hexAPIPath, hexAPIJSON(t, map[string]time.Duration{testVersion100: 7 * 24 * time.Hour, "2.0.0": recent})) + proxy := cooldownCacheProxy(t, u) + return u, proxy, NewHexHandlerWithUpstreams(proxy, "http://proxy.test", u.URL, u.URL).Routes(), signed +} + +// hexVersions decodes the release versions of a served package. +func hexVersions(t *testing.T, body []byte) []string { + t.Helper() + zr, err := gzip.NewReader(bytes.NewReader(body)) + if err != nil { + t.Fatal(err) + } + signed, err := io.ReadAll(zr) + if err != nil { + t.Fatal(err) + } + payload, err := extractProtobufBytes(signed, 1) + if err != nil { + t.Fatal(err) + } + versions, err := packageReleaseVersions(payload) + if err != nil { + t.Fatal(err) + } + return versions +} + +func TestHexCooldownServesFromMetadataCache(t *testing.T) { + u, proxy, h, _ := hexCacheSetup(t, time.Hour) + for i := range 3 { + w := getWith(t, h, hexPackagePath, nil) + if w.Code != http.StatusOK { + t.Fatalf("request %d: status %d", i, w.Code) + } + if got := hexVersions(t, w.Body.Bytes()); len(got) != 1 || got[0] != testVersion100 { + t.Fatalf("request %d: versions %v, want [%s]", i, got, testVersion100) + } + if ce := w.Header().Get("Content-Encoding"); ce != "gzip" { + t.Errorf("Content-Encoding = %q, want gzip", ce) + } + } + for _, path := range []string{hexPackagePath, hexAPIPath} { + if n, _ := u.counts(path); n != 1 { + t.Errorf("%s requested %d times, want 1 within the TTL", path, n) + } + } + + expireCachedMetadata(t, proxy, "hex", "packages/testpkg") + expireCachedMetadata(t, proxy, "hex", hashedCacheKey(u.URL, "api/packages/testpkg")) + if w := getWith(t, h, hexPackagePath, nil); w.Code != http.StatusOK || len(hexVersions(t, w.Body.Bytes())) != 1 { + t.Fatalf("after TTL: status %d", w.Code) + } + for _, path := range []string{hexPackagePath, hexAPIPath} { + if n, nm := u.counts(path); n != 2 || nm != 1 { + t.Errorf("%s: %d requests, %d answered 304; want 2 and 1", path, n, nm) + } + } +} + +func TestHexCooldownStaleCopyIsFiltered(t *testing.T) { + u, proxy, h, _ := hexCacheSetup(t, time.Hour) + getWith(t, h, hexPackagePath, nil) + expireCachedMetadata(t, proxy, "hex", "packages/testpkg") + expireCachedMetadata(t, proxy, "hex", hashedCacheKey(u.URL, "api/packages/testpkg")) + u.setDown(hexPackagePath, true) + u.setDown(hexAPIPath, true) + + w := getWith(t, h, hexPackagePath, nil) + if w.Code != http.StatusOK { + t.Fatalf("status %d, want the stale copy", w.Code) + } + if got := hexVersions(t, w.Body.Bytes()); len(got) != 1 || got[0] != testVersion100 { + t.Errorf("versions %v, want [%s]", got, testVersion100) + } + if got := w.Header().Get("Warning"); got != staleWarning { + t.Errorf("Warning = %q, want %q", got, staleWarning) + } +} + +func TestHexCooldownFailsClosedWithoutTimes(t *testing.T) { + u, _, h, _ := hexCacheSetup(t, time.Hour) + u.setDown(hexAPIPath, true) + for i := range 2 { + if w := getWith(t, h, hexPackagePath, nil); w.Code != http.StatusBadGateway { + t.Fatalf("request %d: status %d, want 502", i, w.Code) + } + } +} + +func TestHexCooldownUnfilteredKeepsSignature(t *testing.T) { + _, _, h, signed := hexCacheSetup(t, 7*24*time.Hour) + w := getWith(t, h, hexPackagePath, nil) + if w.Code != http.StatusOK || !bytes.Equal(w.Body.Bytes(), signed) { + t.Fatalf("status %d; want upstream's signed bytes when nothing is in cooldown", w.Code) + } + etag := w.Header().Get("ETag") + if etag == "" { + t.Fatal("package served without an ETag") + } + if w := getWith(t, h, hexPackagePath, http.Header{"If-None-Match": {etag}}); w.Code != http.StatusNotModified { + t.Fatalf("revalidation: status %d, want 304", w.Code) + } +} + +const condaRepodataPath = "/conda-forge/noarch/repodata.json" + +func condaCacheSetup(t *testing.T) (*cooldownCountingUpstream, *Proxy, *CondaHandler, http.Handler) { + t.Helper() + u := newCooldownCountingUpstream(t) + repodata, err := json.Marshal(map[string]any{ + "info": map[string]any{"subdir": "noarch"}, + "packages": map[string]any{ + "old-1.0.0-0.tar.bz2": map[string]any{"name": "old", "version": "1.0.0", "timestamp": time.Now().Add(-7 * 24 * time.Hour).UnixMilli()}, + "new-2.0.0-0.tar.bz2": map[string]any{"name": "new", "version": "2.0.0", "timestamp": time.Now().Add(-time.Hour).UnixMilli()}, + }, + "packages.conda": map[string]any{}, + }) + if err != nil { + t.Fatal(err) + } + u.set(condaRepodataPath, repodata) + u.gzipped[condaRepodataPath] = true + proxy := cooldownCacheProxy(t, u) + h := NewCondaHandlerWithUpstream(proxy, "http://proxy.test", u.URL) + return u, proxy, h, h.Routes() +} + +func condaPackages(t *testing.T, w *httptest.ResponseRecorder) []string { + t.Helper() + if w.Code != http.StatusOK { + t.Fatalf("status %d, body %q", w.Code, w.Body) + } + var doc struct { + Packages map[string]json.RawMessage `json:"packages"` + } + if err := json.Unmarshal(w.Body.Bytes(), &doc); err != nil { + t.Fatalf("decoding repodata: %v", err) + } + var names []string + for name := range doc.Packages { + names = append(names, name) + } + return names +} + +func assertCondaFiltered(t *testing.T, w *httptest.ResponseRecorder) { + t.Helper() + if got := condaPackages(t, w); len(got) != 1 || got[0] != "old-1.0.0-0.tar.bz2" { + t.Fatalf("packages %v, want only old-1.0.0-0.tar.bz2", got) + } +} + +func TestCondaCooldownServesFromMetadataCache(t *testing.T) { + u, proxy, h, routes := condaCacheSetup(t) + for range 3 { + assertCondaFiltered(t, getWith(t, routes, condaRepodataPath, nil)) + } + if n, _ := u.counts(condaRepodataPath); n != 1 { + t.Errorf("repodata requested %d times, want 1 within the TTL", n) + } + + expireCachedMetadata(t, proxy, "conda", h.metadataCacheKey(condaRepodataPath)) + assertCondaFiltered(t, getWith(t, routes, condaRepodataPath, nil)) + if n, nm := u.counts(condaRepodataPath); n != 2 || nm != 1 { + t.Errorf("%d requests, %d answered 304; want 2 and 1", n, nm) + } +} + +func TestCondaCooldownStaleCopyIsFiltered(t *testing.T) { + u, proxy, h, routes := condaCacheSetup(t) + assertCondaFiltered(t, getWith(t, routes, condaRepodataPath, nil)) + expireCachedMetadata(t, proxy, "conda", h.metadataCacheKey(condaRepodataPath)) + u.setDown(condaRepodataPath, true) + + w := getWith(t, routes, condaRepodataPath, nil) + assertCondaFiltered(t, w) + if got := w.Header().Get("Warning"); got != staleWarning { + t.Errorf("Warning = %q, want %q", got, staleWarning) + } +} + +func TestCondaCooldownConcurrentRequestsShareFetch(t *testing.T) { + u, proxy, h, routes := condaCacheSetup(t) + u.gate = make(chan struct{}) + var release sync.Once + t.Cleanup(func() { release.Do(func() { close(u.gate) }) }) + + const clients = 5 + var wg sync.WaitGroup + recorders := make([]*httptest.ResponseRecorder, clients) + for i := range clients { + wg.Go(func() { recorders[i] = getWith(t, routes, condaRepodataPath, nil) }) + } + key := metadataCoalesceKey("conda", h.metadataCacheKey(condaRepodataPath), u.URL+condaRepodataPath, "*/*", "gzip", false) + waitForMetadataWaiters(t, proxy, key, clients-1) + release.Do(func() { close(u.gate) }) + wg.Wait() + + for _, w := range recorders { + assertCondaFiltered(t, w) + } + if n, _ := u.counts(condaRepodataPath); n != 1 { + t.Errorf("repodata requested %d times, want 1", n) + } +} + +func TestCondaCooldownClientRevalidates(t *testing.T) { + _, _, h, routes := condaCacheSetup(t) + // The first copy is streamed as it is filtered, before its ETag is known. + assertCondaFiltered(t, getWith(t, routes, condaRepodataPath, nil)) + w := getWith(t, routes, condaRepodataPath, nil) + assertCondaFiltered(t, w) + etag := w.Header().Get("ETag") + if etag == "" { + t.Fatal("filtered repodata served without an ETag") + } + if w := getWith(t, routes, condaRepodataPath, http.Header{"If-None-Match": {etag}}); w.Code != http.StatusNotModified { + t.Fatalf("revalidation: status %d, want 304", w.Code) + } + + // Once the entry left out leaves cooldown, the copy changes and so does + // its ETag. + key := h.metadataCacheKey(condaRepodataPath) + h.repodataMu.Lock() + state := h.repodataStates[key] + h.repodataMu.Unlock() + if want := time.Now().Add(-time.Hour + 3*24*time.Hour); state.until.Sub(want).Abs() > time.Minute { + t.Errorf("ETag kept until %v, want about %v", state.until, want) + } + req := httptest.NewRequest(http.MethodGet, condaRepodataPath, nil) + req.Header.Set("If-None-Match", etag) + if h.repodataNotModified(httptest.NewRecorder(), req, key, state.digest, state.until) { + t.Error("ETag still matched after the withheld entry left cooldown") + } +} + +func TestCondaCooldownWithoutMetadataCacheStreams(t *testing.T) { + u, proxy, _, routes := condaCacheSetup(t) + proxy.CacheMetadata = false + for range 2 { + assertCondaFiltered(t, getWith(t, routes, condaRepodataPath, nil)) + } + if n, _ := u.counts(condaRepodataPath); n != 2 { + t.Errorf("repodata requested %d times, want 2 without cache_metadata", n) + } +} + +// A cached repodata.json is filtered as it is read from storage: the +// response starts while the stored document is still being read. +func TestCondaCooldownStreamsCachedRepodata(t *testing.T) { + u, proxy, _, routes := condaCacheSetup(t) + packages := map[string]any{} + for i := range 20000 { + packages[fmt.Sprintf("pkg%d-1.0.0-0.tar.bz2", i)] = map[string]any{ + "name": fmt.Sprintf("pkg%d", i), "version": "1.0.0", "timestamp": time.Now().Add(-7 * 24 * time.Hour).UnixMilli(), + } + } + repodata, err := json.Marshal(map[string]any{"info": map[string]any{}, "packages": packages}) + if err != nil { + t.Fatal(err) + } + u.set(condaRepodataPath, repodata) + // Stored uncompressed, so the document is larger than the part the + // storage hands out before stalling. + u.gzipped[condaRepodataPath] = false + if w := getWith(t, routes, condaRepodataPath, nil); w.Code != http.StatusOK { + t.Fatalf("populating cache: status %d", w.Code) + } + + gate := &stallingStorage{Storage: proxy.Storage, head: 256 << 10, release: make(chan struct{})} + proxy.Storage = gate + var release sync.Once + t.Cleanup(func() { release.Do(func() { close(gate.release) }) }) + srv := httptest.NewServer(routes) + t.Cleanup(srv.Close) + + type result struct { + resp *http.Response + err error + } + started := make(chan result, 1) + go func() { + resp, err := http.Get(srv.URL + condaRepodataPath) + if err == nil { + _, err = io.ReadFull(resp.Body, make([]byte, 1024)) + } + started <- result{resp, err} + }() + var res result + select { + case res = <-started: + case <-time.After(5 * time.Second): + release.Do(func() { close(gate.release) }) + if res := <-started; res.resp != nil { + _ = res.resp.Body.Close() + } + t.Fatal("response did not start before the cached document was read to its end") + } + release.Do(func() { close(gate.release) }) + if res.err != nil { + t.Fatal(res.err) + } + _, _ = io.Copy(io.Discard, res.resp.Body) + _ = res.resp.Body.Close() + if n, _ := u.counts(condaRepodataPath); n != 1 { + t.Errorf("repodata requested %d times, want 1", n) + } +} diff --git a/internal/handler/cooldown_patterns_test.go b/internal/handler/cooldown_patterns_test.go index 83034cf..71fcc23 100644 --- a/internal/handler/cooldown_patterns_test.go +++ b/internal/handler/cooldown_patterns_test.go @@ -10,7 +10,6 @@ import ( "time" "github.com/git-pkgs/cooldown" - "github.com/git-pkgs/proxy/internal/cooldownpolicy" ) func TestNuGetCooldownPackagePatterns(t *testing.T) { @@ -26,7 +25,7 @@ func TestNuGetCooldownPackagePatterns(t *testing.T) { } { t.Run(tc.name, func(t *testing.T) { p, db, store, fetcher := setupTestProxy(t) - policy, err := cooldownpolicy.New(&cooldown.Config{Default: tc.defaultDuration, Packages: tc.exact}, map[string]string{"pkg:nuget/test*": tc.pattern}) + policy, err := cooldown.NewPolicy(&cooldown.Config{Default: tc.defaultDuration, Packages: tc.exact}, map[string]string{"pkg:nuget/test*": tc.pattern}) if err != nil { t.Fatal(err) } @@ -56,7 +55,7 @@ func TestNuGetCooldownPackagePatterns(t *testing.T) { func TestNPMCooldownPatternExemptionRespectsDenylist(t *testing.T) { p, db, store, fetcher := setupTestProxy(t) var err error - p.Cooldown, err = cooldownpolicy.New(&cooldown.Config{Default: "7d"}, map[string]string{"pkg:npm/@example/*": "0"}) + p.Cooldown, err = cooldown.NewPolicy(&cooldown.Config{Default: "7d"}, map[string]string{"pkg:npm/@example/*": "0"}) if err != nil { t.Fatal(err) } diff --git a/internal/handler/cooldown_supported_test.go b/internal/handler/cooldown_supported_test.go new file mode 100644 index 0000000..7187ede --- /dev/null +++ b/internal/handler/cooldown_supported_test.go @@ -0,0 +1,47 @@ +package handler + +import ( + "os" + "path/filepath" + "regexp" + "strings" + "testing" +) + +func TestCooldownSupportedCoversHandlers(t *testing.T) { + calls := regexp.MustCompile(`(?:IsAllowed|Evaluate)\("([a-z]+)"|withheld\(h\.proxy, "([a-z]+)"|IsAllowed\((helmMetadataEcosystem)`) + files, err := filepath.Glob("*.go") + if err != nil { + t.Fatal(err) + } + found := map[string]bool{} + for _, f := range files { + if strings.HasSuffix(f, "_test.go") { + continue + } + src, err := os.ReadFile(f) + if err != nil { + t.Fatal(err) + } + for _, m := range calls.FindAllStringSubmatch(string(src), -1) { + if m[3] != "" { + found[helmMetadataEcosystem] = true + continue + } + found[m[1]+m[2]] = true + } + } + if len(found) < 10 { + t.Fatalf("found only %d ecosystems checking cooldown, the pattern no longer matches the handlers", len(found)) + } + for eco := range found { + if !CooldownSupported(eco) { + t.Errorf("%s checks cooldown but is missing from cooldownEcosystems", eco) + } + } + for eco := range cooldownEcosystems { + if !found[eco] { + t.Errorf("%s is in cooldownEcosystems but no handler checks cooldown for it", eco) + } + } +} diff --git a/internal/handler/cooldown_times.go b/internal/handler/cooldown_times.go new file mode 100644 index 0000000..b765f9a --- /dev/null +++ b/internal/handler/cooldown_times.go @@ -0,0 +1,170 @@ +package handler + +import ( + "bytes" + "compress/gzip" + "context" + "crypto/sha256" + "encoding/hex" + "fmt" + "slices" + "strings" + "time" +) + +// publishTimes maps each version a times document lists to its publish +// time. A version whose time didn't parse maps to the zero time and is let +// through. +type publishTimes map[string]time.Time + +func (p *Proxy) lookupPublishTime(ctx context.Context, t timedMetadata, version string, listed func(metadataResult) ([]string, error)) (time.Time, bool, bool, error) { + var versions []string + docs, err := p.fetchTimedMetadata(ctx, t, func(doc metadataResult) ([]string, error) { + var err error + versions, err = listed(doc) + return versions, err + }) + switch { + case docs.doc.err != nil: + return time.Time{}, false, false, docs.doc.err + case docs.times.err != nil: + return time.Time{}, false, false, docs.times.err + case err != nil: + return time.Time{}, false, false, err + } + published, ok := docs.published[version] + withholdUnknown := !ok && docs.withholdUnknown && slices.Contains(versions, version) + return published, ok && !published.IsZero(), withholdUnknown, nil +} + +// timedMetadata describes metadata whose publish times live in a second +// document, as with the RubyGems compact index and the versions API, or a +// Hex package and the Hex HTTP API. Both are read through the metadata cache. +type timedMetadata struct { + ecosystem string + // docKey and docURL are the cache key and upstream URL of the document + // clients read. They match the plain metadata path's, so both share one + // cached copy. + docKey, docURL string + // timesKey and timesURL are those of the document with publish times. + timesKey, timesURL string + timesAccept string + parseTimes func([]byte) (publishTimes, error) +} + +// timedDocuments is what fetchTimedMetadata hands back. published is read +// from times and is nil when times.err is set. +type timedDocuments struct { + doc metadataResult + times metadataResult + published publishTimes + // withholdUnknown is set when doc lists versions the times document + // doesn't, and that document is a stale copy: those versions are newer + // than the copy, so they are left out rather than let through. + withholdUnknown bool +} + +// fetchTimedMetadata fetches both documents concurrently. The document +// clients read is fetched as the plain metadata path fetches it, with +// identity encoding and Accept */*. +// +// Each document has its own TTL, so a cached times document can be older +// than the document it is used to filter, and miss versions published in +// between. Those versions would be let through as having no publish time. +// listed returns the versions the document lists; when some are missing +// from a times document read from the cache, the times document is fetched +// again before filtering. +func (p *Proxy) fetchTimedMetadata(ctx context.Context, t timedMetadata, listed func(metadataResult) ([]string, error)) (timedDocuments, error) { + var res timedDocuments + var published publishTimes + validate := func(body []byte) error { + parsed, err := t.parseTimes(body) + if err == nil { + published = parsed + } + return err + } + + done := make(chan struct{}) + go func() { + defer close(done) + res.times = p.lookupMetadata(ctx, t.ecosystem, t.timesKey, t.timesURL, t.timesAccept, "", validate) + }() + res.doc = p.lookupMetadata(ctx, t.ecosystem, t.docKey, t.docURL, "*/*", "identity", nil) + <-done + + if res.doc.err != nil || res.times.err != nil { + return res, nil + } + versions, err := listed(res.doc) + if err != nil { + return res, err + } + unknown := func() bool { + for _, v := range versions { + if _, ok := published[v]; !ok { + return true + } + } + return false + } + if unknown() && res.times.fromCache { + p.Logger.Info("cooldown: publish times older than metadata, fetching them again", + "ecosystem", t.ecosystem, "key", t.timesKey) + res.times = p.refreshMetadata(ctx, t.ecosystem, t.timesKey, t.timesURL, t.timesAccept, "", validate) + if res.times.err != nil { + return res, nil + } + } + res.published = published + res.withholdUnknown = res.times.stale && unknown() + return res, nil +} + +// rewriteDigest identifies the inputs of a cooldown rewrite for the rewrite +// cache: both documents and whether unknown versions are withheld. +func (d timedDocuments) rewriteDigest() string { + h := sha256.New() + for _, res := range []metadataResult{d.doc, d.times} { + digest := res.digest + if digest == "" { + sum := sha256.Sum256(res.body) + digest = "sha256:" + hex.EncodeToString(sum[:]) + } + _, _ = fmt.Fprintf(h, "%d:%s", len(digest), digest) + } + _, _ = fmt.Fprintf(h, "%t", d.withholdUnknown) + return "sha256:" + hex.EncodeToString(h.Sum(nil)) +} + +// withheld reports whether cooldown leaves version out, given the +// package's publish times. +func (d timedDocuments) withheld(p *Proxy, ecosystem, packagePURL, version string) bool { + published, ok := d.published[version] + if !ok { + return d.withholdUnknown + } + if published.IsZero() { + return false + } + return !p.cooldown().IsAllowed(ecosystem, packagePURL, published) +} + +// decodedMetadataBody returns res's body without its Content-Encoding. The +// documents are fetched with identity encoding, so an upstream that sends +// gzip anyway is the only case to handle. +func (p *Proxy) decodedMetadataBody(res metadataResult) ([]byte, error) { + switch strings.ToLower(strings.TrimSpace(res.contentEncoding)) { + case "", "identity": + return res.body, nil + case "gzip", "x-gzip": + zr, err := gzip.NewReader(bytes.NewReader(res.body)) + if err != nil { + return nil, err + } + defer func() { _ = zr.Close() }() + return p.ReadMetadata(zr) + default: + return nil, fmt.Errorf("unsupported content encoding %q", res.contentEncoding) + } +} diff --git a/internal/handler/cran.go b/internal/handler/cran.go index d0dbd52..10f1750 100644 --- a/internal/handler/cran.go +++ b/internal/handler/cran.go @@ -51,19 +51,39 @@ func (h *CRANHandler) Routes() http.Handler { mux.HandleFunc("GET /src/contrib/PACKAGES.gz", h.proxyCached) mux.HandleFunc("GET /src/contrib/PACKAGES.rds", h.proxyCached) + // Repository metadata such as archive.rds and current.rds, used by + // remotes::install_version and pak to find archived versions. + mux.HandleFunc("GET /src/contrib/Meta/{filename}", h.handleMeta) + // Binary package indexes mux.HandleFunc("GET /bin/{platform}/contrib/{rversion}/PACKAGES", h.proxyCached) mux.HandleFunc("GET /bin/{platform}/contrib/{rversion}/PACKAGES.gz", h.proxyCached) mux.HandleFunc("GET /bin/{platform}/contrib/{rversion}/PACKAGES.rds", h.proxyCached) + // macOS binaries for R >= 4.3 use two platform segments, e.g. + // bin/macosx/big-sur-arm64/contrib/4.4/. + mux.HandleFunc("GET /bin/{platform}/{arch}/contrib/{rversion}/PACKAGES", h.proxyCached) + mux.HandleFunc("GET /bin/{platform}/{arch}/contrib/{rversion}/PACKAGES.gz", h.proxyCached) + mux.HandleFunc("GET /bin/{platform}/{arch}/contrib/{rversion}/PACKAGES.rds", h.proxyCached) + // Source package downloads mux.HandleFunc("GET /src/contrib/{filename}", h.handleSourceDownload) mux.HandleFunc("GET /src/contrib/Archive/{name}/{filename}", h.handleSourceDownload) // Binary package downloads mux.HandleFunc("GET /bin/{platform}/contrib/{rversion}/{filename}", h.handleBinaryDownload) + mux.HandleFunc("GET /bin/{platform}/{arch}/contrib/{rversion}/{filename}", h.handleBinaryDownload) - return mux + return rejectQueryChars(mux) +} + +// handleMeta serves the .rds files under src/contrib/Meta as cached metadata. +func (h *CRANHandler) handleMeta(w http.ResponseWriter, r *http.Request) { + if !strings.HasSuffix(r.PathValue("filename"), ".rds") { + http.NotFound(w, r) + return + } + h.proxyCached(w, r) } // handleSourceDownload serves a source package, fetching and caching from upstream. @@ -99,6 +119,9 @@ func (h *CRANHandler) handleSourceDownload(w http.ResponseWriter, r *http.Reques // handleBinaryDownload serves a binary package, fetching and caching from upstream. func (h *CRANHandler) handleBinaryDownload(w http.ResponseWriter, r *http.Request) { platform := r.PathValue("platform") + if arch := r.PathValue("arch"); arch != "" { + platform += "-" + arch + } rversion := r.PathValue("rversion") filename := r.PathValue("filename") @@ -165,11 +188,14 @@ func (h *CRANHandler) isBinaryPackage(filename string) bool { return strings.HasSuffix(filename, ".zip") || strings.HasSuffix(filename, ".tgz") } +// metadataCacheKey is the metadata cache key of a request path. +func (h *CRANHandler) metadataCacheKey(urlPath string) string { + return hashedCacheKey(h.upstreamURL, urlPath) +} + // proxyCached forwards a metadata request with caching. func (h *CRANHandler) proxyCached(w http.ResponseWriter, r *http.Request) { - cacheKey := strings.TrimPrefix(r.URL.Path, "/") - cacheKey = strings.ReplaceAll(cacheKey, "/", "_") - h.proxy.ProxyCached(w, r, h.upstreamURL+r.URL.Path, "cran", cacheKey, "*/*") + h.proxy.ProxyCached(w, r, h.upstreamURL+r.URL.Path, "cran", h.metadataCacheKey(r.URL.Path), "*/*") } // proxyUpstream forwards a request to CRAN without caching. diff --git a/internal/handler/cran_test.go b/internal/handler/cran_test.go index 6a9c151..6c156c5 100644 --- a/internal/handler/cran_test.go +++ b/internal/handler/cran_test.go @@ -1,8 +1,14 @@ package handler import ( + "io" "log/slog" + "net/http" + "net/http/httptest" + "strings" "testing" + + "github.com/git-pkgs/registries/fetch" ) func TestCRANParseSourceFilename(t *testing.T) { @@ -50,3 +56,68 @@ func TestCRANParseBinaryFilename(t *testing.T) { } } } + +func TestCRANHandler_MacOSTwoSegmentIndexesAndMeta(t *testing.T) { + for _, path := range []string{ + "/bin/macosx/big-sur-arm64/contrib/4.4/PACKAGES", + "/bin/macosx/big-sur-x86_64/contrib/4.4/PACKAGES.gz", + "/bin/macosx/sonoma-arm64/contrib/4.5/PACKAGES.rds", + "/src/contrib/Meta/archive.rds", + "/src/contrib/Meta/current.rds", + } { + t.Run(path, func(t *testing.T) { + assertUpstreamProxied(t, "index", path, + func(proxy *Proxy, upstreamURL string) http.Handler { + h := &CRANHandler{proxy: proxy, upstreamURL: upstreamURL, proxyURL: "http://localhost"} + return h.Routes() + }, + ) + }) + } +} + +func TestCRANHandler_MacOSTwoSegmentBinaryDownload(t *testing.T) { + proxy, _, _, fetcher := setupTestProxy(t) + fetcher.artifact = &fetch.Artifact{ + Body: io.NopCloser(strings.NewReader("fetched binary")), + ContentType: "application/x-gzip", + } + + h := NewCRANHandler(proxy, "http://localhost") + h.upstreamURL = "https://cran.r-project.org" + srv := httptest.NewServer(h.Routes()) + defer srv.Close() + + resp, err := http.Get(srv.URL + "/bin/macosx/big-sur-arm64/contrib/4.4/dplyr_1.1.4.tgz") + if err != nil { + t.Fatalf("request failed: %v", err) + } + _ = resp.Body.Close() + + if resp.StatusCode != http.StatusOK { + t.Errorf("status = %d, want %d", resp.StatusCode, http.StatusOK) + } + want := "https://cran.r-project.org/bin/macosx/big-sur-arm64/contrib/4.4/dplyr_1.1.4.tgz" + if fetcher.fetchedURL != want { + t.Errorf("upstream URL = %q, want %q", fetcher.fetchedURL, want) + } +} + +func TestCRANHandler_MacOSTwoSegmentBinaryCacheIdentity(t *testing.T) { + proxy, db, store, _ := setupTestProxy(t) + seedPackageWithPURL(t, db, store, "cran", "dplyr", "1.1.4_macosx-big-sur-arm64_4.4", "dplyr_1.1.4.tgz", "arm64 binary") + + h := NewCRANHandler(proxy, "http://localhost") + srv := httptest.NewServer(h.Routes()) + defer srv.Close() + + resp, err := http.Get(srv.URL + "/bin/macosx/big-sur-arm64/contrib/4.4/dplyr_1.1.4.tgz") + if err != nil { + t.Fatalf("request failed: %v", err) + } + defer func() { _ = resp.Body.Close() }() + body, _ := io.ReadAll(resp.Body) + if string(body) != "arm64 binary" { + t.Errorf("body = %q, want %q", body, "arm64 binary") + } +} diff --git a/internal/handler/debian.go b/internal/handler/debian.go index dccb823..bcb0439 100644 --- a/internal/handler/debian.go +++ b/internal/handler/debian.go @@ -5,6 +5,7 @@ import ( "encoding/hex" "fmt" "net/http" + pathpkg "path" "regexp" "sort" "strings" @@ -75,7 +76,7 @@ func NewDebianHandler( // Routes returns the HTTP handler for Debian requests. // Mount this at /debian on your router. func (h *DebianHandler) Routes() http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + return rejectQueryChars(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.Method != http.MethodGet && r.Method != http.MethodHead { http.Error(w, "method not allowed", http.StatusMethodNotAllowed) return @@ -108,10 +109,10 @@ func (h *DebianHandler) Routes() http.Handler { } } - // Route based on path type + // Route by filename rather than path prefix because repositories such as + // Docker's nest the pool under dists//. switch { - case strings.HasPrefix(rest, "pool/"): - // Package downloads - cache these + case isDebPackageFile(rest): h.handlePackageDownload(w, r, repository, upstreamURL, rest) case strings.HasPrefix(rest, "dists/"): // Repository metadata - served through the metadata cache @@ -120,7 +121,11 @@ func (h *DebianHandler) Routes() http.Handler { // Other files (like README, etc.) - proxy directly h.proxyFile(w, r, upstreamURL, rest) } - }) + })) +} + +func isDebPackageFile(path string) bool { + return strings.HasSuffix(path, ".deb") } // repositoryNotFound answers a request addressed to a repository that is not @@ -183,13 +188,49 @@ func (h *DebianHandler) handlePackageDownload( // handleMetadata serves repository metadata files through the metadata cache, // so they keep resolving while the upstream archive is unreachable. +// Index files the cached InRelease or Release lists follow that listing (see +// proxyListedIndex). func (h *DebianHandler) handleMetadata( w http.ResponseWriter, r *http.Request, repository, upstreamURL, path string, ) { cacheKey := h.metadataCacheKeyFor(repository, upstreamURL, path) - h.proxy.ProxyCached(w, r, fmt.Sprintf("%s/%s", upstreamURL, path), "debian", cacheKey, "*/*") + fileURL := fmt.Sprintf("%s/%s", upstreamURL, path) + switch pathpkg.Base(path) { + case "InRelease", "Release", "Release.gpg": + h.proxy.ProxyCached(w, r, fileURL, "debian", cacheKey, "*/*") + return + } + release, want := h.releaseListing(r, repository, upstreamURL, path) + h.proxy.proxyListedIndex(w, r, fileURL, "debian", cacheKey, release, want) +} + +// releaseListing finds the cached release file of the suite path belongs +// to and the sha256 it lists for path, nearest directory first, skipping +// release files that list nothing for path (such as the legacy +// per-component Release). Where both InRelease and Release list it, the one +// fetched last wins: apt reads InRelease and debootstrap Release, and a +// client asking for the index has most likely just fetched one of them. +func (h *DebianHandler) releaseListing(r *http.Request, repository, upstreamURL, path string) (*cachedRelease, string) { + for dir := pathpkg.Dir(path); strings.HasPrefix(dir, "dists/"); dir = pathpkg.Dir(dir) { + var found *cachedRelease + var want string + for _, name := range []string{"InRelease", "Release"} { + release := h.proxy.readCachedRelease(r.Context(), "debian", h.metadataCacheKeyFor(repository, upstreamURL, dir+"/"+name)) + if release == nil { + continue + } + sum := debianReleaseSHA256(release.body, strings.TrimPrefix(path, dir+"/")) + if sum != "" && (found == nil || release.fetchedAt.After(found.fetchedAt)) { + found, want = release, sum + } + } + if found != nil { + return found, want + } + } + return nil, "" } // artifactCacheFilename scopes a package by repository, since the same @@ -203,11 +244,11 @@ func (h *DebianHandler) artifactCacheFilename(repository, filename string) strin } // metadataCacheKeyFor returns the metadata cache key for a request. The main -// archive keeps its separator-based key so existing cache entries stay valid; -// a named repository hashes its identity as APKHandler.metadataCacheKey does. +// archive hashes its upstream URL and the path; a named repository hashes its +// identity as APKHandler.metadataCacheKey does. func (h *DebianHandler) metadataCacheKeyFor(repository, upstreamURL, path string) string { if repository == "" { - return strings.ReplaceAll(path, "/", "_") + return hashedCacheKey(upstreamURL, path) } identity := repository + "\x00" + upstreamURL + "\x00" + path digest := sha256.Sum256([]byte(identity)) @@ -226,12 +267,7 @@ var debPackagePattern = regexp.MustCompile(`^(.+)_([^_]+)_([^_]+)\.deb$`) // parsePoolPath extracts package info from a pool path. // Example: pool/main/n/nginx/nginx_1.18.0-6_amd64.deb func (h *DebianHandler) parsePoolPath(path string) (name, version, arch string) { - // Get the filename - idx := strings.LastIndex(path, "/") - if idx < 0 { - return "", "", "" - } - filename := path[idx+1:] + filename := path[strings.LastIndex(path, "/")+1:] // Parse the filename matches := debPackagePattern.FindStringSubmatch(filename) diff --git a/internal/handler/debian_test.go b/internal/handler/debian_test.go index b94919f..54a72b6 100644 --- a/internal/handler/debian_test.go +++ b/internal/handler/debian_test.go @@ -25,6 +25,7 @@ func TestDebianHandler_parsePoolPath(t *testing.T) { "nmap", "7.91+dfsg1+really7.80+dfsg1-2ubuntu0.1", "amd64", }, {"pool/main/o/openssl/openssl_3.0.2-0ubuntu1.15~build1_amd64.deb", "openssl", "3.0.2-0ubuntu1.15~build1", "amd64"}, + {"nginx_1.18.0-6_amd64.deb", "nginx", "1.18.0-6", "amd64"}, {"invalid/path", "", "", ""}, {"pool/main/n/nginx/nginx.deb", "", "", ""}, }) @@ -35,9 +36,11 @@ func TestDebianHandler_Routes(t *testing.T) { assertRoutesBasics(t, h.Routes(), "/dists/stable/Release", "/pool/../../../etc/passwd") } -// TestDebianHandler_LegacyCacheKeysUnchanged pins the cache identities the -// main archive used before named repositories existed. Deployments carry warm -// caches across upgrades, so a changed key here silently discards them. +// TestDebianHandler_LegacyCacheKeysUnchanged pins the artifact cache identity +// the main archive used before named repositories existed. Deployments carry +// warm caches across upgrades, so a changed key here silently discards them. +// Metadata is cheap to refetch; its keys are covered by +// TestMetadataCacheKeysUnambiguous. func TestDebianHandler_LegacyCacheKeysUnchanged(t *testing.T) { const ( poolPath = "pool/main/h/hello/hello_2.10-3_amd64.deb" @@ -54,17 +57,12 @@ func TestDebianHandler_LegacyCacheKeysUnchanged(t *testing.T) { t.Errorf("legacy artifact cache filename = %q, want %q", got, "hello_2.10-3_amd64.deb") } - // Metadata cache: path separators replaced with underscores. - if got := h.metadataCacheKeyFor("", h.upstreamURL, distPath); got != "dists_trixie_InRelease" { - t.Errorf("legacy metadata cache key = %q, want %q", got, "dists_trixie_InRelease") - } - // A named repository must not reuse either identity. if got := h.artifactCacheFilename("security", filename); got == "hello_2.10-3_amd64.deb" { t.Error("named repository reused the legacy artifact cache filename") } - if got := h.metadataCacheKeyFor("security", "https://security.test", distPath); got == "dists_trixie_InRelease" { - t.Error("named repository reused the legacy metadata cache key") + if h.metadataCacheKeyFor("security", "https://security.test", distPath) == h.metadataCacheKeyFor("", h.upstreamURL, distPath) { + t.Error("named repository reused the main archive's metadata cache key") } } @@ -254,6 +252,44 @@ func TestDebianHandler_PackageCacheScopedPerRepository(t *testing.T) { } } +func TestDebianHandler_FlatArchivePackageIsCached(t *testing.T) { + const pkgBody = "docker-ce package bytes" + + var upstreamHits int + + archive := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + upstreamHits++ + _, _ = fmt.Fprint(w, pkgBody) + })) + defer archive.Close() + + proxy, _, _, _ := setupTestProxy(t) + fetcher := fetch.NewFetcher(fetch.WithHTTPClient(archive.Client()), fetch.WithMaxRetries(0)) + proxy.Fetcher = fetcher + t.Cleanup(func() { _ = fetcher.Close() }) + + h := NewDebianHandler(proxy, "http://proxy.example", "https://archive.test", map[string]string{ + "docker": archive.URL, + }) + + for _, path := range []string{ + "/docker/dists/trixie/pool/stable/amd64/docker-ce_5.0.1-1~debian.13~trixie_amd64.deb", + "/docker/foo_1.0_amd64.deb", + } { + for attempt := 1; attempt <= 2; attempt++ { + w := serveDebianRequest(h, path) + if w.Code != http.StatusOK || w.Body.String() != pkgBody { + t.Fatalf("%s request %d: status = %d, body = %q, want 200 %q", + path, attempt, w.Code, w.Body.String(), pkgBody) + } + } + } + + if upstreamHits != 2 { + t.Errorf("upstream fetched %d times for four requests, want 2: the package is not cached", upstreamHits) + } +} + func serveDebianRequest(h *DebianHandler, target string) *httptest.ResponseRecorder { w := httptest.NewRecorder() h.Routes().ServeHTTP(w, httptest.NewRequest(http.MethodGet, target, nil)) diff --git a/internal/handler/denylist_test.go b/internal/handler/denylist_test.go index b415e2b..663d0c3 100644 --- a/internal/handler/denylist_test.go +++ b/internal/handler/denylist_test.go @@ -14,6 +14,7 @@ import ( "github.com/git-pkgs/cooldown" "github.com/git-pkgs/proxy/internal/denylist" + "github.com/git-pkgs/registries/fetch" ) func setTestDenylist(t testing.TB, p *Proxy, packages ...string) { @@ -144,9 +145,9 @@ func TestPyPIDenylistSimpleRepresentations(t *testing.T) { func TestPyPIDenylistJSONMetadata(t *testing.T) { p := testProxy() setTestDenylist(t, p, "pkg:pypi/demo@1.0.0") - h := NewPyPIHandler(p, "https://proxy.example") + h := NewPyPIHandlerWithUpstreams(p, "https://proxy.example", "", "") body := `{"info":{"name":"Demo","version":"1.0.0"},"releases":{"1.0.0":[{"url":"https://files.pythonhosted.org/packages/demo-1.0.0.tar.gz"}],"2.0.0":[]},"urls":[{"url":"https://files.pythonhosted.org/packages/demo-1.0.0.tar.gz"}]}` - out, err := h.rewriteJSONMetadata([]byte(body)) + out, _, err := h.rewriteJSONMetadata([]byte(body)) if err != nil { t.Fatal(err) } @@ -170,7 +171,9 @@ func TestDenylistDownloadRoutes(t *testing.T) { handler func(*Proxy) http.Handler }{ {"npm", "/demo/-/demo-1.0.0.tgz", "demo-1.0.0.tgz", func(p *Proxy) http.Handler { return NewNPMHandler(p, "http://proxy.test", "").Routes() }}, - {"pypi", "/packages/a/b/demo-1.0.0.tar.gz", "demo-1.0.0.tar.gz", func(p *Proxy) http.Handler { return NewPyPIHandler(p, "http://proxy.test").Routes() }}, + {"pypi", "/packages/a/b/demo-1.0.0.tar.gz", "demo-1.0.0.tar.gz", func(p *Proxy) http.Handler { + return NewPyPIHandlerWithUpstreams(p, "http://proxy.test", "", "").Routes() + }}, {"cargo", "/crates/demo/1.0.0/download", "demo-1.0.0.crate", func(p *Proxy) http.Handler { return NewCargoHandler(p, "http://proxy.test", "", "").Routes() }}, {"deb", "/pool/main/d/demo/demo_1.0.0_amd64.deb", "demo_1.0.0_amd64.deb", func(p *Proxy) http.Handler { return NewDebianHandler(p, "http://proxy.test", "", nil).Routes() }}, } { @@ -229,8 +232,12 @@ func TestDenylistMalformedMetadataFailsClosed(t *testing.T) { handler func(*Proxy) http.Handler }{ {"npm", "/demo", `{"versions":`, contentTypeJSON, func(p *Proxy) http.Handler { return NewNPMHandler(p, "https://proxy.test", "").Routes() }}, - {"pypi-json", "/pypi/demo/json", `{"releases":`, contentTypeJSON, func(p *Proxy) http.Handler { return NewPyPIHandler(p, "https://proxy.test").Routes() }}, - {"pypi-simple", "/simple/demo/", `{"files":{}}`, pypiSimpleJSON, func(p *Proxy) http.Handler { return NewPyPIHandler(p, "https://proxy.test").Routes() }}, + {"pypi-json", "/pypi/demo/json", `{"releases":`, contentTypeJSON, func(p *Proxy) http.Handler { + return NewPyPIHandlerWithUpstreams(p, "https://proxy.test", "", "").Routes() + }}, + {"pypi-simple", "/simple/demo/", `{"files":{}}`, pypiSimpleJSON, func(p *Proxy) http.Handler { + return NewPyPIHandlerWithUpstreams(p, "https://proxy.test", "", "").Routes() + }}, } { t.Run(tc.name, func(t *testing.T) { p := testProxy() @@ -246,3 +253,175 @@ func TestDenylistMalformedMetadataFailsClosed(t *testing.T) { }) } } + +// Denylist entries must match however the ecosystem spells the name or +// version in download URLs. +func TestDenylistMatchesEcosystemSpellings(t *testing.T) { + pypi := func(p *Proxy) http.Handler { + return NewPyPIHandlerWithUpstreams(p, "http://proxy.test", "", "").Routes() + } + for _, tc := range []struct { + name, entry, path string + ecosystem, pkg string + version, filename string + handler func(*Proxy) http.Handler + }{ + {"pypi wheel", "pkg:pypi/zope.interface@6.0", "/packages/a/b/zope_interface-6.0-py3-none-any.whl", + "pypi", "zope_interface", "6.0", "zope_interface-6.0-py3-none-any.whl", pypi}, + {"pypi dotted sdist", "pkg:pypi/zope-interface@6.0", "/packages/a/b/zope.interface-6.0.tar.gz", + "pypi", "zope.interface", "6.0", "zope.interface-6.0.tar.gz", pypi}, + {"nuget", "pkg:nuget/Newtonsoft.Json@13.0.1-Beta", "/v3-flatcontainer/newtonsoft.json/13.0.1-beta/newtonsoft.json.13.0.1-beta.nupkg", + "nuget", "newtonsoft.json", "13.0.1-beta", "newtonsoft.json.13.0.1-beta.nupkg", + func(p *Proxy) http.Handler { return NewNuGetHandler(p, "http://proxy.test").Routes() }}, + {"gem platform", "pkg:gem/nokogiri@1.16.0", "/gems/nokogiri-1.16.0-x86_64-linux.gem", + "gem", "nokogiri", "1.16.0-x86_64-linux", "nokogiri-1.16.0-x86_64-linux.gem", + func(p *Proxy) http.Handler { return NewGemHandler(p, "http://proxy.test").Routes() }}, + {"conda any channel", "pkg:conda/numpy@1.26.4", "/conda-forge/linux-64/numpy-1.26.4-py311_0.conda", + "conda", "conda-forge/numpy", "1.26.4", "numpy-1.26.4-py311_0.conda", + func(p *Proxy) http.Handler { return NewCondaHandler(p, "http://proxy.test").Routes() }}, + {"conda channel qualifier", "pkg:conda/numpy@1.26.4?channel=conda-forge", "/conda-forge/linux-64/numpy-1.26.4-py311_0.conda", + "conda", "conda-forge/numpy", "1.26.4", "numpy-1.26.4-py311_0.conda", + func(p *Proxy) http.Handler { return NewCondaHandler(p, "http://proxy.test").Routes() }}, + {"gem name with digit segment", "pkg:gem/devise-2fa@1.0.0", "/gems/devise-2fa-1.0.0.gem", + "gem", "devise-2fa", "1.0.0", "devise-2fa-1.0.0.gem", + func(p *Proxy) http.Handler { return NewGemHandler(p, "http://proxy.test").Routes() }}, + {"go case-escaped version", "pkg:golang/github.com/example/mod@v1.0.0-RC1", "/github.com/example/mod/@v/v1.0.0-!r!c1.zip", + "golang", "github.com/example/mod", "v1.0.0-!r!c1", "mod@v1.0.0-!r!c1.zip", + func(p *Proxy) http.Handler { return NewGoHandler(p, "http://proxy.test").Routes() }}, + {"go lowercase rule", "pkg:golang/github.com/example/mod@v1.0.0", "/github.com/!example/mod/@v/v1.0.0.zip", + "golang", "github.com/Example/mod", "v1.0.0", goZipFilename("github.com/Example/mod", "v1.0.0"), + func(p *Proxy) http.Handler { return NewGoHandler(p, "http://proxy.test").Routes() }}, + {"go mixed-case rule", "pkg:golang/github.com/Example/mod@v1.0.0", "/github.com/example/mod/@v/v1.0.0.zip", + "golang", "github.com/example/mod", "v1.0.0", "mod@v1.0.0.zip", + func(p *Proxy) http.Handler { return NewGoHandler(p, "http://proxy.test").Routes() }}, + {"oci repository path", "pkg:oci/library/alpine@" + ociTestDigest, "/library/alpine/blobs/" + ociTestDigest, + "oci", "library/alpine", ociTestDigest, ociTestDigest, + func(p *Proxy) http.Handler { + return NewContainerHandlerWithRegistry(p, "http://proxy.test", "https://registry.invalid").Routes() + }}, + } { + t.Run(tc.name, func(t *testing.T) { + // The seeded artifact would be served if the entry didn't match. + p, db, store, fetcher := setupTestProxy(t) + fetcher.fetchErr = errors.New("offline") + seedPackage(t, db, store, tc.ecosystem, tc.pkg, tc.version, tc.filename, "cached content") + setTestDenylist(t, p, tc.entry) + w := httptest.NewRecorder() + tc.handler(p).ServeHTTP(w, httptest.NewRequest(http.MethodGet, tc.path, nil)) + if w.Code != http.StatusForbidden { + t.Fatalf("denied download status=%d body=%s", w.Code, w.Body.String()) + } + }) + } +} + +const ociTestDigest = "sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef" + +// Packagist keeps a tag's leading v in the version it lists, and so in the +// download URL the proxy hands out. +func TestComposerDenylistMatchesTagPrefix(t *testing.T) { + var srv *httptest.Server + srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/p2/symfony/console.json": + _, _ = fmt.Fprintf(w, `{"packages":{"symfony/console":[{"version":"v6.1.7","version_normalized":"6.1.7.0","dist":{"url":%q,"type":"zip"}}]}}`, + srv.URL+"/archives/console.zip") + case "/archives/console.zip": + _, _ = io.WriteString(w, "archive") + default: + http.NotFound(w, r) + } + })) + t.Cleanup(srv.Close) + p, _, _, _ := setupTestProxy(t) + p.Fetcher = fetch.NewFetcher(fetch.WithHTTPClient(srv.Client()), fetch.WithMaxRetries(0)) + setTestDenylist(t, p, "pkg:composer/symfony/console@6.1.7") + h := NewComposerHandlerWithUpstreams(p, "http://proxy.test", srv.URL, srv.URL).Routes() + w := httptest.NewRecorder() + h.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/files/symfony/console/v6.1.7/console.zip", nil)) + if w.Code != http.StatusForbidden { + t.Fatalf("status=%d body=%s", w.Code, w.Body.String()) + } +} + +// Swift archives are cached under pkg:generic/swift-registry/{scope}.{name}, +// which is also what streaming checks. +func TestSwiftDenylistBlocksArchive(t *testing.T) { + for _, stream := range []bool{false, true} { + for _, entry := range []string{"pkg:swift/Apple/Example@1.2.3", "pkg:generic/swift-registry/apple.example@1.2.3"} { + t.Run(fmt.Sprintf("stream=%t/%s", stream, entry), func(t *testing.T) { + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + _, _ = io.WriteString(w, `{"id":"apple.example","version":"1.2.3","resources":[{"name":"source-archive","type":"application/zip","checksum":"`+strings.Repeat("0", 64)+`"}]}`) + })) + t.Cleanup(upstream.Close) + p, _, _, fetcher := setupTestProxy(t) + fetcher.artifact = &fetch.Artifact{Body: io.NopCloser(strings.NewReader("archive")), Size: 7} + p.StreamArtifacts = stream + setTestDenylist(t, p, entry) + req := httptest.NewRequest(http.MethodGet, "/apple/example/1.2.3.zip", nil) + req.Header.Set("Accept", swiftAcceptArchive) + w := httptest.NewRecorder() + NewSwiftHandler(p, "http://proxy.test", upstream.URL).Routes().ServeHTTP(w, req) + if w.Code != http.StatusForbidden || fetcher.fetchCalled { + t.Fatalf("status=%d fetched=%t body=%s", w.Code, fetcher.fetchCalled, w.Body.String()) + } + }) + } + } +} + +// A denied digest is refused as a manifest as well as a blob, whether the +// client names it or a tag resolves to it. +func TestContainerDenylistBlocksManifests(t *testing.T) { + manifest := `{"schemaVersion":2}` + digest := sha256Digest([]byte(manifest)) + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set(headerContentType, "application/vnd.oci.image.manifest.v1+json") + w.Header().Set("Docker-Content-Digest", digest) + _, _ = io.WriteString(w, manifest) + })) + t.Cleanup(upstream.Close) + for _, tc := range []struct{ entry, reference string }{ + {"pkg:oci/library/alpine@" + digest, digest}, + {"pkg:oci/library/alpine@" + digest, "3.19"}, + {"pkg:oci/library/alpine@3.19", "3.19"}, + } { + t.Run(tc.entry+"/"+tc.reference, func(t *testing.T) { + p := testProxy() + p.HTTPClient = upstream.Client() + h := NewContainerHandlerWithRegistry(p, "http://proxy.test", upstream.URL).Routes() + // Cache the manifest first, then deny it. + w := httptest.NewRecorder() + h.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/library/alpine/manifests/"+tc.reference, nil)) + if w.Code != http.StatusOK { + t.Fatalf("allowed status=%d", w.Code) + } + setTestDenylist(t, p, tc.entry) + for _, method := range []string{http.MethodGet, http.MethodHead} { + w = httptest.NewRecorder() + h.ServeHTTP(w, httptest.NewRequest(method, "/library/alpine/manifests/"+tc.reference, nil)) + if w.Code != http.StatusForbidden { + t.Fatalf("%s status=%d body=%s", method, w.Code, w.Body.String()) + } + } + w = httptest.NewRecorder() + h.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/library/alpine/manifests/other", nil)) + if strings.HasPrefix(tc.entry, "pkg:oci/library/alpine@3.19") && w.Code != http.StatusOK { + t.Fatalf("other tag status=%d", w.Code) + } + }) + } +} + +func TestPyPIDenylistSimpleMatchesSeparators(t *testing.T) { + body := `xy` + h, p := setupPyPIHandler(t, func(r *http.Request) (*http.Response, error) { + return pypiHTTPResponse(r, "text/html", body), nil + }) + setTestDenylist(t, p, "pkg:pypi/zope.interface@6.0") + w := httptest.NewRecorder() + h.Routes().ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/simple/zope-interface/", nil)) + if w.Code != http.StatusOK || strings.Contains(w.Body.String(), "6.0") || !strings.Contains(w.Body.String(), "7.0") { + t.Fatalf("status=%d body=%s", w.Code, w.Body.String()) + } +} diff --git a/internal/handler/download_cooldown.go b/internal/handler/download_cooldown.go new file mode 100644 index 0000000..4ede9a8 --- /dev/null +++ b/internal/handler/download_cooldown.go @@ -0,0 +1,159 @@ +package handler + +import ( + "net/http" + "sync" + "time" + + "golang.org/x/sync/singleflight" +) + +// publishTimeLookup reads a version's publish time from upstream metadata. ok +// is false when the metadata has no usable time for the version. withholdUnknown +// marks a listed version missing from stale publish-time metadata. +type publishTimeLookup func() (published time.Time, ok, withholdUnknown bool, err error) + +// downloadVersion names the version an artifact download is for, so its +// cooldown can be checked before the artifact is served. +type downloadVersion struct { + ecosystem string + // policyName is the package name the cooldown policy is keyed by, + // canonicalPackagePURL(ecosystem, policyName). + policyName string + // storedName and version name the versions row the publish time is kept + // in, the same names the artifact is cached under. An empty storedName + // keeps no time, and every check asks lookup. + storedName string + version string + cacheName string + filename string + lookup publishTimeLookup +} + +// withholdInCooldown reports whether a download is inside the cooldown +// window, or a lookup failure prevents an uncached download. +func (p *Proxy) withholdInCooldown(w http.ResponseWriter, r *http.Request, d downloadVersion) bool { + withheld, err := p.versionInCooldown(d) + if err != nil { + if !p.serveCachedDespiteCooldownError(w, r, d.ecosystem, d.cacheName, d.version, d.filename, err) { + p.writeCooldownLookupError(w, d.ecosystem, d.policyName, err) + } + return true + } + if !withheld { + return false + } + p.Logger.Info("cooldown: withholding "+d.ecosystem+" download", + "name", d.policyName, "version", d.version) + http.Error(w, ErrVersionNotFound.Error(), http.StatusNotFound) + return true +} + +func (p *Proxy) versionInCooldown(d downloadVersion) (bool, error) { + policyKey := canonicalPackagePURL(d.ecosystem, d.policyName) + if !p.cooldownApplies(d.ecosystem, d.policyName) { + return false, nil + } + + var versionPURL string + if d.storedName != "" { + versionPURL = canonicalVersionPURL(d.ecosystem, d.storedName, d.version) + if ver, err := p.DB.GetVersionByPURL(versionPURL); err == nil && ver != nil && ver.PublishedAt.Valid { + return !p.cooldown().IsAllowed(d.ecosystem, policyKey, ver.PublishedAt.Time), nil + } + } + + published, ok, withholdUnknown, err := d.lookup() + if err != nil { + return false, err + } + if !ok { + return withholdUnknown, nil + } + + if versionPURL != "" { + if err := p.DB.SetVersionPublishedAt(versionPURL, canonicalPackagePURL(d.ecosystem, d.storedName), published); err != nil { + p.Logger.Warn("cooldown: could not store publish time", + "ecosystem", d.ecosystem, "name", d.policyName, "version", d.version, "error", err) + } + } + + return !p.cooldown().IsAllowed(d.ecosystem, policyKey, published), nil +} + +// maxPublishIndexes bounds how many documents publishIndexCache keeps an +// index for. +const maxPublishIndexes = 64 + +// publishIndexCache keeps, for each large metadata document, the publish +// times a download check reads from it, so a document is decompressed and +// parsed once per version from upstream rather than on every download. +// Concurrent checks for a document not indexed yet share one parse. +type publishIndexCache struct { + mu sync.Mutex + entries map[string]publishIndexEntry + group singleflight.Group +} + +type publishIndexEntry struct { + digest string + index any + expires time.Time +} + +// publishIndex reuses parsed documents by digest, or for a minute without one. +func publishIndex[V any](p *Proxy, key string, load func() metadataResult, build func(metadataResult) (V, error)) (V, error) { //nolint:ireturn // Supports timestamp maps and Helm lookups. + c := &p.sharedProxy().publishIndexes + fresh := func() (V, bool) { + c.mu.Lock() + defer c.mu.Unlock() + if e, ok := c.entries[key]; ok && !e.expires.IsZero() && p.clock().Before(e.expires) { + return e.index.(V), true + } + var zero V + return zero, false + } + if index, ok := fresh(); ok { + return index, nil + } + v, err, _ := c.group.Do(key, func() (any, error) { + if index, ok := fresh(); ok { + return index, nil + } + res := load() + if res.err == nil && res.digest != "" { + c.mu.Lock() + entry, ok := c.entries[key] + c.mu.Unlock() + if ok && entry.digest == res.digest { + return entry.index, nil + } + } + index, err := build(res) + if err != nil { + return nil, err + } + c.mu.Lock() + defer c.mu.Unlock() + if c.entries == nil { + c.entries = make(map[string]publishIndexEntry) + } + if _, ok := c.entries[key]; !ok && len(c.entries) >= maxPublishIndexes { + for evict := range c.entries { + delete(c.entries, evict) + break + } + } + entry := publishIndexEntry{digest: res.digest, index: index} + if res.digest == "" || !p.CacheMetadata { + entry.expires = p.clock().Add(time.Minute) + } + c.entries[key] = entry + return index, nil + }) + if err != nil { + var zero V + return zero, err + } + return v.(V), nil +} diff --git a/internal/handler/download_cooldown_cache_test.go b/internal/handler/download_cooldown_cache_test.go new file mode 100644 index 0000000..d51b862 --- /dev/null +++ b/internal/handler/download_cooldown_cache_test.go @@ -0,0 +1,115 @@ +package handler + +import ( + "errors" + "fmt" + "net/http" + "net/http/httptest" + "testing" + "time" +) + +func TestGemDownloadSharesPublishTimeMetadata(t *testing.T) { + u, proxy, h := gemCacheSetup(t) + wantStatus(t, serveGet(t, h, gemInfoPath), http.StatusOK, "") + seedPackage(t, proxy.DB, proxy.Storage.(*mockStorage), "gem", "testgem", "1.0.0", "testgem-1.0.0.gem", "gem bytes") + wantStatus(t, serveGet(t, h, "/gems/testgem-1.0.0.gem"), http.StatusOK, "") + if n, _ := u.counts(gemVersionsPath); n != 1 { + t.Fatalf("versions API fetched %d times, want 1", n) + } +} + +type downloadPublishTimeCase struct { + name string + down bool + absent bool + untimed bool + refresh bool + wantStatus int +} + +func TestDownloadCooldownRefreshesMissingPublishTimes(t *testing.T) { + for _, c := range downloadCooldownCases() { + if c.ecosystem != "gem" && c.ecosystem != "hex" { + continue + } + for _, scenario := range []downloadPublishTimeCase{ + {name: "refreshed times", refresh: true, wantStatus: http.StatusNotFound}, + {name: "stale times and listed version", down: true, wantStatus: http.StatusNotFound}, + {name: "stale times and absent version", down: true, absent: true, wantStatus: http.StatusOK}, + {name: "fresh times without version", wantStatus: http.StatusOK}, + {name: "stale times with untimed version", down: true, untimed: true, wantStatus: http.StatusOK}, + } { + for _, cached := range []bool{false, true} { + if !cached && scenario.wantStatus == http.StatusOK { + continue + } + t.Run(fmt.Sprintf("%s/%s/cached=%t", c.ecosystem, scenario.name, cached), func(t *testing.T) { + assertDownloadPublishTime(t, c, scenario, cached) + }) + } + } + } +} + +func assertDownloadPublishTime(t *testing.T, c downloadCooldownCase, scenario downloadPublishTimeCase, cached bool) { + t.Helper() + u := newCooldownCountingUpstream(t) + proxy := cooldownCacheProxy(t, u) + fetcher := proxy.Fetcher.(*mockFetcher) + fetcher.fetchErr = errors.New("unchecked artifact download") + h := c.handler(proxy, u.URL) + docPath, timesPath := "/info/demo", "/api/v1/versions/demo.json" + if c.ecosystem == "hex" { + docPath, timesPath = "/packages/demo", "/api/packages/demo" + } + oldTimes := map[string]time.Time{cooldownOldVersion: time.Now().Add(-30 * 24 * time.Hour)} + if scenario.untimed { + oldTimes[cooldownRecentVersion] = time.Time{} + } + setDownloadMetadata(t, u, c, docPath, oldTimes) + setDownloadMetadata(t, u, c, timesPath, oldTimes) + wantStatus(t, serveGet(t, h, docPath), http.StatusOK, "") + + newTimes := map[string]time.Time{ + cooldownOldVersion: oldTimes[cooldownOldVersion], + cooldownUntimed: time.Now().Add(-time.Minute), + } + if !scenario.absent { + newTimes[cooldownRecentVersion] = time.Now().Add(-time.Hour) + } + setDownloadMetadata(t, u, c, docPath, newTimes) + expireCachedMetadata(t, proxy, c.ecosystem, docPath[1:]) + if scenario.refresh { + setDownloadMetadata(t, u, c, timesPath, newTimes) + } + u.setDown(timesPath, scenario.down) + if cached { + c.seedCachedArtifact(t, proxy, cooldownRecentVersion) + } + wantStatus(t, serveGet(t, h, c.path(cooldownRecentVersion)), scenario.wantStatus, "") + if fetcher.fetchCalled { + t.Error("fetched an unchecked artifact") + } + if n, _ := u.counts(timesPath); n != 2 { + t.Errorf("publish times fetched %d times, want 2", n) + } +} + +func setDownloadMetadata(t *testing.T, u *cooldownCountingUpstream, c downloadCooldownCase, path string, times map[string]time.Time) { + t.Helper() + w := httptest.NewRecorder() + c.metadata(w, httptest.NewRequest(http.MethodGet, path, nil), times) + wantStatus(t, w, http.StatusOK, "") + u.set(path, w.Body.Bytes()) +} + +func TestHexDownloadSharesPublishTimeMetadata(t *testing.T) { + u, proxy, h, _ := hexCacheSetup(t, 0) + wantStatus(t, serveGet(t, h, hexPackagePath), http.StatusOK, "") + seedPackage(t, proxy.DB, proxy.Storage.(*mockStorage), "hex", "testpkg", "1.0.0", "testpkg-1.0.0.tar", "hex bytes") + wantStatus(t, serveGet(t, h, "/tarballs/testpkg-1.0.0.tar"), http.StatusOK, "") + if n, _ := u.counts(hexAPIPath); n != 1 { + t.Fatalf("Hex API fetched %d times, want 1", n) + } +} diff --git a/internal/handler/download_cooldown_errors_test.go b/internal/handler/download_cooldown_errors_test.go new file mode 100644 index 0000000..b214db2 --- /dev/null +++ b/internal/handler/download_cooldown_errors_test.go @@ -0,0 +1,101 @@ +package handler + +import ( + "fmt" + "net/http" + "net/http/httptest" + "sync/atomic" + "testing" + "time" + + "github.com/git-pkgs/cooldown" + registryclient "github.com/git-pkgs/registries/client" +) + +func TestDownloadCooldownLookupFailures(t *testing.T) { + for _, c := range downloadCooldownCases() { + for _, failure := range []string{"upstream error", "invalid metadata", "rate limited"} { + for _, cached := range []bool{false, true} { + t.Run(fmt.Sprintf("%s/%s/cached=%t", c.ecosystem, failure, cached), func(t *testing.T) { + assertDownloadLookupFailure(t, c, failure, cached) + }) + } + } + } +} + +func assertDownloadLookupFailure(t *testing.T, c downloadCooldownCase, failure string, cached bool) { + t.Helper() + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + if failure == "upstream error" { + w.WriteHeader(http.StatusInternalServerError) + } + _, _ = w.Write([]byte("invalid metadata")) + })) + t.Cleanup(upstream.Close) + proxy, _, _, fetcher := setupTestProxy(t) + proxy.Cooldown = &cooldown.Config{Default: "7d"} + proxy.HTTPClient = upstream.Client() + if failure == "rate limited" { + proxy.HTTPClient = &http.Client{Transport: roundTripperFunc(func(_ *http.Request) (*http.Response, error) { + return nil, ®istryclient.HeldError{Host: "upstream.example", Until: time.Now().Add(time.Minute), RetryAfter: time.Minute} + })} + } + if cached { + c.seedCachedArtifact(t, proxy, cooldownRecentVersion) + } + w := serveGet(t, c.handler(proxy, upstream.URL), c.path(cooldownRecentVersion)) + want := http.StatusBadGateway + if failure == "rate limited" { + want = http.StatusServiceUnavailable + } + if cached { + want = http.StatusOK + if w.Body.Len() == 0 { + t.Fatal("cached artifact body is empty") + } + } + wantStatus(t, w, want, "") + if fetcher.fetchCalled { + t.Fatal("lookup failure fetched an unchecked artifact") + } +} + +func TestDownloadPublishIndexesHaveShortTTLWithoutMetadataCache(t *testing.T) { + for _, c := range downloadCooldownCases() { + if c.ecosystem != "conda" && c.ecosystem != "helm" { + continue + } + t.Run(c.ecosystem, func(t *testing.T) { + var calls atomic.Int64 + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + calls.Add(1) + c.metadata(w, r, map[string]time.Time{ + cooldownOldVersion: time.Now().Add(-30 * 24 * time.Hour), + cooldownRecentVersion: time.Now().Add(-time.Hour), + }) + })) + t.Cleanup(upstream.Close) + proxy, _, _, _ := setupTestProxy(t) + proxy.HTTPClient = upstream.Client() + proxy.Cooldown = &cooldown.Config{Default: "7d"} + clock := &testClock{t: time.Now()} + proxy.now = clock.now + c.seedCachedArtifact(t, proxy, cooldownOldVersion) + c.seedCachedArtifact(t, proxy, cooldownRecentVersion) + h := c.handler(proxy, upstream.URL) + for range 3 { + wantStatus(t, serveGet(t, h, c.path(cooldownOldVersion)), http.StatusOK, "") + wantStatus(t, serveGet(t, h, c.path(cooldownRecentVersion)), http.StatusNotFound, "") + } + if n := calls.Load(); n != 1 { + t.Fatalf("index downloads within TTL = %d, want 1", n) + } + clock.advance(time.Minute + time.Second) + wantStatus(t, serveGet(t, h, c.path(cooldownRecentVersion)), http.StatusNotFound, "") + if n := calls.Load(); n != 2 { + t.Errorf("index downloads after expiry = %d, want 2", n) + } + }) + } +} diff --git a/internal/handler/download_cooldown_test.go b/internal/handler/download_cooldown_test.go new file mode 100644 index 0000000..1fd915f --- /dev/null +++ b/internal/handler/download_cooldown_test.go @@ -0,0 +1,483 @@ +package handler + +import ( + "compress/gzip" + "encoding/json" + "errors" + "fmt" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/git-pkgs/cooldown" +) + +// Versions every download cooldown fixture lists: one published before the +// window, one inside it, and one without a publish time. +const ( + cooldownOldVersion = "1.0.0" + cooldownRecentVersion = "2.0.0" + cooldownUntimed = "3.0.0" +) + +// downloadCooldownCase drives one ecosystem's artifact endpoint. The package +// is always named demo, so the policy key is pkg:{ecosystem}/demo. +type downloadCooldownCase struct { + ecosystem string + // cachedName is the name the artifact is cached under, and keepsTime + // whether the publish time is kept in its versions row. + cachedName string + keepsTime bool + // artifactVersion maps a release to the version the artifact is cached + // under, and filename and path to its file and download path. + artifactVersion func(version string) string + filename func(version string) string + path func(version string) string + // metadata serves the upstream document holding the publish times; a + // zero time is listed without one. + metadata func(w http.ResponseWriter, r *http.Request, times map[string]time.Time) + handler func(proxy *Proxy, upstreamURL string) http.Handler +} + +func sameVersion(version string) string { return version } + +func chartContent(version string) string { return "chart " + version } + +func downloadCooldownCases() []downloadCooldownCase { + return []downloadCooldownCase{ + { + ecosystem: "cargo", + cachedName: "demo", + keepsTime: true, + artifactVersion: sameVersion, + filename: func(v string) string { return "demo-" + v + ".crate" }, + path: func(v string) string { return "/crates/demo/" + v + "/download" }, + metadata: cargoCooldownMetadata, + handler: func(p *Proxy, u string) http.Handler { return NewCargoHandler(p, "http://proxy", u, u).Routes() }, + }, + { + ecosystem: "gem", + cachedName: "demo", + keepsTime: true, + // Platform gems carry the platform in the filename and the + // cached version, but not in the versions API number. + artifactVersion: func(v string) string { return v + "-x86_64-linux" }, + filename: func(v string) string { return "demo-" + v + "-x86_64-linux.gem" }, + path: func(v string) string { return "/gems/demo-" + v + "-x86_64-linux.gem" }, + metadata: gemCooldownMetadata, + handler: func(p *Proxy, u string) http.Handler { return NewGemHandlerWithUpstream(p, "http://proxy", u).Routes() }, + }, + { + ecosystem: "hex", + cachedName: "demo", + keepsTime: true, + artifactVersion: sameVersion, + filename: func(v string) string { return "demo-" + v + ".tar" }, + path: func(v string) string { return "/tarballs/demo-" + v + ".tar" }, + metadata: hexCooldownMetadata, + handler: func(p *Proxy, u string) http.Handler { + return NewHexHandlerWithUpstreams(p, "http://proxy", u, u).Routes() + }, + }, + { + ecosystem: "pub", + cachedName: "demo", + keepsTime: true, + artifactVersion: sameVersion, + filename: func(v string) string { return "demo-" + v + ".tar.gz" }, + path: func(v string) string { return "/packages/demo/versions/" + v + ".tar.gz" }, + metadata: pubCooldownMetadata, + handler: func(p *Proxy, u string) http.Handler { return NewPubHandlerWithUpstream(p, "http://proxy", u).Routes() }, + }, + { + // Conda caches under {channel}/{name}, but the policy is keyed by + // the name alone, as the repodata filter keys it. Each build has + // its own timestamp, so none is kept in the version's row. + ecosystem: "conda", + cachedName: "conda-forge/demo", + artifactVersion: sameVersion, + filename: func(v string) string { return "noarch/demo-" + v + "-py_0.conda" }, + path: func(v string) string { return "/conda-forge/noarch/demo-" + v + "-py_0.conda" }, + metadata: condaCooldownMetadata, + handler: func(p *Proxy, u string) http.Handler { + return NewCondaHandlerWithUpstream(p, "http://proxy", u).Routes() + }, + }, + { + // Helm caches charts under the repository and digest, so the + // chart name and time come from the index on every check. + cachedName: "stable", + ecosystem: "helm", + artifactVersion: func(v string) string { return sha256Hex(chartContent(v)) }, + filename: func(v string) string { return "demo-" + v + ".tgz" }, + path: func(v string) string { return "/stable/charts/" + sha256Hex(chartContent(v)) + "/demo-" + v + ".tgz" }, + metadata: helmCooldownMetadata, + handler: func(p *Proxy, u string) http.Handler { + return NewHelmHandler(p, "http://proxy", map[string]string{"stable": u + "/charts"}).Routes() + }, + }, + } +} + +func cargoCooldownMetadata(w http.ResponseWriter, r *http.Request, times map[string]time.Time) { + if r.URL.Path != "/de/mo/demo" { + http.NotFound(w, r) + return + } + for version, published := range times { + line := map[string]string{"name": "demo", "vers": version} + if !published.IsZero() { + line["pubtime"] = published.Format(time.RFC3339) + } + encoded, _ := json.Marshal(line) + _, _ = fmt.Fprintf(w, "%s\n", encoded) + } +} + +func gemCooldownMetadata(w http.ResponseWriter, r *http.Request, times map[string]time.Time) { + if r.URL.Path == "/info/demo" { + _, _ = fmt.Fprintln(w, "---") + for version := range times { + _, _ = fmt.Fprintf(w, "%s-x86_64-linux |checksum:a\n", version) + } + return + } + if r.URL.Path != "/api/v1/versions/demo.json" { + http.NotFound(w, r) + return + } + var versions []gemVersion + for version, published := range times { + v := gemVersion{Number: version, Platform: "x86_64-linux"} + if !published.IsZero() { + v.CreatedAt = published.Format(time.RFC3339) + } + versions = append(versions, v) + } + _ = json.NewEncoder(w).Encode(versions) +} + +func hexCooldownMetadata(w http.ResponseWriter, r *http.Request, times map[string]time.Time) { + if r.URL.Path == "/packages/demo" { + var versions []string + for version := range times { + versions = append(versions, version) + } + _, _ = w.Write(buildHexSigned(buildHexPackage("demo", versions))) + return + } + if r.URL.Path != "/api/packages/demo" { + http.NotFound(w, r) + return + } + var pkg hexPackageAPI + for version, published := range times { + release := hexRelease{Version: version} + if !published.IsZero() { + release.InsertedAt = published.Format(time.RFC3339Nano) + } + pkg.Releases = append(pkg.Releases, release) + } + _ = json.NewEncoder(w).Encode(pkg) +} + +func pubCooldownMetadata(w http.ResponseWriter, r *http.Request, times map[string]time.Time) { + if r.URL.Path != "/api/packages/demo" { + http.NotFound(w, r) + return + } + var versions []map[string]string + for version, published := range times { + v := map[string]string{"version": version} + if !published.IsZero() { + v["published"] = published.Format(time.RFC3339) + } + versions = append(versions, v) + } + _ = json.NewEncoder(w).Encode(map[string]any{"name": "demo", "versions": versions}) +} + +func condaCooldownMetadata(w http.ResponseWriter, r *http.Request, times map[string]time.Time) { + if r.URL.Path != "/conda-forge/noarch/repodata.json" { + http.NotFound(w, r) + return + } + packages := map[string]map[string]any{} + for version, published := range times { + entry := map[string]any{"name": "demo", "version": version} + if !published.IsZero() { + entry["timestamp"] = published.UnixMilli() + } + packages["demo-"+version+"-py_0.conda"] = entry + } + // The download check asks for gzip, as proxyCached does. + w.Header().Set(headerContentEncoding, "gzip") + gz := gzip.NewWriter(w) + _ = json.NewEncoder(gz).Encode(map[string]any{"packages.conda": packages}) + _ = gz.Close() +} + +func helmCooldownMetadata(w http.ResponseWriter, r *http.Request, times map[string]time.Time) { + if r.URL.Path != "/charts/index.yaml" { + http.NotFound(w, r) + return + } + _, _ = fmt.Fprintln(w, "apiVersion: v1\nentries:\n demo:") + for version, published := range times { + _, _ = fmt.Fprintf(w, " - digest: %s\n urls: [demo-%s.tgz]\n version: %s\n", + sha256Hex(chartContent(version)), version, version) + if !published.IsZero() { + _, _ = fmt.Fprintf(w, " created: %s\n", published.Format(time.RFC3339)) + } + } +} + +// seedCachedArtifact caches the release's artifact the way an earlier, +// cooldown-free download would have. +func (c downloadCooldownCase) seedCachedArtifact(t *testing.T, proxy *Proxy, version string) { + t.Helper() + db, store := proxy.DB, proxy.Storage.(*mockStorage) + content := "artifact " + version + if c.ecosystem == "helm" { + content = chartContent(version) + } + seedPackage(t, db, store, c.ecosystem, c.cachedName, c.artifactVersion(version), c.filename(version), content) +} + +// TestDownloadCooldownWithholdsCachedArtifacts requests each ecosystem's +// artifact endpoint for a version that was cached before the cooldown was +// raised. A version inside the window must be withheld, from the cache too; +// one past the window, or without a known publish time, is served. +func TestDownloadCooldownWithholdsCachedArtifacts(t *testing.T) { + now := time.Now().Truncate(time.Second) + times := map[string]time.Time{ + cooldownOldVersion: now.Add(-30 * 24 * time.Hour), + cooldownRecentVersion: now.Add(-time.Hour), + cooldownUntimed: {}, + } + statuses := map[string]int{ + cooldownOldVersion: http.StatusOK, + cooldownRecentVersion: http.StatusNotFound, + cooldownUntimed: http.StatusOK, + } + + for _, c := range downloadCooldownCases() { + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + c.metadata(w, r, times) + })) + t.Cleanup(upstream.Close) + + for _, version := range []string{cooldownOldVersion, cooldownRecentVersion, cooldownUntimed} { + t.Run(c.ecosystem+"/"+version, func(t *testing.T) { + proxy, db, _, fetcher := setupTestProxy(t) + proxy.HTTPClient = upstream.Client() + fetcher.fetchErr = errors.New("artifact must be served from the cache") + c.seedCachedArtifact(t, proxy, version) + proxy.Cooldown = &cooldown.Config{Packages: map[string]string{ + canonicalPackagePURL(c.ecosystem, "demo"): "7d", + }} + + w := httptest.NewRecorder() + c.handler(proxy, upstream.URL).ServeHTTP(w, httptest.NewRequest(http.MethodGet, c.path(version), nil)) + + if w.Code != statuses[version] { + t.Fatalf("status = %d, want %d (body %q)", w.Code, statuses[version], w.Body.String()) + } + if w.Code == http.StatusOK && w.Body.String() == "" { + t.Error("served an empty body") + } + if !c.keepsTime || times[version].IsZero() { + return + } + ver, err := db.GetVersionByPURL(canonicalVersionPURL(c.ecosystem, c.cachedName, c.artifactVersion(version))) + if err != nil || ver == nil || !ver.PublishedAt.Valid { + t.Fatalf("publish time not stored: %+v, %v", ver, err) + } + if got, want := ver.PublishedAt.Time, times[version]; !got.Equal(want) { + t.Errorf("stored publish time = %v, want %v", got, want) + } + }) + } + } +} + +// TestDownloadCooldownUsesStoredPublishTime checks that a stored publish +// time decides the download without asking the upstream, which here fails. +func TestDownloadCooldownUsesStoredPublishTime(t *testing.T) { + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + http.Error(w, "unavailable", http.StatusServiceUnavailable) + })) + t.Cleanup(upstream.Close) + + for _, c := range downloadCooldownCases() { + if !c.keepsTime { + continue + } + t.Run(c.ecosystem, func(t *testing.T) { + proxy, db, _, fetcher := setupTestProxy(t) + proxy.HTTPClient = upstream.Client() + fetcher.fetchErr = errors.New("artifact must be served from the cache") + c.seedCachedArtifact(t, proxy, cooldownRecentVersion) + versionPURL := canonicalVersionPURL(c.ecosystem, c.cachedName, c.artifactVersion(cooldownRecentVersion)) + packagePURL := canonicalPackagePURL(c.ecosystem, c.cachedName) + if err := db.SetVersionPublishedAt(versionPURL, packagePURL, time.Now().Add(-time.Hour)); err != nil { + t.Fatalf("seeding publish time: %v", err) + } + proxy.Cooldown = &cooldown.Config{Default: "7d"} + + w := httptest.NewRecorder() + c.handler(proxy, upstream.URL).ServeHTTP(w, httptest.NewRequest(http.MethodGet, c.path(cooldownRecentVersion), nil)) + if w.Code != http.StatusNotFound { + t.Fatalf("status = %d, want 404 (body %q)", w.Code, w.Body.String()) + } + }) + } +} + +// TestDownloadCooldownOtherPackagesSkipLookup checks that a download outside +// every cooldown rule is served without reading upstream metadata. Helm +// needs the index to learn the chart name, so it is left out. +func TestDownloadCooldownOtherPackagesSkipLookup(t *testing.T) { + for _, c := range downloadCooldownCases() { + if c.ecosystem == "helm" { + continue + } + t.Run(c.ecosystem, func(t *testing.T) { + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + t.Errorf("unexpected upstream request %s", r.URL.Path) + http.Error(w, "unexpected", http.StatusInternalServerError) + })) + t.Cleanup(upstream.Close) + proxy, _, _, fetcher := setupTestProxy(t) + proxy.HTTPClient = upstream.Client() + fetcher.fetchErr = errors.New("artifact must be served from the cache") + c.seedCachedArtifact(t, proxy, cooldownRecentVersion) + proxy.Cooldown = &cooldown.Config{Packages: map[string]string{ + canonicalPackagePURL(c.ecosystem, "other"): "7d", + }} + + w := httptest.NewRecorder() + c.handler(proxy, upstream.URL).ServeHTTP(w, httptest.NewRequest(http.MethodGet, c.path(cooldownRecentVersion), nil)) + if w.Code != http.StatusOK { + t.Fatalf("status = %d, want 200 (body %q)", w.Code, strings.TrimSpace(w.Body.String())) + } + }) + } +} + +// TestCondaDownloadCooldownPerBuild checks that builds of one version are +// judged by their own timestamps, whichever is requested first: a rebuild +// inside the window is withheld and an old build stays available. +func TestCondaDownloadCooldownPerBuild(t *testing.T) { + now := time.Now() + repodata := map[string]any{"packages.conda": map[string]any{ + "demo-1.0.0-py_0.conda": map[string]any{"name": "demo", "version": "1.0.0", "timestamp": now.Add(-400 * 24 * time.Hour).UnixMilli()}, + "demo-1.0.0-py_1.conda": map[string]any{"name": "demo", "version": "1.0.0", "timestamp": now.Add(-time.Hour).UnixMilli()}, + }} + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + _ = json.NewEncoder(w).Encode(repodata) + })) + t.Cleanup(upstream.Close) + + builds := map[string]int{"py_0": http.StatusOK, "py_1": http.StatusNotFound} + for _, order := range [][]string{{"py_0", "py_1", "py_0"}, {"py_1", "py_0", "py_1"}} { + t.Run(strings.Join(order, ","), func(t *testing.T) { + proxy, db, store, fetcher := setupTestProxy(t) + proxy.HTTPClient = upstream.Client() + fetcher.fetchErr = errors.New("artifact must be served from the cache") + for build := range builds { + filename := "noarch/demo-1.0.0-" + build + ".conda" + seedPackage(t, db, store, "conda", "conda-forge/demo", "1.0.0", filename, "artifact "+build) + } + proxy.Cooldown = &cooldown.Config{Default: "7d"} + h := NewCondaHandlerWithUpstream(proxy, "http://proxy", upstream.URL).Routes() + + for _, build := range order { + w := httptest.NewRecorder() + h.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/conda-forge/noarch/demo-1.0.0-"+build+".conda", nil)) + if w.Code != builds[build] { + t.Fatalf("%s status = %d, want %d", build, w.Code, builds[build]) + } + } + }) + } +} + +// TestPublishIndexBuildsOncePerDocument checks that an index is reused for +// the same document, rebuilt for a new one, and kept briefly without a digest. +func TestPublishIndexBuildsOncePerDocument(t *testing.T) { + proxy, _, _, _ := setupTestProxy(t) + proxy.CacheMetadata = true + builds := 0 + build := func(res metadataResult) (map[string]bool, error) { + builds++ + return map[string]bool{string(res.body): true}, nil + } + steps := []struct { + res metadataResult + want string + wantBuilds int + }{ + {metadataResult{body: []byte("a"), digest: "d1"}, "a", 1}, + {metadataResult{body: []byte("ignored"), digest: "d1"}, "a", 1}, + {metadataResult{body: []byte("b"), digest: "d2"}, "b", 2}, + {metadataResult{body: []byte("c")}, "c", 3}, + {metadataResult{body: []byte("c")}, "c", 3}, + } + for i, step := range steps { + got, err := publishIndex(proxy, "key", func() metadataResult { return step.res }, build) + if err != nil || !got[step.want] || builds != step.wantBuilds { + t.Fatalf("step %d: publishIndex = %v, %v after %d builds, want %q after %d", i, got, err, builds, step.want, step.wantBuilds) + } + } +} + +// TestCondaDownloadCooldownPastMetadataLimit checks that a cached package is +// withheld when its repodata is over metadata_max_size, as the repodata +// endpoint hides it: once only decompressed, and once already compressed. +func TestCondaDownloadCooldownPastMetadataLimit(t *testing.T) { + plain := largeRepodata(500) + compressed := gzipPayload(t, plain) + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set(headerContentEncoding, "gzip") + _, _ = w.Write(compressed) + })) + t.Cleanup(upstream.Close) + + for _, tt := range []struct { + name string + limit int64 + }{ + {"decompressed over the limit", int64(len(compressed)) + 1}, + {"compressed over the limit", int64(len(compressed)) - 1}, + } { + t.Run(tt.name, func(t *testing.T) { + proxy, db, store, fetcher := setupTestProxy(t) + proxy.HTTPClient = upstream.Client() + proxy.CacheMetadata = true + proxy.MetadataTTL = time.Hour + proxy.MetadataMaxSize = tt.limit + fetcher.fetchErr = errors.New("artifact must be served from the cache") + for _, file := range []string{"pkg-0-old.conda", "pkg-1-new.conda"} { + seedPackage(t, db, store, "conda", "conda-forge/pkg", strings.Split(file, "-")[1], "linux-64/"+file, "artifact "+file) + } + proxy.Cooldown = &cooldown.Config{Default: "3d"} + h := NewCondaHandlerWithUpstream(proxy, "http://proxy", upstream.URL).Routes() + + w := httptest.NewRecorder() + h.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/conda-forge/linux-64/repodata.json", nil)) + if w.Code != http.StatusOK || strings.Contains(w.Body.String(), "pkg-1-new.conda") { + t.Fatalf("repodata status = %d, want 200 without pkg-1-new.conda", w.Code) + } + for file, want := range map[string]int{"pkg-0-old.conda": http.StatusOK, "pkg-1-new.conda": http.StatusNotFound} { + w := httptest.NewRecorder() + h.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/conda-forge/linux-64/"+file, nil)) + if w.Code != want { + t.Errorf("%s status = %d, want %d (body %q)", file, w.Code, want, w.Body.String()) + } + } + }) + } +} diff --git a/internal/handler/download_test.go b/internal/handler/download_test.go index 2ac8ace..c53585e 100644 --- a/internal/handler/download_test.go +++ b/internal/handler/download_test.go @@ -1,7 +1,9 @@ package handler import ( + "crypto/sha1" "database/sql" + "encoding/hex" "fmt" "io" "net/http" @@ -12,10 +14,9 @@ import ( "time" "github.com/git-pkgs/proxy/internal/database" - "github.com/git-pkgs/proxy/internal/httpclient" "github.com/git-pkgs/proxy/internal/metrics" - "github.com/git-pkgs/proxy/internal/storage" "github.com/git-pkgs/purl" + registryclient "github.com/git-pkgs/registries/client" "github.com/git-pkgs/registries/fetch" ) @@ -44,7 +45,7 @@ func seedPackageWithPURL(t *testing.T, db *database.DB, store *mockStorage, ecos t.Fatalf("failed to upsert version: %v", err) } - storagePath := storage.ArtifactPath(ecosystem, "", name, version, filename) + storagePath := ecosystem + "/" + name + "/" + version + "/" + filename store.files[storagePath] = []byte(content) sharedArtifact := testArtifact(content, versionPURL, filename, "application/octet-stream") @@ -489,7 +490,7 @@ func TestPubHandler_CacheMiss(t *testing.T) { func TestCondaHandler_DownloadCacheHit(t *testing.T) { proxy, db, store, _ := setupTestProxy(t) - seedPackageWithPURL(t, db, store, "conda", "main/numpy", "1.24.0", "numpy-1.24.0-py311h64a7726_0.conda", "conda pkg") + seedPackageWithPURL(t, db, store, "conda", "main/numpy", "1.24.0", "linux-64/numpy-1.24.0-py311h64a7726_0.conda", "conda pkg") h := NewCondaHandler(proxy, "http://localhost") srv := httptest.NewServer(h.Routes()) @@ -512,7 +513,7 @@ func TestCondaHandler_DownloadCacheHit(t *testing.T) { func TestCondaHandler_DownloadTarBz2CacheHit(t *testing.T) { proxy, db, store, _ := setupTestProxy(t) - seedPackageWithPURL(t, db, store, "conda", "main/scipy", "1.11.0", "scipy-1.11.0-py311hb2e3ea1_0.tar.bz2", "tar bz2 data") + seedPackageWithPURL(t, db, store, "conda", "main/scipy", "1.11.0", "linux-64/scipy-1.11.0-py311hb2e3ea1_0.tar.bz2", "tar bz2 data") h := NewCondaHandler(proxy, "http://localhost") srv := httptest.NewServer(h.Routes()) @@ -872,6 +873,109 @@ func TestMavenHandler_ChecksumsCachedAsArtifacts(t *testing.T) { } } +// Any file named after its coordinates goes through the download path, so +// policy applies to it whatever its extension. +func TestMavenHandler_DeniedVersionBlocksEveryArtifactFile(t *testing.T) { + proxy, _, _, fetcher := setupTestProxy(t) + setTestDenylist(t, proxy, "pkg:maven/com.google.protobuf/protoc@3.21.0") + + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + t.Errorf("denied file %s proxied to upstream", r.URL.Path) + })) + defer upstream.Close() + + h := NewMavenHandler(proxy, "http://localhost", upstream.URL, upstream.URL) + proxy.HTTPClient = upstream.Client() + + for _, name := range []string{ + "protoc-3.21.0-linux-x86_64.exe", + "protoc-3.21.0-linux-x86_64.exe.sha1", + "protoc-3.21.0.hpi", + "protoc-3.21.0.pom", + } { + fetcher.fetchCalled = false + w := httptest.NewRecorder() + h.Routes().ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/com/google/protobuf/protoc/3.21.0/"+name, nil)) + if w.Code != http.StatusForbidden { + t.Errorf("GET %s: status = %d, want %d", name, w.Code, http.StatusForbidden) + } + if fetcher.fetchCalled { + t.Errorf("GET %s: fetched a denied file", name) + } + } +} + +func TestMavenHandler_UncommonArtifactFilesCached(t *testing.T) { + proxy, _, _, fetcher := setupTestProxy(t) + + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + t.Errorf("artifact file %s proxied without caching", r.URL.Path) + })) + defer upstream.Close() + + h := NewMavenHandler(proxy, "http://localhost", upstream.URL, upstream.URL) + proxy.HTTPClient = upstream.Client() + + for _, path := range []string{ + "/com/google/protobuf/protoc/3.21.0/protoc-3.21.0-linux-x86_64.exe", + "/com/google/protobuf/protoc/3.21.0/protoc-3.21.0-linux-x86_64.exe.sha1", + "/org/example/plugin/1.0/plugin-1.0.hpi", + "/org/example/native/1.0/native-1.0-linux.so", + "/org/example/lib/1.0-SNAPSHOT/lib-1.0-20240101.120000-1.exe", + } { + for i := range 2 { + fetcher.artifact = &fetch.Artifact{ + Body: io.NopCloser(strings.NewReader("binary")), + ContentType: "application/octet-stream", + } + fetcher.fetchCalled = false + + w := httptest.NewRecorder() + h.Routes().ServeHTTP(w, httptest.NewRequest(http.MethodGet, path, nil)) + + if w.Code != http.StatusOK || w.Body.String() != "binary" { + t.Errorf("GET %s: status %d body %q", path, w.Code, w.Body.String()) + } + if fetcher.fetchCalled != (i == 0) { + t.Errorf("GET %s request %d: fetched = %v, want %v", path, i+1, fetcher.fetchCalled, i == 0) + } + } + } +} + +func TestMavenHandler_NonArtifactPathsProxied(t *testing.T) { + proxy, _, _, fetcher := setupTestProxy(t) + + var proxied []string + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + proxied = append(proxied, r.URL.Path) + _, _ = fmt.Fprint(w, "listing") + })) + defer upstream.Close() + + h := NewMavenHandler(proxy, "http://localhost", upstream.URL, upstream.URL) + proxy.HTTPClient = upstream.Client() + + paths := []string{ + "/com/google/protobuf/protoc/3.21.0/", + "/com/google/protobuf/protoc/", + "/archetype-catalog.xml", + } + for _, path := range paths { + w := httptest.NewRecorder() + h.Routes().ServeHTTP(w, httptest.NewRequest(http.MethodGet, path, nil)) + if w.Code != http.StatusOK || w.Body.String() != "listing" { + t.Errorf("GET %s: status %d body %q", path, w.Code, w.Body.String()) + } + } + if len(proxied) != len(paths) { + t.Errorf("proxied %v, want %v", proxied, paths) + } + if fetcher.fetchCalled { + t.Error("non-artifact path went through the download path") + } +} + func TestMavenHandler_CacheMiss(t *testing.T) { proxy, _, _, fetcher := setupTestProxy(t) fetcher.artifact = &fetch.Artifact{ @@ -972,8 +1076,7 @@ func TestMavenHandler_GradlePluginMarkerFallbackAndCache(t *testing.T) { func TestMavenHandler_GradlePluginMarkerMetadataFallback(t *testing.T) { paths := map[string]string{ - "/com/diffplug/spotless/com.diffplug.spotless.gradle.plugin/maven-metadata.xml": "", - "/com/diffplug/spotless/com.diffplug.spotless.gradle.plugin/maven-metadata.xml.sha1": "sha1", + "/com/diffplug/spotless/com.diffplug.spotless.gradle.plugin/maven-metadata.xml": "", } primaryHits := map[string]int{} @@ -1029,6 +1132,18 @@ func TestMavenHandler_GradlePluginMarkerMetadataFallback(t *testing.T) { t.Fatalf("GET %s did not hit plugin portal fallback", reqPath) } } + + // The checksum is computed from the metadata served from the fallback. + resp, err := http.Get(srv.URL + "/com/diffplug/spotless/com.diffplug.spotless.gradle.plugin/maven-metadata.xml.sha1") + if err != nil { + t.Fatal(err) + } + body, _ := io.ReadAll(resp.Body) + _ = resp.Body.Close() + sum := sha1.Sum([]byte("")) //nolint:gosec // Maven publishes SHA-1 checksums. + if resp.StatusCode != http.StatusOK || string(body) != hex.EncodeToString(sum[:]) { + t.Fatalf("GET maven-metadata.xml.sha1: %d %q, want %x", resp.StatusCode, body, sum) + } } func TestMavenHandler_GradlePluginChecksumFallbackToPluginPortal(t *testing.T) { @@ -1278,7 +1393,7 @@ func TestRPMHandler_DownloadCacheMiss(t *testing.T) { } func TestMavenHandler_UpstreamHeldReturns503(t *testing.T) { - held := &httpclient.HeldError{Host: "repo1.maven.org", Until: time.Now().Add(90 * time.Second), RetryAfter: 90 * time.Second} + held := ®istryclient.HeldError{Host: "repo1.maven.org", Until: time.Now().Add(90 * time.Second), RetryAfter: 90 * time.Second} t.Run("artifact", func(t *testing.T) { proxy, _, _, fetcher := setupTestProxy(t) @@ -1326,7 +1441,7 @@ func (fn roundTripperFunc) RoundTrip(req *http.Request) (*http.Response, error) func TestMavenHandler_HeldArtifactMissesSkipCircuitBreaker(t *testing.T) { proxy, _, _, _ := setupTestProxy(t) upstreamCalls := 0 - gate := httpclient.NewRateLimitGate(roundTripperFunc(func(req *http.Request) (*http.Response, error) { + gate := registryclient.NewRateLimitGate(roundTripperFunc(func(req *http.Request) (*http.Response, error) { upstreamCalls++ return &http.Response{ StatusCode: http.StatusTooManyRequests, @@ -1366,15 +1481,19 @@ func TestMavenHandler_HeldArtifactMissesSkipCircuitBreaker(t *testing.T) { } func TestHandlers_UpstreamHeldMetadataReturns503(t *testing.T) { - held := &httpclient.HeldError{Host: "upstream.example", Until: time.Now().Add(42 * time.Second), RetryAfter: 42 * time.Second} + held := ®istryclient.HeldError{Host: "upstream.example", Until: time.Now().Add(42 * time.Second), RetryAfter: 42 * time.Second} tests := []struct { name string handler func(*Proxy) http.Handler path string }{ {"npm metadata", func(p *Proxy) http.Handler { return NewNPMHandler(p, "http://localhost", "").Routes() }, "/lodash"}, - {"pypi simple", func(p *Proxy) http.Handler { return NewPyPIHandler(p, "http://localhost").Routes() }, "/simple/requests/"}, - {"pypi json", func(p *Proxy) http.Handler { return NewPyPIHandler(p, "http://localhost").Routes() }, "/pypi/requests/json"}, + {"pypi simple", func(p *Proxy) http.Handler { + return NewPyPIHandlerWithUpstreams(p, "http://localhost", "", "").Routes() + }, "/simple/requests/"}, + {"pypi json", func(p *Proxy) http.Handler { + return NewPyPIHandlerWithUpstreams(p, "http://localhost", "", "").Routes() + }, "/pypi/requests/json"}, {"cargo index", func(p *Proxy) http.Handler { return NewCargoHandler(p, "http://localhost", "", "").Routes() }, "/se/rd/serde"}, diff --git a/internal/handler/fetch_lease.go b/internal/handler/fetch_lease.go new file mode 100644 index 0000000..e49b7ef --- /dev/null +++ b/internal/handler/fetch_lease.go @@ -0,0 +1,183 @@ +package handler + +import ( + "context" + "crypto/rand" + "crypto/sha256" + "encoding/hex" + "time" + + "github.com/git-pkgs/proxy/internal/database" + "github.com/git-pkgs/proxy/internal/metrics" +) + +// Instances sharing a Postgres database coalesce cache misses through fetch +// leases, as coalesceFetch and coalesceMetadata do within one instance. The +// instance that runs the fetch holds the lease for the miss and renews it +// while it downloads. Another instance missing the same key waits for the +// stored result and serves that, or takes the lease over if the holder +// releases it without storing anything or stops renewing it. +var ( + fetchLeaseTTL = 30 * time.Second + fetchLeaseRenew = 10 * time.Second + // The wait for another instance's fetch polls the cache, starting + // quickly for small files and backing off for large ones. + fetchLeasePollMin = 50 * time.Millisecond + fetchLeasePollMax = 2 * time.Second +) + +// fetchLeaseKey turns a coalescing key, which can hold long URLs and NUL +// separators, into a fixed-size table key. +func fetchLeaseKey(kind, key string) string { + sum := sha256.Sum256([]byte(kind + "\x00" + key)) + return hex.EncodeToString(sum[:]) +} + +func newLeaseOwner() string { + var b [16]byte + _, _ = rand.Read(b[:]) + return hex.EncodeToString(b[:]) +} + +// fetchLeasesEnabled reports whether misses are coalesced across instances. +func (p *Proxy) fetchLeasesEnabled() bool { + return p.DB != nil && p.DB.Dialect() == database.DialectPostgres +} + +// leaseOutcome says how a caller goes on after awaitFetchLease. +type leaseOutcome int + +const ( + // leaseFetch: this instance fetches, and calls release afterwards. + leaseFetch leaseOutcome = iota + // leaseStored: ready found the result another instance stored. + leaseStored + // leaseFailed: the fetch this caller waited on failed. It fetches + // without the lease, as every instance that waited does at the same + // time, or serves a stale copy, rather than queueing behind the others. + leaseFailed +) + +// awaitFetchLease takes the lease on key before this instance fetches it from +// upstream. While another instance holds the lease, it polls ready, which +// reports whether that instance's result is now stored and, if so, keeps it +// for the caller. release is to be called with whether the fetch failed once +// it is done; err is set when ctx ended while waiting. +// +// A failing lease query is logged and the fetch goes ahead without a lease, +// so a database hiccup costs a duplicate fetch rather than the request. +func (p *Proxy) awaitFetchLease(ctx context.Context, kind, key string, ready func() bool) (release func(failed bool), outcome leaseOutcome, err error) { + noop := func(bool) {} + if !p.fetchLeasesEnabled() { + return noop, leaseFetch, nil + } + leaseKey := fetchLeaseKey(kind, key) + owner := newLeaseOwner() + delay := fetchLeasePollMin + waited := false + for { + acquired, err := p.DB.AcquireFetchLease(leaseKey, owner, fetchLeaseTTL) + if err != nil { + p.Logger.Warn("fetch lease unavailable, fetching without it", "kind", kind, "error", err) + return noop, leaseFetch, nil + } + if acquired { + // The holder may have stored the result and released the lease + // between this caller's last poll and taking it. + if waited && ready() { + p.releaseFetchLease(leaseKey, owner) + return noop, leaseStored, nil + } + return p.holdFetchLease(leaseKey, owner), leaseFetch, nil + } + if !waited { + metrics.RecordFetchLeaseWait(kind) + waited = true + } + outcome, done, err := p.waitForLeaseHolder(ctx, kind, leaseKey, ready, &delay) + if done || err != nil { + return noop, outcome, err + } + } +} + +// waitForLeaseHolder polls ready while another instance holds the lease on +// leaseKey. It is done when ready found the result, when the fetch it waited +// on failed, or when the lease can't be read; otherwise it returns once the +// lease is free to take. +func (p *Proxy) waitForLeaseHolder(ctx context.Context, kind, leaseKey string, ready func() bool, delay *time.Duration) (outcome leaseOutcome, done bool, err error) { + holder := "" + for { + current, failed, held, err := p.DB.FetchLeaseHolder(leaseKey) + if err != nil { + p.Logger.Warn("fetch lease unavailable, fetching without it", "kind", kind, "error", err) + return leaseFetch, true, nil + } + if failed && current == holder { + return leaseFailed, true, nil + } + if !held || failed { + // Released, expired, or failed before this caller waited on + // it: free to take. + return leaseFetch, false, nil + } + holder = current + timer := time.NewTimer(*delay) + select { + case <-ctx.Done(): + timer.Stop() + return leaseFetch, true, ctx.Err() + case <-timer.C: + } + if ready() { + return leaseStored, true, nil + } + *delay = min(*delay+*delay, fetchLeasePollMax) + } +} + +// holdFetchLease renews owner's lease on leaseKey until the returned release +// is called. release drops the lease, or marks it failed so instances +// waiting on it stop waiting. +func (p *Proxy) holdFetchLease(leaseKey, owner string) func(failed bool) { + stop := make(chan struct{}) + done := make(chan struct{}) + go func() { + defer close(done) + ticker := time.NewTicker(fetchLeaseRenew) + defer ticker.Stop() + for { + select { + case <-stop: + return + case <-ticker.C: + // A lease that lapsed, say after a long pause, lets another + // instance fetch too. That costs a duplicate fetch, nothing + // else, so the fetch here carries on either way. + if held, err := p.DB.RenewFetchLease(leaseKey, owner, fetchLeaseTTL); err != nil || !held { + p.Logger.Debug("fetch lease lapsed", "error", err) + } + } + } + }() + return func(failed bool) { + close(stop) + <-done + if !failed { + p.releaseFetchLease(leaseKey, owner) + return + } + if err := p.DB.FailFetchLease(leaseKey, owner); err != nil { + // Waiting instances take the lease once it expires. + p.Logger.Warn("failed to mark fetch lease failed", "error", err) + } + } +} + +func (p *Proxy) releaseFetchLease(leaseKey, owner string) { + if err := p.DB.ReleaseFetchLease(leaseKey, owner); err != nil { + // The lease expires on its own; until then other instances wait + // on it and then fetch. + p.Logger.Warn("failed to release fetch lease", "error", err) + } +} diff --git a/internal/handler/fetch_lease_test.go b/internal/handler/fetch_lease_test.go new file mode 100644 index 0000000..0be8d42 --- /dev/null +++ b/internal/handler/fetch_lease_test.go @@ -0,0 +1,428 @@ +package handler + +import ( + "context" + "errors" + "io" + "log/slog" + "net/http" + "net/http/httptest" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/git-pkgs/proxy/internal/database" + "github.com/git-pkgs/proxy/internal/metrics" + "github.com/git-pkgs/registries/fetch" + "github.com/prometheus/client_golang/prometheus/testutil" +) + +// gateFetcher counts upstream fetches, signals entered when the first one +// starts and holds every fetch until release is closed. +type gateFetcher struct { + calls atomic.Int64 + content string + err error + entered chan struct{} + release chan struct{} + once sync.Once + opened sync.Once +} + +// newGateFetcher returns a gateFetcher that is released when the test ends +// at the latest, so a failing test does not leave fetches hanging. +func newGateFetcher(t *testing.T, content string, err error) *gateFetcher { + f := &gateFetcher{content: content, err: err, entered: make(chan struct{}), release: make(chan struct{})} + t.Cleanup(f.open) + return f +} + +func (f *gateFetcher) open() { f.opened.Do(func() { close(f.release) }) } + +func (f *gateFetcher) Fetch(ctx context.Context, url string) (*fetch.Artifact, error) { + return f.FetchWithHeaders(ctx, url, nil) +} + +func (f *gateFetcher) FetchWithHeaders(ctx context.Context, _ string, _ http.Header) (*fetch.Artifact, error) { + f.calls.Add(1) + f.once.Do(func() { close(f.entered) }) + select { + case <-f.release: + case <-ctx.Done(): + return nil, ctx.Err() + } + if f.err != nil { + return nil, f.err + } + return &fetch.Artifact{Body: io.NopCloser(strings.NewReader(f.content)), ContentType: "application/gzip"}, nil +} + +func (f *gateFetcher) Head(context.Context, string) (int64, string, error) { return 0, "", nil } + +// sharedInstances returns two proxies sharing one Postgres database and one +// storage, as two replicas would. It skips without PROXY_DATABASE_URL. +func sharedInstances(t *testing.T) (*Proxy, *Proxy, *database.DB) { + t.Helper() + db := openTestPostgres(t) + if db == nil { + t.Skip("PROXY_DATABASE_URL not set") + } + store := newMockStorage() + logger := slog.New(slog.NewTextHandler(io.Discard, nil)) + a := NewProxy(db, store, &mockFetcher{}, fetch.NewResolver(), logger) + b := NewProxy(db, store, &mockFetcher{}, fetch.NewResolver(), logger) + return a, b, db +} + +const leaseTestURL = "https://registry.npmjs.org/left-pad/-/left-pad-1.3.0.tgz" + +func fetchLeftPad(p *Proxy) (string, error) { + return fetchLeftPadCtx(context.Background(), p) +} + +func fetchLeftPadCtx(ctx context.Context, p *Proxy) (string, error) { + res, err := p.GetOrFetchArtifactFromURL(ctx, "npm", "left-pad", "1.3.0", "left-pad-1.3.0.tgz", leaseTestURL) + if err != nil { + return "", err + } + defer func() { _ = res.Reader.Close() }() + b, err := io.ReadAll(res.Reader) + return string(b), err +} + +type fetchResult struct { + body string + err error +} + +func goFetchLeftPad(ctx context.Context, p *Proxy) chan fetchResult { + ch := make(chan fetchResult, 1) + go func() { + body, err := fetchLeftPadCtx(ctx, p) + ch <- fetchResult{body, err} + }() + return ch +} + +// waitForLeaseWaits returns once the lease wait counter for kind has passed +// from. +func waitForLeaseWaits(t *testing.T, kind string, from float64) { + t.Helper() + deadline := time.Now().Add(5 * time.Second) + for testutil.ToFloat64(metrics.FetchLeaseWaits.WithLabelValues(kind)) <= from { + if time.Now().After(deadline) { + t.Fatal("timed out waiting for the second instance to wait on the lease") + } + time.Sleep(time.Millisecond) + } +} + +// waitForArtifactWaiters returns once n callers have joined p's fetch of +// left-pad. +func waitForArtifactWaiters(t *testing.T, p *Proxy, n int) { + t.Helper() + deadline := time.Now().Add(5 * time.Second) + for { + p.fetchMu.Lock() + joined := 0 + for _, f := range p.inFlight { + joined += f.waiters + } + p.fetchMu.Unlock() + if joined >= n { + return + } + if time.Now().After(deadline) { + t.Fatal("timed out waiting for a caller to join the fetch") + } + time.Sleep(time.Millisecond) + } +} + +func TestFetchLeaseCoalescesArtifactAcrossInstances(t *testing.T) { + a, b, _ := sharedInstances(t) + const content = "left-pad tarball" + fa := newGateFetcher(t, content, nil) + fb := newGateFetcher(t, content, nil) + fb.open() + a.Fetcher, b.Fetcher = fa, fb + + waits := testutil.ToFloat64(metrics.FetchLeaseWaits.WithLabelValues(metrics.CacheKindArtifact)) + resA := goFetchLeftPad(context.Background(), a) + <-fa.entered + resB := goFetchLeftPad(context.Background(), b) + waitForLeaseWaits(t, metrics.CacheKindArtifact, waits) + fa.open() + + for name, ch := range map[string]chan fetchResult{"a": resA, "b": resB} { + r := <-ch + if r.err != nil || r.body != content { + t.Errorf("instance %s: body %q, err %v", name, r.body, r.err) + } + } + if got := fa.calls.Load() + fb.calls.Load(); got != 1 { + t.Errorf("upstream fetches = %d (a %d, b %d), want 1", got, fa.calls.Load(), fb.calls.Load()) + } +} + +// TestFetchLeaseFailedFetchLetsOtherInstanceFetch checks that an instance +// waiting on a fetch that fails takes the lease over and fetches itself, +// rather than waiting until the lease expires. +func TestFetchLeaseFailedFetchLetsOtherInstanceFetch(t *testing.T) { + a, b, _ := sharedInstances(t) + const content = "left-pad tarball" + fa := newGateFetcher(t, "", errors.New("upstream down")) + fb := newGateFetcher(t, content, nil) + fb.open() + a.Fetcher, b.Fetcher = fa, fb + + waits := testutil.ToFloat64(metrics.FetchLeaseWaits.WithLabelValues(metrics.CacheKindArtifact)) + resA := goFetchLeftPad(context.Background(), a) + <-fa.entered + resB := goFetchLeftPad(context.Background(), b) + waitForLeaseWaits(t, metrics.CacheKindArtifact, waits) + started := time.Now() + fa.open() + + if r := <-resA; r.err == nil { + t.Error("instance a: want the upstream error") + } + r := <-resB + if r.err != nil || r.body != content { + t.Fatalf("instance b: body %q, err %v", r.body, r.err) + } + if fb.calls.Load() != 1 { + t.Errorf("b's upstream fetches = %d, want 1", fb.calls.Load()) + } + if waited := time.Since(started); waited >= fetchLeaseTTL { + t.Errorf("b waited %s, as long as the lease lasts", waited) + } +} + +// TestFetchLeaseExpiredIsTakenOver checks that a lease left by an instance +// that stopped while fetching holds the others up only until it expires. +func TestFetchLeaseExpiredIsTakenOver(t *testing.T) { + _, b, db := sharedInstances(t) + const content = "left-pad tarball" + fb := newGateFetcher(t, content, nil) + fb.open() + b.Fetcher = fb + + key := artifactCoalesceKey("pkg:npm/left-pad@1.3.0", "left-pad-1.3.0.tgz", leaseTestURL, "", "") + if ok, err := db.AcquireFetchLease(fetchLeaseKey(metrics.CacheKindArtifact, key), "stopped-instance", 300*time.Millisecond); err != nil || !ok { + t.Fatalf("taking the lease for the stopped instance: %v, %v", ok, err) + } + started := time.Now() + body, err := fetchLeftPad(b) + if err != nil || body != content { + t.Fatalf("body %q, err %v", body, err) + } + if waited := time.Since(started); waited < 250*time.Millisecond { + t.Errorf("fetched after %s, before the lease expired; is the test key right?", waited) + } +} + +func TestFetchLeaseCoalescesMetadataAcrossInstances(t *testing.T) { + a, b, _ := sharedInstances(t) + u := newMetadataUpstream(t, http.StatusOK) + var released sync.Once + release := func() { released.Do(func() { close(u.release) }) } + t.Cleanup(release) + for _, p := range []*Proxy{a, b} { + p.HTTPClient = u.Client() + p.CacheMetadata = true + p.MetadataTTL = time.Minute + } + + waits := testutil.ToFloat64(metrics.FetchLeaseWaits.WithLabelValues(metrics.CacheKindMetadata)) + resA := startMetadataCalls(a, context.Background(), 1, u.URL+"/left-pad", "application/json")[0] + <-u.entered + resB := startMetadataCalls(b, context.Background(), 1, u.URL+"/left-pad", "application/json")[0] + waitForLeaseWaits(t, metrics.CacheKindMetadata, waits) + release() + + for name, ch := range map[string]chan metadataCall{"a": resA, "b": resB} { + r := <-ch + if r.err != nil || !strings.Contains(string(r.body), "application/json") { + t.Errorf("instance %s: body %q, err %v", name, r.body, r.err) + } + } + if got := u.calls.Load(); got != 1 { + t.Errorf("upstream metadata requests = %d, want 1", got) + } +} + +// TestFetchLeaseNotUsedWithoutMetadataCache checks that metadata misses are +// not held up when there is no stored copy to wait for. +func TestFetchLeaseNotUsedWithoutMetadataCache(t *testing.T) { + a, b, _ := sharedInstances(t) + u := newMetadataUpstream(t, http.StatusOK) + a.HTTPClient, b.HTTPClient = u.Client(), u.Client() + + resA := startMetadataCalls(a, context.Background(), 1, u.URL+"/left-pad", "application/json")[0] + <-u.entered + resB := startMetadataCalls(b, context.Background(), 1, u.URL+"/left-pad", "application/json")[0] + deadline := time.Now().Add(5 * time.Second) + for u.calls.Load() < 2 { + if time.Now().After(deadline) { + t.Fatal("b did not fetch while a was fetching") + } + time.Sleep(time.Millisecond) + } + close(u.release) + for _, ch := range []chan metadataCall{resA, resB} { + if r := <-ch; r.err != nil { + t.Errorf("unexpected error: %v", r.err) + } + } +} + +// TestFetchLeaseWaitOutlivesDetachedCaller checks that a caller waiting on +// another instance's fetch keeps waiting after its client goes away when its +// fetch is detached, so callers that joined it still get the artifact. +func TestFetchLeaseWaitOutlivesDetachedCaller(t *testing.T) { + a, b, _ := sharedInstances(t) + const content = "left-pad tarball" + fa := newGateFetcher(t, content, nil) + fb := newGateFetcher(t, content, nil) + fb.open() + a.Fetcher, b.Fetcher = fa, fb + + waits := testutil.ToFloat64(metrics.FetchLeaseWaits.WithLabelValues(metrics.CacheKindArtifact)) + resA := goFetchLeftPad(context.Background(), a) + <-fa.entered + leadCtx, cancelLead := context.WithCancel(DetachUpstreamFetch(context.Background())) + defer cancelLead() + resLead := goFetchLeftPad(leadCtx, b) + waitForLeaseWaits(t, metrics.CacheKindArtifact, waits) + resJoined := goFetchLeftPad(context.Background(), b) + waitForArtifactWaiters(t, b, 1) + cancelLead() + fa.open() + <-resLead + + for name, ch := range map[string]chan fetchResult{"a": resA, "b's joined caller": resJoined} { + r := <-ch + if r.err != nil || r.body != content { + t.Errorf("%s: body %q, err %v", name, r.body, r.err) + } + } + if got := fb.calls.Load(); got != 0 { + t.Errorf("b fetched %d times, want 0", got) + } +} + +// TestFetchLeaseFailedFetchWaitersFetchInParallel checks that once a fetch +// fails, the instances waiting on it fetch at the same time rather than one +// after another, so a hanging upstream costs each one timeout. +func TestFetchLeaseFailedFetchWaitersFetchInParallel(t *testing.T) { + a, b, db := sharedInstances(t) + c := NewProxy(db, b.Storage, &mockFetcher{}, fetch.NewResolver(), b.Logger) + const content = "left-pad tarball" + fa := newGateFetcher(t, "", errors.New("upstream down")) + fb := newGateFetcher(t, content, nil) + fc := newGateFetcher(t, content, nil) + a.Fetcher, b.Fetcher, c.Fetcher = fa, fb, fc + + waits := testutil.ToFloat64(metrics.FetchLeaseWaits.WithLabelValues(metrics.CacheKindArtifact)) + resA := goFetchLeftPad(context.Background(), a) + <-fa.entered + resB := goFetchLeftPad(context.Background(), b) + waitForLeaseWaits(t, metrics.CacheKindArtifact, waits) + resC := goFetchLeftPad(context.Background(), c) + waitForLeaseWaits(t, metrics.CacheKindArtifact, waits+1) + fa.open() + if r := <-resA; r.err == nil { + t.Fatal("instance a: want the upstream error") + } + + for name, entered := range map[string]chan struct{}{"b": fb.entered, "c": fc.entered} { + select { + case <-entered: + case <-time.After(5 * time.Second): + t.Fatalf("%s did not fetch while the other waiting instance was fetching", name) + } + } + fb.open() + fc.open() + for name, ch := range map[string]chan fetchResult{"b": resB, "c": resC} { + if r := <-ch; r.err != nil || r.body != content { + t.Errorf("instance %s: body %q, err %v", name, r.body, r.err) + } + } +} + +// TestFetchLeaseFailedMetadataServesStale checks that an instance waiting on +// a metadata fetch that fails serves its stale copy at once, as the holder +// does, instead of asking the failing upstream again. +func TestFetchLeaseFailedMetadataServesStale(t *testing.T) { + a, b, _ := sharedInstances(t) + var status atomic.Int32 + status.Store(http.StatusOK) + var calls atomic.Int32 + entered := make(chan struct{}, 1) + release := make(chan struct{}) + var released sync.Once + open := func() { released.Do(func() { close(release) }) } + t.Cleanup(open) + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + calls.Add(1) + if code := int(status.Load()); code != http.StatusOK { + entered <- struct{}{} + <-release + w.WriteHeader(code) + return + } + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"name":"left-pad"}`)) + })) + t.Cleanup(upstream.Close) + for _, p := range []*Proxy{a, b} { + p.HTTPClient = upstream.Client() + p.CacheMetadata = true + p.MetadataTTL = 50 * time.Millisecond + } + fetchMeta := func(p *Proxy) chan metadataCall { + ch := make(chan metadataCall, 1) + go func() { + body, _, err := p.FetchOrCacheMetadata(context.Background(), "npm", "left-pad", upstream.URL+"/left-pad", "application/json") + ch <- metadataCall{body, err} + }() + return ch + } + if r := <-fetchMeta(a); r.err != nil { + t.Fatalf("seeding the cache: %v", r.err) + } + time.Sleep(100 * time.Millisecond) + + status.Store(http.StatusServiceUnavailable) + waits := testutil.ToFloat64(metrics.FetchLeaseWaits.WithLabelValues(metrics.CacheKindMetadata)) + resA := fetchMeta(a) + <-entered + resB := fetchMeta(b) + waitForLeaseWaits(t, metrics.CacheKindMetadata, waits) + open() + + for name, ch := range map[string]chan metadataCall{"a": resA, "b": resB} { + if r := <-ch; r.err != nil || string(r.body) != `{"name":"left-pad"}` { + t.Errorf("instance %s: body %q, err %v; want the stale copy", name, r.body, r.err) + } + } + if got := calls.Load(); got != 2 { + t.Errorf("upstream requests = %d, want 2: the seed and a's failed refresh", got) + } +} + +func TestFetchLeaseNotUsedOnSQLite(t *testing.T) { + proxy, _, _, _ := setupTestProxy(t) + release, outcome, err := proxy.awaitFetchLease(context.Background(), metrics.CacheKindArtifact, "k", func() bool { + t.Error("ready polled on SQLite") + return false + }) + if err != nil || outcome != leaseFetch { + t.Fatalf("awaitFetchLease = %v, %v; want to fetch at once", outcome, err) + } + release(false) +} diff --git a/internal/handler/filename_download.go b/internal/handler/filename_download.go index fc96586..c37d07d 100644 --- a/internal/handler/filename_download.go +++ b/internal/handler/filename_download.go @@ -3,6 +3,7 @@ package handler import ( "net/http" "strings" + "time" ) type filenameDownload struct { @@ -12,6 +13,9 @@ type filenameDownload struct { parseErr string fetchErr string parse func(string) (name, version string) + // publishTime reads a version's publish time from upstream metadata for + // the download-time cooldown check. + publishTime func(r *http.Request, name, version string) (time.Time, bool, bool, error) } func (p *Proxy) handleFilenameDownload(w http.ResponseWriter, r *http.Request, d filenameDownload) { @@ -27,9 +31,16 @@ func (p *Proxy) handleFilenameDownload(w http.ResponseWriter, r *http.Request, d return } - p.Logger.Info(d.ecosystem+" download request", + p.Logger.Debug(d.ecosystem+" download request", "name", name, "version", version, "filename", filename) + if p.withholdInCooldown(w, r, downloadVersion{ + ecosystem: d.ecosystem, policyName: name, storedName: name, version: version, cacheName: name, filename: filename, + lookup: func() (time.Time, bool, bool, error) { return d.publishTime(r, name, version) }, + }) { + return + } + downloadURL := d.upstreamURL + r.URL.Path result, err := p.GetOrFetchArtifactFromURL( r.Context(), d.ecosystem, name, version, filename, downloadURL, diff --git a/internal/handler/freebsd.go b/internal/handler/freebsd.go new file mode 100644 index 0000000..aceffa4 --- /dev/null +++ b/internal/handler/freebsd.go @@ -0,0 +1,256 @@ +package handler + +import ( + "crypto/sha256" + "encoding/hex" + "errors" + "fmt" + "net/http" + "regexp" + "strings" + + "github.com/git-pkgs/proxy/internal/retention" + "github.com/git-pkgs/purl" +) + +const ( + freebsdEcosystem = "freebsd" + // defaultFreeBSDRepositoryName is the repository name used when no + // upstream.freebsd repositories are configured. + defaultFreeBSDRepositoryName = "freebsd" + // defaultFreeBSDUpstream is the official FreeBSD package mirror. + defaultFreeBSDUpstream = "https://pkg.freebsd.org" + freebsdNamespace = "freebsd" + freebsdMatchCount = 3 // full match + name + version + freebsdHashedDir = "Hashed" + freebsdPackageMedia = "application/octet-stream" +) + +// Packages are stored as pkg:bsd/freebsd/{name}, whichever configured +// repository they came from. +func init() { + retention.Default.Register(retention.Spec{Key: freebsdEcosystem, CanonicalPackage: freebsdRetentionKey}) +} + +// freebsdRetentionKey maps pkg:bsd/freebsd/{name} to the stored package PURL. +// Another namespace, or a name with a slash, can never match a stored package +// and is refused. +func freebsdRetentionKey(p *purl.PURL) (string, bool) { + if p == nil || p.Type != "bsd" || p.Namespace != freebsdNamespace || strings.Contains(p.Name, "/") { + return "", false + } + canonical := purl.MakePURLString(freebsdEcosystem, p.Name, "") + return canonical, canonical != "" +} + +// FreeBSDHandler serves FreeBSD pkg repositories, ports and pkgbase alike. +// Each configured upstream is mounted at /freebsd/{repository}/ and the rest +// of the path mirrors the upstream layout ({ABI}/{repo}/{file}). +// +// Repository catalogues (meta.conf, packagesite.pkg, data.pkg) carry their +// signature inside the archive, so they are served byte for byte through the +// metadata cache. Packages under Hashed/ have the content hash in their name +// and never change, so they go to the artifact cache. Other package files, +// unhashed ones and the bootstrap package under Latest/, can be rebuilt under +// the same name and are passed through after the denylist; while a scanner +// covers freebsd they are refused, since only cached artifacts are scanned. +// Everything else, such as signatures and keys, is passed through. +type FreeBSDHandler struct { + proxy *Proxy + proxyURL string + repositories map[string]string +} + +// NewFreeBSDHandler creates a FreeBSD pkg repository handler. Without +// repositories it serves the official mirror as "freebsd". +func NewFreeBSDHandler(proxy *Proxy, proxyURL string, repositories map[string]string) *FreeBSDHandler { + h := &FreeBSDHandler{ + proxy: proxy, + proxyURL: strings.TrimSuffix(proxyURL, "/"), + repositories: make(map[string]string, len(repositories)), + } + for name, repositoryURL := range repositories { + h.repositories[name] = strings.TrimSuffix(repositoryURL, "/") + } + if len(h.repositories) == 0 { + h.repositories[defaultFreeBSDRepositoryName] = defaultFreeBSDUpstream + } + return h +} + +// Routes returns the HTTP handler for pkg requests. +// Mount this at /freebsd on your router. +func (h *FreeBSDHandler) Routes() http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodGet && r.Method != http.MethodHead { + http.Error(w, "method not allowed", http.StatusMethodNotAllowed) + return + } + + path := strings.TrimPrefix(r.URL.Path, "/") + + // A decoded '?' or '#' would cut the upstream path short and cache one + // file under another file's name. + if containsPathTraversal(path) || strings.ContainsAny(path, "?#") { + http.Error(w, "invalid path", http.StatusBadRequest) + return + } + + repository, rest, ok := strings.Cut(path, "/") + upstreamURL, found := h.repositories[repository] + if !ok || rest == "" || !found { + http.NotFound(w, r) + return + } + + switch { + case isFreeBSDCatalogue(rest): + h.handleMetadata(w, r, repository, upstreamURL, rest) + case isFreeBSDHashedPackage(rest): + h.handlePackageDownload(w, r, repository, upstreamURL, rest) + case isFreeBSDPackageFile(rest): + h.handleUncachedPackage(w, r, upstreamURL, rest) + default: + h.proxyFile(w, r, upstreamURL, rest) + } + }) +} + +// freebsdCataloguePattern matches the files pkg reads to update a repository: +// meta and meta.conf, and the packagesite and data catalogues in the current +// (.pkg) and older (.txz, .tzst) packing formats. +var freebsdCataloguePattern = regexp.MustCompile(`^(?:meta(?:\.conf|\.txz|\.tzst|\.pkg)?|(?:packagesite|data)\.(?:pkg|txz|tzst))$`) + +func freebsdBase(path string) string { + return path[strings.LastIndex(path, "/")+1:] +} + +// isFreeBSDCatalogue reports whether path names a repository catalogue. The +// depth isn't checked, so repositories built with poudriere and served under +// another layout work too; package files are always {name}-{version}.pkg and +// can't take these names. +func isFreeBSDCatalogue(path string) bool { + return freebsdCataloguePattern.MatchString(freebsdBase(path)) +} + +// freebsdHashedPattern matches {name}-{version}~{hash}.pkg. Port versions +// never contain '-', so the version is what follows the last one, e.g. +// zsh-navigation-tools-2.2.7~2$imxi7k7w.pkg or +// FreeBSD-syslogd-man-14.snap20261019150821~2$k6xtent4.pkg. +var freebsdHashedPattern = regexp.MustCompile(`^(.+)-([^-~/]+)~[^~/]+\.pkg$`) + +// isFreeBSDHashedPackage reports whether path names a package in a Hashed/ +// directory: All/Hashed/ for ports, Hashed/ for pkgbase. +func isFreeBSDHashedPackage(path string) bool { + dir := strings.TrimSuffix(path, "/"+freebsdBase(path)) + return freebsdBase(dir) == freebsdHashedDir && freebsdHashedPattern.MatchString(freebsdBase(path)) +} + +// parseFreeBSDPackage returns the name and version of a hashed package file. +func parseFreeBSDPackage(filename string) (name, version string) { + matches := freebsdHashedPattern.FindStringSubmatch(filename) + if len(matches) != freebsdMatchCount { + return "", "" + } + return matches[1], matches[2] +} + +// freebsdUnhashedPattern matches {name}-{version} package files in the current +// (.pkg) and older (.txz, .tzst) packing formats, split at the last '-' like +// freebsdHashedPattern. +var freebsdUnhashedPattern = regexp.MustCompile(`^(.+)-([^-~/]+)\.(?:pkg|txz|tzst)$`) + +// freebsdPackageFilePattern matches every package file name, including +// Latest/pkg.pkg, which has no version. Catalogues match it too and must be +// routed first. +var freebsdPackageFilePattern = regexp.MustCompile(`\.(?:pkg|txz|tzst)$`) + +// isFreeBSDPackageFile reports whether path names a package file. +func isFreeBSDPackageFile(path string) bool { + return freebsdPackageFilePattern.MatchString(freebsdBase(path)) +} + +// parseFreeBSDPackageFile returns the name and version of any package file, +// hashed or not, or empty strings for a file without a version such as +// Latest/pkg.pkg. +func parseFreeBSDPackageFile(filename string) (name, version string) { + if name, version = parseFreeBSDPackage(filename); name != "" { + return name, version + } + matches := freebsdUnhashedPattern.FindStringSubmatch(filename) + if len(matches) != freebsdMatchCount { + return "", "" + } + return matches[1], matches[2] +} + +// errFreeBSDUnscannable refuses package files that can't be cached while +// scanning covers freebsd. +var errFreeBSDUnscannable = errors.New("package file can't be scanned: only packages under Hashed/ are cached and scanned; build the repository with pkg repo --hash") + +// handleUncachedPackage passes a package file outside Hashed/ through. Its +// name may be reused for a rebuild with other bytes, which pkg would then +// reject against the catalogue checksum, so it is never cached. The denylist +// applies when the name carries a version. Scanners only see cached +// artifacts, so the file is refused while one covers freebsd. +func (h *FreeBSDHandler) handleUncachedPackage(w http.ResponseWriter, r *http.Request, upstreamURL, path string) { + name, version := parseFreeBSDPackageFile(freebsdBase(path)) + if name != "" && h.proxy.versionDenied(freebsdEcosystem, name, version) { + h.proxy.serveArtifactError(w, fmt.Errorf("%w: %s", ErrVersionDenied, canonicalVersionPURL(freebsdEcosystem, name, version)), "") + return + } + if h.proxy.Scanners.Covers(freebsdEcosystem) { + h.proxy.Logger.Warn("refusing unscannable freebsd package", "path", path) + JSONError(w, http.StatusForbidden, errFreeBSDUnscannable.Error()) + return + } + h.proxyFile(w, r, upstreamURL, path) +} + +// handlePackageDownload caches hashed packages. The cache key holds the +// repository and full path, since every ABI and repository has its own +// builds. +func (h *FreeBSDHandler) handlePackageDownload(w http.ResponseWriter, r *http.Request, repository, upstreamURL, path string) { + name, version := parseFreeBSDPackage(freebsdBase(path)) + if name == "" { + h.proxyFile(w, r, upstreamURL, path) + return + } + + downloadURL := upstreamURL + "/" + path + cacheFilename := repository + "/" + path + + h.proxy.Logger.Info("freebsd package download", + "repository", repository, "name", name, "version", version) + + result, err := h.proxy.GetOrFetchArtifactFromURL( + r.Context(), freebsdEcosystem, name, version, cacheFilename, downloadURL) + if err != nil { + h.proxy.serveArtifactError(w, err, "failed to fetch package") + return + } + + if result.Artifact.MediaType == "" { + result.Artifact.MediaType = freebsdPackageMedia + } + ServeArtifactRequest(w, r, result) +} + +// handleMetadata serves catalogues unchanged through the metadata cache, +// which keeps their embedded signatures valid. +func (h *FreeBSDHandler) handleMetadata(w http.ResponseWriter, r *http.Request, repository, upstreamURL, path string) { + h.proxy.ProxyCached(w, r, upstreamURL+"/"+path, freebsdEcosystem, + h.metadataCacheKey(repository, upstreamURL, path), "*/*") +} + +// metadataCacheKey hashes repository, upstream URL and path, as APKHandler does. +func (h *FreeBSDHandler) metadataCacheKey(repository, upstreamURL, path string) string { + identity := repository + "\x00" + upstreamURL + "\x00" + path + digest := sha256.Sum256([]byte(identity)) + return hex.EncodeToString(digest[:]) +} + +// proxyFile passes other files through uncached. +func (h *FreeBSDHandler) proxyFile(w http.ResponseWriter, r *http.Request, upstreamURL, path string) { + h.proxy.ProxyFile(w, r, upstreamURL+"/"+path) +} diff --git a/internal/handler/freebsd_test.go b/internal/handler/freebsd_test.go new file mode 100644 index 0000000..4702f34 --- /dev/null +++ b/internal/handler/freebsd_test.go @@ -0,0 +1,407 @@ +package handler + +import ( + "io" + "log/slog" + "net/http" + "net/http/httptest" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/git-pkgs/proxy/internal/config" + "github.com/git-pkgs/proxy/internal/scanner" + "github.com/git-pkgs/purl" + "github.com/git-pkgs/registries/fetch" +) + +const freebsdABI = "/FreeBSD:14:amd64" + +func TestFreeBSDPathClassification(t *testing.T) { + tests := []struct { + path string + catalogue bool + hashed bool + }{ + {"FreeBSD:14:amd64/latest/meta.conf", true, false}, + {"FreeBSD:14:amd64/latest/meta", true, false}, + {"FreeBSD:14:amd64/latest/packagesite.pkg", true, false}, + {"FreeBSD:14:amd64/latest/data.pkg", true, false}, + {"FreeBSD:13:amd64/quarterly/packagesite.txz", true, false}, + {"142amd64-default/packagesite.tzst", true, false}, + {"FreeBSD:14:amd64/latest/All/Hashed/zsh-5.9_5~2$3rwh1rgp.pkg", false, true}, + {"FreeBSD:15:amd64/base_latest/Hashed/FreeBSD-acct-15.snap20261021214449~2$k6xtent4.pkg", false, true}, + {"FreeBSD:14:amd64/latest/All/zsh-5.9_5.pkg", false, false}, + {"FreeBSD:15:amd64/base_latest/FreeBSD-acct-15.snap20261021214449.pkg", false, false}, + {"FreeBSD:14:amd64/latest/Latest/pkg.pkg", false, false}, + {"FreeBSD:14:amd64/latest/Latest/pkg.pkg.sig", false, false}, + {"FreeBSD:14:amd64/latest/All/Hashed/no-hash.pkg", false, false}, + } + for _, tt := range tests { + if got := isFreeBSDCatalogue(tt.path); got != tt.catalogue { + t.Errorf("isFreeBSDCatalogue(%q) = %v, want %v", tt.path, got, tt.catalogue) + } + if got := isFreeBSDHashedPackage(tt.path); got != tt.hashed { + t.Errorf("isFreeBSDHashedPackage(%q) = %v, want %v", tt.path, got, tt.hashed) + } + } +} + +func TestParseFreeBSDPackage(t *testing.T) { + tests := []struct { + filename, name, version string + }{ + {"zsh-5.9_5~2$3rwh1rgp.pkg", "zsh", "5.9_5"}, + {"zsh-navigation-tools-2.2.7~2$imxi7k7w.pkg", "zsh-navigation-tools", "2.2.7"}, + {"py311-requests-2.32.3_1,1~2$abcdefgh.pkg", "py311-requests", "2.32.3_1,1"}, + {"FreeBSD-syslogd-man-14.snap20261019150821~2$k6xtent4.pkg", "FreeBSD-syslogd-man", "14.snap20261019150821"}, + {"nohash-1.0.pkg", "", ""}, + } + for _, tt := range tests { + name, version := parseFreeBSDPackage(tt.filename) + if name != tt.name || version != tt.version { + t.Errorf("parseFreeBSDPackage(%q) = %q, %q, want %q, %q", tt.filename, name, version, tt.name, tt.version) + } + } +} + +func TestParseFreeBSDPackageFile(t *testing.T) { + tests := []struct { + filename, name, version string + pkgfile bool + }{ + {"zsh-5.9_5~2$3rwh1rgp.pkg", "zsh", "5.9_5", true}, + {"zsh-5.9_5.pkg", "zsh", "5.9_5", true}, + {"zsh-navigation-tools-2.2.7.pkg", "zsh-navigation-tools", "2.2.7", true}, + {"py311-requests-2.32.3_1,1.txz", "py311-requests", "2.32.3_1,1", true}, + {"FreeBSD-acct-15.snap20261021214449.tzst", "FreeBSD-acct", "15.snap20261021214449", true}, + {"pkg.pkg", "", "", true}, + {"pkg.txz", "", "", true}, + {"pkg.pkg.sig", "", "", false}, + {"pkg.pkg.pub", "", "", false}, + {"zsh-5.9_5.pkg.sig", "", "", false}, + {"zsh-5.9_5.tar", "", "", false}, + } + for _, tt := range tests { + name, version := parseFreeBSDPackageFile(tt.filename) + if name != tt.name || version != tt.version { + t.Errorf("parseFreeBSDPackageFile(%q) = %q, %q, want %q, %q", tt.filename, name, version, tt.name, tt.version) + } + if got := isFreeBSDPackageFile("FreeBSD:14:amd64/latest/All/" + tt.filename); got != tt.pkgfile { + t.Errorf("isFreeBSDPackageFile(%q) = %v, want %v", tt.filename, got, tt.pkgfile) + } + } +} + +func TestFreeBSDHandler_Routes(t *testing.T) { + h := NewFreeBSDHandler(nil, "http://localhost:8080", nil) + assertRoutesBasics(t, h.Routes(), "/freebsd"+freebsdABI+"/latest/meta.conf", "/freebsd"+freebsdABI+"/../../../etc/passwd") +} + +func TestFreeBSDHandler_DefaultsToOfficialMirror(t *testing.T) { + h := NewFreeBSDHandler(nil, "http://localhost:8080", nil) + if got := h.repositories[defaultFreeBSDRepositoryName]; got != defaultFreeBSDUpstream { + t.Errorf("default repository = %q, want %q", got, defaultFreeBSDUpstream) + } +} + +func TestFreeBSDHandler_UnknownRepositoryReturns404(t *testing.T) { + proxy, _, _, _ := setupTestProxy(t) + h := NewFreeBSDHandler(proxy, "http://localhost:8080", map[string]string{"freebsd": "https://example.test"}) + for _, target := range []string{"/unknown" + freebsdABI + "/latest/meta.conf", "/freebsd", "/"} { + if w := serveFreeBSDRequest(h, target); w.Code != http.StatusNotFound { + t.Errorf("%s: status = %d, want 404", target, w.Code) + } + } +} + +// fakeFreeBSDMirror serves files and counts requests per path. It answers +// 503 for everything while down is set. +type fakeFreeBSDMirror struct { + *httptest.Server + down atomic.Bool + mu sync.Mutex + requests map[string]int +} + +func newFakeFreeBSDMirror(t *testing.T, files map[string]string) *fakeFreeBSDMirror { + t.Helper() + m := &fakeFreeBSDMirror{requests: map[string]int{}} + m.Server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if m.down.Load() { + http.Error(w, "unavailable", http.StatusServiceUnavailable) + return + } + body, ok := files[r.URL.Path] + if !ok { + http.NotFound(w, r) + return + } + m.mu.Lock() + m.requests[r.URL.Path]++ + m.mu.Unlock() + w.Header().Set("Content-Type", "application/octet-stream") + _, _ = w.Write([]byte(body)) + })) + t.Cleanup(m.Close) + return m +} + +func (m *fakeFreeBSDMirror) count(path string) int { + m.mu.Lock() + defer m.mu.Unlock() + return m.requests[path] +} + +func TestFreeBSDHandler_CataloguesServedUnchanged(t *testing.T) { + files := map[string]string{ + freebsdABI + "/latest/meta.conf": "version = 2;\npacking_format = \"tzst\";\n", + freebsdABI + "/latest/packagesite.pkg": "\x28\xb5\x2f\xfdpackagesite.yaml and its signature", + freebsdABI + "/latest/data.pkg": "\x28\xb5\x2f\xfddata and its signature", + } + mirror := newFakeFreeBSDMirror(t, files) + proxy, _, _, _ := setupTestProxy(t) + proxy.CacheMetadata = true + proxy.MetadataTTL = time.Hour + proxy.HTTPClient = mirror.Client() + h := NewFreeBSDHandler(proxy, "http://proxy.example", map[string]string{"freebsd": mirror.URL}) + + for round, down := range []bool{false, true} { + mirror.down.Store(down) + for path, want := range files { + w := serveFreeBSDRequest(h, "/freebsd"+path) + if w.Code != http.StatusOK || w.Body.String() != want { + t.Fatalf("round %d %s: status = %d, body %q, want 200 and the upstream bytes", round, path, w.Code, w.Body) + } + } + } + for path := range files { + if got := mirror.count(path); got != 1 { + t.Errorf("%s fetched %d times, want 1", path, got) + } + } +} + +func TestFreeBSDHandler_HashedPackagesCachedPerABI(t *testing.T) { + const file = "/latest/All/Hashed/zsh-5.9_5~2$3rwh1rgp.pkg" + files := map[string]string{ + "/FreeBSD:14:amd64" + file: "amd64 package", + "/FreeBSD:14:aarch64" + file: "aarch64 package", + } + mirror := newFakeFreeBSDMirror(t, files) + proxy, db, _, _ := setupTestProxy(t) + fetcher := fetch.NewFetcher(fetch.WithHTTPClient(mirror.Client()), fetch.WithMaxRetries(0)) + proxy.Fetcher = fetcher + t.Cleanup(func() { _ = fetcher.Close() }) + h := NewFreeBSDHandler(proxy, "http://proxy.example", map[string]string{"freebsd": mirror.URL}) + + for round, down := range []bool{false, true} { + mirror.down.Store(down) + for path, want := range files { + w := serveFreeBSDRequest(h, "/freebsd"+path) + if w.Code != http.StatusOK || w.Body.String() != want { + t.Fatalf("round %d %s: status = %d, body %q, want 200 and %q", round, path, w.Code, w.Body, want) + } + } + } + for path := range files { + if got := mirror.count(path); got != 1 { + t.Errorf("%s fetched %d times, want 1", path, got) + } + } + + record, err := db.GetArtifact("pkg:bsd/freebsd/zsh@5.9_5", "freebsd/FreeBSD:14:amd64"+file) + if err != nil || record == nil { + t.Errorf("artifact record for pkg:bsd/freebsd/zsh@5.9_5 = %v, %v", record, err) + } +} + +// Unhashed packages can be rebuilt under the same name, and the bootstrap +// files under Latest/ change with every build, so none of them are cached. +// Without a denylist entry or a scanner they are passed through. +func TestFreeBSDHandler_UnhashedFilesPassedThrough(t *testing.T) { + files := map[string]string{ + freebsdABI + "/latest/Latest/pkg.pkg": "bootstrap package", + freebsdABI + "/latest/Latest/pkg.pkg.sig": "bootstrap signature", + freebsdABI + "/latest/All/zsh-5.9_5.pkg": "unhashed package", + } + mirror := newFakeFreeBSDMirror(t, files) + proxy, _, _, _ := setupTestProxy(t) + proxy.CacheMetadata = true + proxy.MetadataTTL = time.Hour + proxy.HTTPClient = mirror.Client() + h := NewFreeBSDHandler(proxy, "http://proxy.example", map[string]string{"freebsd": mirror.URL}) + + for range 2 { + for path, want := range files { + w := serveFreeBSDRequest(h, "/freebsd"+path) + if w.Code != http.StatusOK || w.Body.String() != want { + t.Fatalf("%s: status = %d, body %q, want 200 and %q", path, w.Code, w.Body, want) + } + } + } + for path := range files { + if got := mirror.count(path); got != 2 { + t.Errorf("%s fetched %d times, want 2 (not cached)", path, got) + } + } +} + +// Package files without a hash in their name are checked against the +// denylist like hashed ones, before anything is fetched. +func TestFreeBSDHandler_DenylistCoversEveryPackageFile(t *testing.T) { + denied := []string{ + freebsdABI + "/latest/All/Hashed/zsh-5.9_5~2$3rwh1rgp.pkg", + freebsdABI + "/latest/All/zsh-5.9_5.pkg", + freebsdABI + "/latest/All/zsh-5.9_5~2$3rwh1rgp.pkg", + "/142amd64-default/All/zsh-5.9_5.txz", + "/142amd64-default/All/zsh-5.9_5.tzst", + } + allowed := map[string]string{ + freebsdABI + "/latest/All/zsh-5.9_4.pkg": "older build", + freebsdABI + "/latest/All/zsh-navigation-tools-5.9_5.pkg": "another package", + } + files := map[string]string{} + for _, path := range denied { + files[path] = "denied package" + } + for path, body := range allowed { + files[path] = body + } + mirror := newFakeFreeBSDMirror(t, files) + proxy, _, _, _ := setupTestProxy(t) + proxy.HTTPClient = mirror.Client() + fetcher := fetch.NewFetcher(fetch.WithHTTPClient(mirror.Client()), fetch.WithMaxRetries(0)) + proxy.Fetcher = fetcher + t.Cleanup(func() { _ = fetcher.Close() }) + setTestDenylist(t, proxy, "pkg:bsd/freebsd/zsh@5.9_5") + h := NewFreeBSDHandler(proxy, "http://proxy.example", map[string]string{"freebsd": mirror.URL}) + + for _, path := range denied { + if w := serveFreeBSDRequest(h, "/freebsd"+path); w.Code != http.StatusForbidden { + t.Errorf("%s: status = %d, want 403", path, w.Code) + } + if got := mirror.count(path); got != 0 { + t.Errorf("%s fetched %d times, want 0", path, got) + } + } + for path, want := range allowed { + if w := serveFreeBSDRequest(h, "/freebsd"+path); w.Code != http.StatusOK || w.Body.String() != want { + t.Errorf("%s: status = %d, body %q, want 200 and %q", path, w.Code, w.Body, want) + } + } +} + +// Package files the proxy can't cache can't be scanned either, so they are +// refused while a scanner covers freebsd. Catalogues, signatures and hashed +// packages are unaffected. +func TestFreeBSDHandler_ScanningRefusesUncachablePackages(t *testing.T) { + refused := []string{ + freebsdABI + "/latest/All/zsh-5.9_5.pkg", + freebsdABI + "/latest/Latest/pkg.pkg", + "/142amd64-default/Latest/pkg.txz", + "/142amd64-default/All/zsh-5.9_5.tzst", + } + served := map[string]string{ + freebsdABI + "/latest/meta.conf": "version = 2;\n", + freebsdABI + "/latest/Latest/pkg.pkg.sig": "bootstrap signature", + freebsdABI + "/latest/Latest/pkg.pkg.pub": "bootstrap key", + } + files := map[string]string{} + for _, path := range refused { + files[path] = "unscanned package" + } + for path, body := range served { + files[path] = body + } + + for _, ecosystems := range [][]string{nil, {"freebsd"}} { + mirror := newFakeFreeBSDMirror(t, files) + proxy, _, _, _ := setupTestProxy(t) + proxy.HTTPClient = mirror.Client() + proxy.Scanners = newFreeBSDScanGroup(t, ecosystems) + h := NewFreeBSDHandler(proxy, "http://proxy.example", map[string]string{"freebsd": mirror.URL}) + + for _, path := range refused { + w := serveFreeBSDRequest(h, "/freebsd"+path) + if w.Code != http.StatusForbidden || !strings.Contains(w.Body.String(), "scan") { + t.Errorf("ecosystems %v %s: status = %d, body %q, want 403 naming the scan", ecosystems, path, w.Code, w.Body) + } + if got := mirror.count(path); got != 0 { + t.Errorf("ecosystems %v %s fetched %d times, want 0", ecosystems, path, got) + } + } + for path, want := range served { + if w := serveFreeBSDRequest(h, "/freebsd"+path); w.Code != http.StatusOK || w.Body.String() != want { + t.Errorf("ecosystems %v %s: status = %d, body %q, want 200 and %q", ecosystems, path, w.Code, w.Body, want) + } + } + } +} + +// A scanner restricted to other ecosystems never sees FreeBSD packages, so +// unhashed files are passed through as without scanning. +func TestFreeBSDHandler_ScannerForOtherEcosystemsPassesThrough(t *testing.T) { + const path = freebsdABI + "/latest/All/zsh-5.9_5.pkg" + mirror := newFakeFreeBSDMirror(t, map[string]string{path: "unhashed package"}) + proxy, _, _, _ := setupTestProxy(t) + proxy.HTTPClient = mirror.Client() + proxy.Scanners = newFreeBSDScanGroup(t, []string{"npm"}) + h := NewFreeBSDHandler(proxy, "http://proxy.example", map[string]string{"freebsd": mirror.URL}) + + if w := serveFreeBSDRequest(h, "/freebsd"+path); w.Code != http.StatusOK || w.Body.String() != "unhashed package" { + t.Errorf("status = %d, body %q, want 200 and the upstream bytes", w.Code, w.Body) + } +} + +func newFreeBSDScanGroup(t *testing.T, ecosystems []string) *scanner.Group { + t.Helper() + g, err := scanner.NewGroup(config.ScanningConfig{ + Enabled: true, + SigningKey: "test-signing-key", + Scanners: []config.ScannerConfig{ + {Name: "test-scanner", URL: "http://scanner.invalid/scan", Ecosystems: ecosystems}, + }, + }, slog.New(slog.NewTextHandler(io.Discard, nil))) + if err != nil { + t.Fatalf("scanner.NewGroup() error: %v", err) + } + return g +} + +func serveFreeBSDRequest(h *FreeBSDHandler, target string) *httptest.ResponseRecorder { + w := httptest.NewRecorder() + h.Routes().ServeHTTP(w, httptest.NewRequest(http.MethodGet, target, nil)) + return w +} + +func TestFreeBSDRetentionKey(t *testing.T) { + tests := []struct { + key string + want string + ok bool + }{ + {"pkg:bsd/freebsd/zsh", "pkg:bsd/freebsd/zsh", true}, + {"pkg:bsd/FreeBSD/FreeBSD-acct", "pkg:bsd/freebsd/FreeBSD-acct", true}, + {"pkg:bsd/freebsd/libstdc++", "pkg:bsd/freebsd/libstdc%2B%2B", true}, + {"pkg:bsd/netbsd/zsh", "", false}, + {"pkg:bsd/zsh", "", false}, + {"pkg:bsd/freebsd/latest%2Fzsh", "", false}, + {"pkg:apk/freebsd/zsh", "", false}, + } + for _, tt := range tests { + p, err := purl.Parse(tt.key) + if err != nil { + t.Fatalf("Parse(%s): %v", tt.key, err) + } + got, ok := freebsdRetentionKey(p) + if ok != tt.ok || (ok && got != tt.want) { + t.Errorf("freebsdRetentionKey(%s) = %q, %v, want %q, %v", tt.key, got, ok, tt.want, tt.ok) + } + } + if _, ok := freebsdRetentionKey(nil); ok { + t.Error("freebsdRetentionKey(nil) accepted") + } +} diff --git a/internal/handler/gem.go b/internal/handler/gem.go index 2d2136b..fa7c24b 100644 --- a/internal/handler/gem.go +++ b/internal/handler/gem.go @@ -1,10 +1,11 @@ package handler import ( - "bufio" + "bytes" "encoding/json" "fmt" "net/http" + "regexp" "strings" "time" @@ -81,6 +82,7 @@ func (h *GemHandler) handleDownload(w http.ResponseWriter, r *http.Request) { parseErr: "could not parse gem filename", fetchErr: "failed to fetch gem", parse: h.parseGemFilename, + publishTime: h.publishTime, }) } @@ -88,141 +90,190 @@ func (h *GemHandler) handleDownload(w http.ResponseWriter, r *http.Request) { // e.g., "rails-7.1.0.gem" -> ("rails", "7.1.0") // e.g., "aws-sdk-s3-1.142.0.gem" -> ("aws-sdk-s3", "1.142.0") // e.g., "sorbet-static-0.5.11002-universal-darwin-22.gem" -> ("sorbet-static", "0.5.11002-universal-darwin-22") +// e.g., "devise-2fa-1.0.0.gem" -> ("devise-2fa", "1.0.0") // -// The version starts at the first hyphen followed by a digit. Platforms can -// end in a number (universal-java-17, arm64-darwin-23), so splitting at the -// last one would cut the platform; only gem names with a "-" segment -// are misread this way, and those are rare. +// A gem file is named {name}-{version}[-{platform}]. RubyGems writes a +// version as dot-separated alphanumeric segments starting with a digit, +// turning any "-" into ".pre.", and a platform starts with a letter (its +// CPU, or java), though it can end in a number (universal-java-17), so +// splitting at the last "-" would cut the platform. The version +// starts at the first "-" that leaves such a version and platform, +// so a name with a "-" segment of its own, such as devise-2fa, is +// kept whole. A filename no split fits is split at the first "-". +// +// Trying every "-" costs time quadratic in the filename's length, so +// a filename longer than maxGemFilenameLength is refused. func (h *GemHandler) parseGemFilename(filename string) (name, version string) { + if len(filename) > maxGemFilenameLength { + return "", "" + } base := strings.TrimSuffix(filename, ".gem") + first := -1 for i := 0; i+1 < len(base); i++ { - if base[i] == '-' && base[i+1] >= '0' && base[i+1] <= '9' { + if base[i] != '-' || base[i+1] < '0' || base[i+1] > '9' { + continue + } + if first < 0 { + first = i + } + if gemVersionAndPlatform(base[i+1:]) { return base[:i], base[i+1:] } } - return "", "" + if first < 0 { + return "", "" + } + return base[:first], base[first+1:] +} + +// maxGemFilenameLength bounds the gem filenames parseGemFilename accepts. +// Real gem filenames are a small fraction of this. +const maxGemFilenameLength = 512 + +var ( + gemVersionPattern = regexp.MustCompile(`^[0-9]+(\.[0-9A-Za-z]+)*$`) + gemPlatformPattern = regexp.MustCompile(`^[A-Za-z][0-9A-Za-z_]*(-[0-9A-Za-z_]+)*$`) +) + +// gemVersionAndPlatform reports whether s reads as {version}[-{platform}]. +func gemVersionAndPlatform(s string) bool { + version, platform, hasPlatform := strings.Cut(s, "-") + return gemVersionPattern.MatchString(version) && (!hasPlatform || gemPlatformPattern.MatchString(platform)) } // handleCompactIndex serves the compact index for a gem, filtering versions // based on cooldown when enabled. +// +// With cooldown the index and the versions API's publish times are read +// through the metadata cache, so a bundle install within metadata_ttl of the +// last one asks rubygems.org nothing, and one after it revalidates both with +// their ETags. The filtered index is kept in the rewrite cache and served +// with an ETag of its own. func (h *GemHandler) handleCompactIndex(w http.ResponseWriter, r *http.Request) { - if h.proxy.Cooldown == nil || !h.proxy.Cooldown.Enabled() { - h.proxyCached(w, r) - return - } - name := r.PathValue("name") if name == "" { http.Error(w, "invalid gem name", http.StatusBadRequest) return } + if !h.proxy.cooldownApplies("gem", name) { + h.proxyCached(w, r) + return + } h.proxy.Logger.Info("gem compact index request with cooldown", "name", name) - indexResp, filteredVersions, err := h.fetchIndexAndVersions(r, name) + docs, err := h.proxy.fetchTimedMetadata(r.Context(), h.timedIndex(name), h.indexVersions) + switch { + case docs.doc.err != nil: + h.proxy.writeMetadataFetchError(w, docs.doc.err) + return + case docs.times.err != nil: + h.proxy.writeCooldownLookupError(w, "gem", name, docs.times.err) + return + case err != nil: + h.proxy.Logger.Error("failed to read gem compact index", "gem", name, "error", err) + http.Error(w, "failed to read upstream response", http.StatusBadGateway) + return + } + + packagePURL := canonicalPackagePURL("gem", name) + m, err := h.proxy.cachedRewrite(r.Context(), "gem", h.proxyURL, "info/"+name, docs.doc.body, docs.rewriteDigest(), + func([]byte) ([]byte, []string, error) { + body, err := h.proxy.decodedMetadataBody(docs.doc) + if err != nil { + return nil, nil, err + } + out, kept := h.filterIndex(body, name, func(version string) bool { + return docs.withheld(h.proxy, "gem", packagePURL, version) + }) + return out, kept, nil + }) if err != nil { - if writeUpstreamHeld(w, err) { - return - } - h.proxy.Logger.Error("upstream compact index request failed", "error", err) - http.Error(w, "upstream request failed", http.StatusBadGateway) - return - } - defer func() { _ = indexResp.Body.Close() }() - - if indexResp.StatusCode != http.StatusOK { - h.proxy.relayResponse(w, r, indexResp, nil) + h.proxy.Logger.Error("failed to filter gem compact index", "gem", name, "error", err) + http.Error(w, "failed to read upstream response", http.StatusBadGateway) return } - if filteredVersions == nil { - h.proxy.Logger.Warn("failed to fetch version timestamps, proxying unfiltered", "name", name) - h.proxy.relayResponse(w, r, indexResp, nil) - return + // Served as identity, as upstream's index was: Bundler checks digest + // headers against the bytes it receives, and asks for ranges of it. + m = m.identity() + contentType := docs.doc.contentType + if contentType == "" || contentType == contentTypeJSON { + contentType = "text/plain; charset=utf-8" } - - h.writeFilteredIndex(w, indexResp, name, filteredVersions) + markStale(w, docs.doc.stale || docs.times.stale) + serveRewrittenMetadataAs(w, r, m, contentType) } -// fetchIndexAndVersions fetches the compact index and versions API concurrently. -// Returns the index response, a set of versions to filter (nil if versions API failed), -// and an error if the index fetch itself failed. -func (h *GemHandler) fetchIndexAndVersions(r *http.Request, name string) (*http.Response, map[string]bool, error) { - type versionsResult struct { - filtered map[string]bool - err error +// timedIndex describes a gem's compact index and the versions API it takes +// publish times from. +func (h *GemHandler) timedIndex(name string) timedMetadata { + return timedMetadata{ + ecosystem: "gem", + docKey: "info/" + name, + docURL: h.upstreamURL + "/info/" + name, + timesKey: "api/v1/versions/" + name + ".json", + timesURL: fmt.Sprintf("%s/api/v1/versions/%s.json", h.upstreamURL, name), + timesAccept: contentTypeJSON, + parseTimes: parseGemVersions, } - - versionsCh := make(chan versionsResult, 1) - go func() { - filtered, err := h.fetchFilteredVersions(r, name) - versionsCh <- versionsResult{filtered: filtered, err: err} - }() - - indexResp, err := h.fetchCompactIndex(r, name) - - versionsRes := <-versionsCh - - if err != nil { - return nil, nil, err - } - - if versionsRes.err != nil { - return indexResp, nil, nil - } - - return indexResp, versionsRes.filtered, nil } -// fetchCompactIndex fetches the compact index from upstream. -func (h *GemHandler) fetchCompactIndex(r *http.Request, name string) (*http.Response, error) { - indexURL := h.upstreamURL + "/info/" + name - req, err := http.NewRequestWithContext(r.Context(), http.MethodGet, indexURL, nil) +// indexVersions lists the versions in a compact index, as the versions API +// names them. +func (h *GemHandler) indexVersions(doc metadataResult) ([]string, error) { + body, err := h.proxy.decodedMetadataBody(doc) if err != nil { return nil, err } - for _, hdr := range []string{"Accept", headerAcceptEncoding, "If-None-Match", "If-Modified-Since"} { - if v := r.Header.Get(hdr); v != "" { - req.Header.Set(hdr, v) + var versions []string + for rest := body; len(rest) > 0; { + line, tail, _ := bytes.Cut(rest, []byte("\n")) + rest = tail + if version := gemIndexLineVersion(line); gemIndexListsVersion(version) { + versions = append(versions, string(version)) } } - return h.proxy.HTTPClient.Do(req) + return versions, nil } -// writeFilteredIndex writes the compact index response with cooldown-filtered versions removed. -func (h *GemHandler) writeFilteredIndex(w http.ResponseWriter, resp *http.Response, name string, filtered map[string]bool) { - for k, vv := range resp.Header { - if strings.EqualFold(k, headerContentLength) { - continue // length will change after filtering - } - for _, v := range vv { - w.Header().Add(k, v) - } +// gemIndexLineVersion returns the version a compact index line starts with. +func gemIndexLineVersion(line []byte) []byte { + if spaceIdx := bytes.IndexByte(line, ' '); spaceIdx > 0 { + return line[:spaceIdx] } - w.WriteHeader(http.StatusOK) + return line +} - scanner := bufio.NewScanner(resp.Body) - for scanner.Scan() { - line := scanner.Text() +// gemIndexListsVersion reports whether a compact index line's first field +// is a version, rather than the "---" that starts the file or an empty line. +func gemIndexListsVersion(field []byte) bool { + return len(field) > 0 && string(field) != "---" +} - if line == "---" { - _, _ = fmt.Fprintln(w, line) - continue +// filterIndex returns the compact index without the lines of versions +// withheld reports, and the versions it kept. +func (h *GemHandler) filterIndex(body []byte, name string, withheld func(string) bool) ([]byte, []string) { + var kept []string + var out bytes.Buffer + out.Grow(len(body)) + for rest := body; len(rest) > 0; { + line, tail, _ := bytes.Cut(rest, []byte("\n")) + rest = tail + + version := gemIndexLineVersion(line) + if gemIndexListsVersion(version) { + if withheld(string(version)) { + h.proxy.Logger.Info("cooldown: filtering gem version", + "gem", name, "version", string(version)) + continue + } + kept = append(kept, string(version)) } - - version := line - if spaceIdx := strings.IndexByte(line, ' '); spaceIdx > 0 { - version = line[:spaceIdx] - } - - if filtered[version] { - h.proxy.Logger.Info("cooldown: filtering gem version", - "gem", name, "version", version) - continue - } - - _, _ = fmt.Fprintln(w, line) + out.Write(line) + out.WriteByte('\n') } + return out.Bytes(), kept } // gemVersion represents a version entry from the RubyGems versions API. @@ -232,50 +283,30 @@ type gemVersion struct { CreatedAt string `json:"created_at"` } -// fetchFilteredVersions fetches the versions API and returns a set of version -// strings that should be filtered out by cooldown. -func (h *GemHandler) fetchFilteredVersions(r *http.Request, name string) (map[string]bool, error) { - versionsURL := fmt.Sprintf("%s/api/v1/versions/%s.json", h.upstreamURL, name) - req, err := http.NewRequestWithContext(r.Context(), http.MethodGet, versionsURL, nil) - if err != nil { - return nil, err - } - - resp, err := h.proxy.HTTPClient.Do(req) - if err != nil { - return nil, err - } - defer func() { _ = resp.Body.Close() }() - - if resp.StatusCode != http.StatusOK { - return nil, fmt.Errorf("versions API returned %d", resp.StatusCode) - } - +// parseGemVersions reads the publish times from a versions API response, +// keyed by version as the compact index writes it. +func parseGemVersions(body []byte) (publishTimes, error) { var versions []gemVersion - if err := json.NewDecoder(resp.Body).Decode(&versions); err != nil { + if err := json.Unmarshal(body, &versions); err != nil { return nil, err } - - packagePURL := canonicalPackagePURL("gem", name) - filtered := make(map[string]bool) - + times := make(publishTimes, len(versions)) for _, v := range versions { + versionStr := v.Number + if v.Platform != "" && v.Platform != "ruby" { + versionStr = v.Number + "-" + v.Platform + } createdAt, err := time.Parse(time.RFC3339, v.CreatedAt) if err != nil { - continue - } - - if !h.proxy.Cooldown.IsAllowed("gem", packagePURL, createdAt) { - // Build version string matching compact index format - versionStr := v.Number - if v.Platform != "" && v.Platform != "ruby" { - versionStr = v.Number + "-" + v.Platform - } - filtered[versionStr] = true + createdAt = time.Time{} } + times[versionStr] = createdAt } + return times, nil +} - return filtered, nil +func (h *GemHandler) publishTime(r *http.Request, name, version string) (time.Time, bool, bool, error) { + return h.proxy.lookupPublishTime(r.Context(), h.timedIndex(name), version, h.indexVersions) } // proxyCached forwards a metadata request with caching. diff --git a/internal/handler/gem_test.go b/internal/handler/gem_test.go index ce63deb..ba62ef8 100644 --- a/internal/handler/gem_test.go +++ b/internal/handler/gem_test.go @@ -1,6 +1,7 @@ package handler import ( + "compress/gzip" "encoding/json" "fmt" "log/slog" @@ -30,6 +31,12 @@ func TestGemParseFilename(t *testing.T) { {"google-protobuf-3.25.3-arm64-darwin-23.gem", "google-protobuf", "3.25.3-arm64-darwin-23"}, {"nokogiri-1.16.0-x64-mingw-ucrt.gem", "nokogiri", "1.16.0-x64-mingw-ucrt"}, {"rake-13.1.0.pre.1.gem", "rake", "13.1.0.pre.1"}, + {"devise-2fa-1.0.0.gem", "devise-2fa", "1.0.0"}, + {"devise-2fa-1.0.0-java.gem", "devise-2fa", "1.0.0-java"}, + {"foo-2-1.0.0.gem", "foo-2", "1.0.0"}, + {"foo-2-1.gem", "foo-2", "1"}, + {"foo-2-x86_64-linux.gem", "foo", "2-x86_64-linux"}, + {"odd-1_0.gem", "odd", "1_0"}, {"no-version.gem", "", ""}, {"invalid", "", ""}, } @@ -43,6 +50,31 @@ func TestGemParseFilename(t *testing.T) { } } +func TestGemDownloadRefusesLongFilename(t *testing.T) { + // Every "-1-" could start a version, and each try reads to the "!" at + // the end before failing, so parsing this used to take minutes. + filename := strings.Repeat("-1-aaaaaa", 100_000) + "!.gem" + + h := &GemHandler{proxy: testProxy(), upstreamURL: "http://upstream.invalid"} + req := httptest.NewRequest(http.MethodGet, "/gems/x", nil) + req.SetPathValue("filename", "x"+filename) + w := httptest.NewRecorder() + + done := make(chan struct{}) + go func() { + h.handleDownload(w, req) + close(done) + }() + select { + case <-done: + case <-time.After(5 * time.Second): + t.Fatal("parsing a long gem filename did not finish within 5s") + } + if w.Code != http.StatusBadRequest { + t.Errorf("status = %d, want %d", w.Code, http.StatusBadRequest) + } +} + func TestGemCompactIndexCooldown(t *testing.T) { now := time.Now() oldTime := now.Add(-7 * 24 * time.Hour).Format(time.RFC3339) @@ -101,6 +133,118 @@ func TestGemCompactIndexCooldown(t *testing.T) { } } +// gemCooldownUpstream serves index as /info/testgem, gzipped when the +// request accepts gzip as rubygems.org does, with 1.0.0 published a week ago +// and 2.0.0 an hour ago. +func gemCooldownUpstream(t *testing.T, index string, headers http.Header) *httptest.Server { + t.Helper() + now := time.Now() + versionsJSON, _ := json.Marshal([]gemVersion{ + {Number: "1.0.0", Platform: "ruby", CreatedAt: now.Add(-7 * 24 * time.Hour).Format(time.RFC3339)}, + {Number: "2.0.0", Platform: "ruby", CreatedAt: now.Add(-time.Hour).Format(time.RFC3339)}, + }) + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/info/testgem": + for k, vv := range headers { + w.Header()[k] = vv + } + w.Header().Set("Content-Type", "text/plain; charset=utf-8") + if !strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") { + _, _ = w.Write([]byte(index)) + return + } + w.Header().Set("Content-Encoding", "gzip") + gz := gzip.NewWriter(w) + _, _ = gz.Write([]byte(index)) + _ = gz.Close() + case "/api/v1/versions/testgem.json": + _, _ = w.Write(versionsJSON) + default: + w.WriteHeader(http.StatusNotFound) + } + })) + t.Cleanup(upstream.Close) + return upstream +} + +func TestGemCompactIndexCooldownClientAcceptsGzip(t *testing.T) { + index := "---\n1.0.0 dep1:>= 1.0|checksum:abc123\n2.0.0 dep1:>= 1.0|checksum:def456\n" + upstream := gemCooldownUpstream(t, index, http.Header{ + "Etag": {`"upstream"`}, + "Repr-Digest": {"sha-256=:upstream:"}, + }) + + proxy := testProxy() + proxy.Cooldown = &cooldown.Config{Default: "3d"} + h := &GemHandler{proxy: proxy, upstreamURL: upstream.URL} + + // Bundler sends Accept-Encoding: gzip by default. + req := httptest.NewRequest(http.MethodGet, "/info/testgem", nil) + req.Header.Set("Accept-Encoding", "gzip;q=1.0,deflate;q=0.6,identity;q=0.3") + req.SetPathValue("name", "testgem") + w := httptest.NewRecorder() + h.handleCompactIndex(w, req) + + if w.Code != http.StatusOK { + t.Fatalf("status = %d, want %d", w.Code, http.StatusOK) + } + if ce := w.Header().Get("Content-Encoding"); ce != "" { + t.Errorf("Content-Encoding = %q, want none", ce) + } + want := "---\n1.0.0 dep1:>= 1.0|checksum:abc123\n" + if got := w.Body.String(); got != want { + t.Errorf("body = %q, want %q", got, want) + } + if v := w.Header().Get("Repr-Digest"); v != "" { + t.Errorf("Repr-Digest = %q, upstream's value must not describe the filtered index", v) + } + if v := w.Header().Get("ETag"); v == "" || v == `"upstream"` { + t.Errorf("ETag = %q, want one of the filtered index", v) + } +} + +func TestGemCompactIndexCooldownLongLine(t *testing.T) { + // A version line longer than bufio.Scanner's 64 KB default used to end + // the response early with a 200. + long := "1.0.0 " + strings.Repeat("dep:>= 1.0,", 10_000) + "|checksum:abc" + index := "---\n" + long + "\n2.0.0 |checksum:def\n3.0.0 |checksum:ghi\n" + upstream := gemCooldownUpstream(t, index, nil) + + proxy := testProxy() + proxy.Cooldown = &cooldown.Config{Default: "3d"} + h := &GemHandler{proxy: proxy, upstreamURL: upstream.URL} + + req := httptest.NewRequest(http.MethodGet, "/info/testgem", nil) + req.SetPathValue("name", "testgem") + w := httptest.NewRecorder() + h.handleCompactIndex(w, req) + + want := "---\n" + long + "\n3.0.0 |checksum:ghi\n" + if w.Code != http.StatusOK || w.Body.String() != want { + t.Fatalf("status = %d, body of %d bytes; want 200 with %d bytes", w.Code, w.Body.Len(), len(want)) + } +} + +func TestGemCompactIndexCooldownOversizedIndex(t *testing.T) { + index := "---\n1.0.0 |checksum:abc\n" + strings.Repeat("9.9.9 |checksum:zzz\n", 100) + upstream := gemCooldownUpstream(t, index, nil) + + proxy := testProxy() + proxy.Cooldown = &cooldown.Config{Default: "3d"} + proxy.MetadataMaxSize = 256 + h := &GemHandler{proxy: proxy, upstreamURL: upstream.URL} + + req := httptest.NewRequest(http.MethodGet, "/info/testgem", nil) + req.SetPathValue("name", "testgem") + w := httptest.NewRecorder() + h.handleCompactIndex(w, req) + + if w.Code != http.StatusBadGateway { + t.Fatalf("status = %d, want %d", w.Code, http.StatusBadGateway) + } +} + func TestGemCompactIndexCooldownWithPlatformVersion(t *testing.T) { now := time.Now() recentTime := now.Add(-1 * time.Hour).Format(time.RFC3339) @@ -199,18 +343,16 @@ func TestGemCompactIndexVersionsAPIFails(t *testing.T) { w := httptest.NewRecorder() h.handleCompactIndex(w, req) - // Should still return OK with unfiltered content - if w.Code != http.StatusOK { - t.Fatalf("status = %d, want %d", w.Code, http.StatusOK) + // Without publish times the index can't be filtered, so it isn't served. + if w.Code != http.StatusBadGateway { + t.Fatalf("status = %d, want %d", w.Code, http.StatusBadGateway) } - - body := w.Body.String() - if !strings.Contains(body, "1.0.0") { - t.Error("expected unfiltered content when versions API fails") + if strings.Contains(w.Body.String(), "1.0.0") { + t.Error("served the unfiltered index when the versions API failed") } } -func TestGemFetchFilteredVersions(t *testing.T) { +func TestGemParseVersions(t *testing.T) { now := time.Now() oldTime := now.Add(-7 * 24 * time.Hour).Format(time.RFC3339) recentTime := now.Add(-1 * time.Hour).Format(time.RFC3339) @@ -219,40 +361,52 @@ func TestGemFetchFilteredVersions(t *testing.T) { {Number: "1.0.0", Platform: "ruby", CreatedAt: oldTime}, {Number: "2.0.0", Platform: "ruby", CreatedAt: recentTime}, {Number: "2.0.0", Platform: "java", CreatedAt: recentTime}, + {Number: "3.0.0", Platform: "ruby", CreatedAt: "not a time"}, }) - upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - _, _ = w.Write(versionsJSON) - })) - defer upstream.Close() - proxy := testProxy() - proxy.Cooldown = &cooldown.Config{ - Default: "3d", - } + proxy.Cooldown = &cooldown.Config{Default: "3d"} - h := &GemHandler{ - proxy: proxy, - upstreamURL: upstream.URL, - proxyURL: "http://proxy.local", - } - - req := httptest.NewRequest(http.MethodGet, "/info/testgem", nil) - filtered, err := h.fetchFilteredVersions(req, "testgem") + times, err := parseGemVersions(versionsJSON) if err != nil { t.Fatal(err) } - - if filtered["1.0.0"] { - t.Error("version 1.0.0 should not be filtered (old enough)") - } - if !filtered["2.0.0"] { - t.Error("version 2.0.0 (ruby) should be filtered") - } - if !filtered["2.0.0-java"] { - t.Error("version 2.0.0-java should be filtered") + docs := timedDocuments{published: times} + purl := canonicalPackagePURL("gem", "testgem") + for version, want := range map[string]bool{"1.0.0": false, "2.0.0": true, "2.0.0-java": true, "3.0.0": false, "4.0.0": false} { + if got := docs.withheld(proxy, "gem", purl, version); got != want { + t.Errorf("withheld(%s) = %v, want %v", version, got, want) + } } _ = fmt.Sprintf // silence unused import } + +func TestGemCooldownVersionsSizeLimit(t *testing.T) { + versionsJSON, _ := json.Marshal([]gemVersion{ + {Number: "2.0.0", Platform: "ruby", CreatedAt: time.Now().Add(-time.Hour).Format(time.RFC3339)}, + }) + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if strings.HasPrefix(r.URL.Path, "/api/v1/versions/") { + _, _ = w.Write(versionsJSON) + _, _ = w.Write([]byte(strings.Repeat(" ", 4096))) + return + } + _, _ = w.Write([]byte("---\n2.0.0 |checksum:abc\n")) + })) + defer upstream.Close() + + proxy := testProxy() + proxy.Cooldown = &cooldown.Config{Default: "3d"} + proxy.MetadataMaxSize = 1024 + h := &GemHandler{proxy: proxy, upstreamURL: upstream.URL} + + req := httptest.NewRequest(http.MethodGet, "/info/testgem", nil) + req.SetPathValue("name", "testgem") + w := httptest.NewRecorder() + h.handleCompactIndex(w, req) + + if w.Code != http.StatusBadGateway { + t.Errorf("status = %d, want %d", w.Code, http.StatusBadGateway) + } +} diff --git a/internal/handler/generic.go b/internal/handler/generic.go index bf7f088..0e08140 100644 --- a/internal/handler/generic.go +++ b/internal/handler/generic.go @@ -10,6 +10,7 @@ import ( "strings" "github.com/git-pkgs/proxy/internal/config" + "github.com/git-pkgs/proxy/internal/retention" ) const ( @@ -28,6 +29,10 @@ const ( // and served without revalidation once fetched. var githubReleaseAssetPattern = regexp.MustCompile(`^([^/]+)/([^/]+)/releases/download/([^/]+)/([^/]+)$`) +func init() { + retention.Default.Register(retention.Spec{Key: genericEcosystem, CanonicalPackage: retention.DefaultCanonical(genericEcosystem)}) +} + // builtinGenericArtifacts maps well-known download hosts to patterns for // their version-pinned paths. They apply to any generic upstream configured // with that base URL, after the upstream's own generic_artifacts. @@ -66,6 +71,9 @@ type GenericHandler struct { proxy *Proxy repositories map[string]string artifactPatterns map[string][]*regexp.Regexp + // paths holds each upstream's upstream.generic_paths patterns; an + // upstream without any serves every path. + paths map[string][]string } // NewGenericHandler creates a generic HTTP download proxy handler. @@ -92,6 +100,13 @@ func NewGenericHandler(proxy *Proxy, repositories map[string]string, artifactPat return h } +// WithPaths limits upstreams to the paths their upstream.generic_paths +// patterns match. Any other path answers 404. +func (h *GenericHandler) WithPaths(paths map[string][]string) *GenericHandler { + h.paths = paths + return h +} + func (h *GenericHandler) addArtifactPatterns(name string, patterns []string) { for _, pattern := range patterns { re, err := config.CompileGenericArtifactPattern(pattern) @@ -121,8 +136,12 @@ func (h *GenericHandler) Routes() http.Handler { } repository, rest, ok := strings.Cut(path, "/") + if repository == HostedGenericRepository && h.proxy.HostedEnabled { + h.handleHosted(w, r, rest) + return + } upstreamURL, found := h.repositories[repository] - if !ok || rest == "" || !found { + if !ok || rest == "" || !found || !config.GenericPathAllowed(h.paths[repository], rest) { http.NotFound(w, r) return } @@ -136,6 +155,38 @@ func (h *GenericHandler) Routes() http.Handler { }) } +// HostedGenericRepository is the /generic/{name}/ path that serves pushed +// generic files instead of an upstream while hosted packages are enabled. +const HostedGenericRepository = config.HostedGenericRepository + +// handleHosted serves a pushed file at {name}/{version}/{file}. Pushed files +// never come from an upstream, so anything not pushed is a 404. +func (h *GenericHandler) handleHosted(w http.ResponseWriter, r *http.Request, path string) { + segments := strings.Split(path, "/") + if len(segments) != hostedGenericPathSegments { + http.NotFound(w, r) + return + } + target, err := HostedTargetFor(genericEcosystem, segments[0], segments[1], segments[2]) + if err != nil { + http.NotFound(w, r) + return + } + result, err := h.proxy.GetLocalArtifact(r.Context(), genericEcosystem, target.Name, target.Version, target.Filename) + if err != nil { + h.proxy.serveArtifactError(w, err, "failed to read pushed file") + return + } + if result == nil { + http.NotFound(w, r) + return + } + serveGenericArtifact(w, r, result) +} + +// hostedGenericPathSegments is {name}/{version}/{file}. +const hostedGenericPathSegments = 3 + // genericArtifact is the identity of a version-pinned download. type genericArtifact struct { name string @@ -229,7 +280,12 @@ func (h *GenericHandler) handleArtifact(w http.ResponseWriter, r *http.Request, h.proxy.serveArtifactError(w, err, "failed to fetch artifact") return } + serveGenericArtifact(w, r, result) +} +// serveGenericArtifact serves a cached or pushed file, as a plain download +// when its media type is unknown. +func serveGenericArtifact(w http.ResponseWriter, r *http.Request, result *CacheResult) { if result.Artifact.MediaType == "" { result.Artifact.MediaType = "application/octet-stream" } diff --git a/internal/handler/generic_test.go b/internal/handler/generic_test.go index 2165b1a..a74be8c 100644 --- a/internal/handler/generic_test.go +++ b/internal/handler/generic_test.go @@ -2,6 +2,7 @@ package handler import ( "context" + "io" "net/http" "net/http/httptest" "regexp" @@ -12,11 +13,29 @@ import ( "github.com/git-pkgs/proxy/internal/config" upstreamhttp "github.com/git-pkgs/proxy/internal/httpclient" + "github.com/git-pkgs/proxy/internal/retention" "github.com/git-pkgs/registries/fetch" ) const testReleaseAssetPath = "/jqlang/jq/releases/download/jq-1.7.1/jq-linux-amd64" +func TestGenericRetentionConfig(t *testing.T) { + cfg := config.Default() + cfg.Storage.Retention.Ecosystems = map[string]string{"generic": "30d"} + cfg.Storage.Retention.Packages = map[string]string{"pkg:generic/jqlang%2Fjq": "90d"} + + rules, err := cfg.RetentionRules(retention.Default) + if err != nil { + t.Fatalf("RetentionRules() error = %v", err) + } + if got := rules.For(genericEcosystem, "pkg:generic/jqlang%2Fjq"); got != 90*24*time.Hour { + t.Errorf("jqlang/jq retention = %v, want 90d", got) + } + if got := rules.For(genericEcosystem, "pkg:generic/other%2Frepo"); got != 30*24*time.Hour { + t.Errorf("generic ecosystem retention = %v, want 30d", got) + } +} + func TestParseGitHubReleaseAsset(t *testing.T) { tests := []struct { path string @@ -294,6 +313,7 @@ func TestGenericHandler_RejectsUnknownUpstreamAndBadPaths(t *testing.T) { {"traversal", http.MethodGet, "/github/../etc/passwd", http.StatusBadRequest}, {"encoded traversal", http.MethodGet, "/github/%2e%2e/etc/passwd", http.StatusBadRequest}, {"post", http.MethodPost, "/github/owner/repo/releases/download/v1/asset", http.StatusMethodNotAllowed}, + {"hosted files with hosting off", http.MethodGet, "/hosted/tools/1.2.0/tool.tar.gz", http.StatusNotFound}, } for _, tt := range tests { @@ -328,7 +348,7 @@ func TestGenericHandler_ReleaseAssetIsCachedAndServedWhenUpstreamDown(t *testing })) defer upstream.Close() - proxy, _, store, _ := setupTestProxy(t) + proxy, db, store, _ := setupTestProxy(t) store.seekable = true fetcher := fetch.NewFetcher(fetch.WithHTTPClient(upstream.Client()), fetch.WithMaxRetries(0)) proxy.Fetcher = fetcher @@ -346,6 +366,13 @@ func TestGenericHandler_ReleaseAssetIsCachedAndServedWhenUpstreamDown(t *testing if got := upstreamRequests.Load(); got != 1 { t.Fatalf("upstream requests = %d, want 1", got) } + pkg, err := db.GetPackageByEcosystemName(genericEcosystem, "jqlang/jq") + if err != nil || pkg == nil { + t.Fatalf("release package = %v, %v; want a cached package", pkg, err) + } + if pkg.PURL != "pkg:generic/jqlang%2Fjq" { + t.Errorf("release package PURL = %q, want pkg:generic/jqlang%%2Fjq", pkg.PURL) + } // Second request must be served from cache, even with the upstream down. available.Store(false) @@ -603,3 +630,63 @@ func serveGenericRequest(h *GenericHandler, target string) *httptest.ResponseRec h.Routes().ServeHTTP(w, httptest.NewRequest(http.MethodGet, target, nil)) return w } + +func TestGenericHandler_UpstreamNamedHostedWhileHostingIsOff(t *testing.T) { + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _, _ = io.WriteString(w, "from upstream "+r.URL.Path) + })) + t.Cleanup(upstream.Close) + proxy, _, _, _ := setupTestProxy(t) + proxy.HTTPClient = upstream.Client() + h := NewGenericHandler(proxy, map[string]string{"hosted": upstream.URL}) + + w := httptest.NewRecorder() + h.Routes().ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/hosted/index.json", nil)) + if w.Code != http.StatusOK || w.Body.String() != "from upstream /index.json" { + t.Errorf("status = %d, body %q, want the upstream response", w.Code, w.Body) + } +} + +func TestGenericHandler_ServesOnlyConfiguredPaths(t *testing.T) { + var requested []string + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + requested = append(requested, r.URL.RequestURI()) + _, _ = io.WriteString(w, "from upstream "+r.URL.Path) + })) + t.Cleanup(upstream.Close) + proxy, _, _, _ := setupTestProxy(t) + proxy.HTTPClient = upstream.Client() + fetcher := fetch.NewFetcher(fetch.WithHTTPClient(upstream.Client()), fetch.WithMaxRetries(0)) + proxy.Fetcher = fetcher + t.Cleanup(func() { _ = fetcher.Close() }) + + h := NewGenericHandler(proxy, map[string]string{"github-api": upstream.URL, "open": upstream.URL}). + WithPaths(map[string][]string{"github-api": {"repos/*/*/releases/**", "rate_limit"}}) + + for _, target := range []string{ + "/github-api/repos/jqlang/jq/releases/tags/jq-1.7.1", + "/github-api/rate_limit", + "/open/user/repos", + } { + if w := serveGenericRequest(h, target); w.Code != http.StatusOK { + t.Errorf("GET %s: status = %d, want 200: %s", target, w.Code, w.Body.String()) + } + } + + served := len(requested) + for _, target := range []string{ + "/github-api/user/repos", + "/github-api/repos/acme/private/contents/secret.txt", + "/github-api/repos/jqlang/jq/releases", + "/github-api/repos/jqlang/jq%3F/releases/x", + "/github-api/repos/jqlang/jq/releases/%2575ser", + "/github-api/jqlang/jq/releases/download/jq-1.7.1/jq-linux-amd64", + } { + if w := serveGenericRequest(h, target); w.Code != http.StatusNotFound { + t.Errorf("GET %s: status = %d, want 404", target, w.Code) + } + } + if len(requested) != served { + t.Errorf("upstream saw %v for paths outside generic_paths", requested[served:]) + } +} diff --git a/internal/handler/git.go b/internal/handler/git.go new file mode 100644 index 0000000..7243d84 --- /dev/null +++ b/internal/handler/git.go @@ -0,0 +1,309 @@ +package handler + +import ( + "errors" + "net/http" + "net/url" + "strings" + "time" + + "github.com/git-pkgs/proxy/internal/config" + "github.com/git-pkgs/proxy/internal/gitcache" + "github.com/git-pkgs/proxy/internal/metrics" +) + +const ( + gitEcosystem = "git" + + gitInfoRefs = "/info/refs" + gitUploadPack = "/git-upload-pack" + gitReceivePack = "/git-receive-pack" + gitRequestType = "application/x-git-upload-pack-request" + + // gitRequestTimeout replaces the server's read and write timeouts for Git + // requests once any request body has been read: a cold clone of a large + // repository keeps the client waiting before the first byte, and a large + // pack takes a while to send. + gitRequestTimeout = 2 * time.Hour + // gitWriteStallTimeout bounds each write of a Git response, so a client + // that stops reading does not hold an upload-pack process for + // gitRequestTimeout. + gitWriteStallTimeout = 2 * time.Minute +) + +// GitHandler serves Git repositories read-only over smart HTTP at +// /git/{name}/{repo}, from a local cache of the upstream.git hosts. Clients +// clone and fetch with ordinary git commands, usually through an insteadOf +// rewrite. Pushing and the dumb protocol are refused. +type GitHandler struct { + proxy *Proxy + cache *gitcache.Cache + upstreams map[string]gitUpstream + // baseURL is where clients reach the proxy, for LFS download URLs. + baseURL string + // lfsDownloads keeps upstream LFS download URLs between a batch and + // the GETs that follow it. + lfsDownloads *lfsDownloads + // writeStall is gitWriteStallTimeout, shorter in tests. + writeStall time.Duration +} + +type gitUpstream struct { + config.GitUpstream + // dir names the upstream's directory in the cache (gitcache.UpstreamDir). + dir string + // fetchWants is off when upstream.auth has credentials for the host. A + // fetch by ID there could reach commits outside the repos allowlist, + // as GitHub serves any commit in a repository's fork network. + fetchWants bool +} + +// NewGitHandler creates a Git handler serving upstream.git from cache. +func NewGitHandler(proxy *Proxy, cache *gitcache.Cache, upstream config.UpstreamConfig) *GitHandler { + h := &GitHandler{ + proxy: proxy, + cache: cache, + upstreams: make(map[string]gitUpstream, len(upstream.Git)), + writeStall: gitWriteStallTimeout, + lfsDownloads: &lfsDownloads{}, + } + for name, git := range upstream.Git { + git.URL = strings.TrimSuffix(git.URL, "/") + h.upstreams[name] = gitUpstream{ + GitUpstream: git, + dir: gitcache.UpstreamDir(name, git.URL), + fetchWants: !upstream.HasAuthWithin(git.URL), + } + } + return h +} + +// Routes returns the HTTP handler for Git requests. Mount this at /git. +func (h *GitHandler) Routes() http.Handler { + return http.HandlerFunc(h.serve) +} + +// gitRequest is a parsed /git/{name}/{repo}/{endpoint} request. +type gitRequest struct { + infoRefs bool + fetchWants bool + // key names the repository in the cache: {name}-{URL hash}/{repo}.git, + // with any .git the client gave removed from repo first, so both + // spellings share one copy. + key string + // repoURL is the upstream repository, spelled as the client spelled it. + repoURL string +} + +func (h *GitHandler) serve(w http.ResponseWriter, r *http.Request) { + if repoPath, endpoint, ok := strings.Cut(strings.TrimPrefix(r.URL.Path, "/"), gitLFSPath); ok { + h.serveLFS(w, r, repoPath, endpoint) + return + } + req, status, msg := h.parse(r) + if status != 0 { + http.Error(w, msg, status) + return + } + // An upload-pack request is read in full first, within the server's read + // timeout, so nothing waits on a client that is slow to send one. + var body *gitcache.Request + if !req.infoRefs { + var err error + if body, err = h.cache.ReadRequest(r); err != nil { + h.serveRequestError(w, req, err) + return + } + defer body.Close() + } + // The read deadline is extended too: once the body is read, an HTTP/1 + // server watches the connection, and a read timeout there would cancel + // the request. + rc := http.NewResponseController(w) + deadline := time.Now().Add(gitRequestTimeout) + if err := errors.Join(rc.SetReadDeadline(deadline), rc.SetWriteDeadline(deadline)); err != nil { + h.proxy.Logger.Warn("git: cannot extend the request deadlines", "error", err) + } + w = &stallWriter{ResponseWriter: w, rc: rc, stall: h.writeStall, deadline: deadline} + // What is left buffered once the handler returns is bounded as well. + defer func() { _ = rc.SetWriteDeadline(time.Now().Add(h.writeStall)) }() + + lease, err := h.cache.Open(r.Context(), req.key, req.repoURL, + gitcache.OpenOptions{Refresh: req.infoRefs, FetchWants: req.fetchWants}) + if err != nil { + h.serveError(w, r, err) + return + } + defer lease.Release() + if !req.infoRefs { + lease.ServeUploadPack(w, r, body) + return + } + if lease.Hit() { + metrics.RecordArtifactCacheHit(gitEcosystem) + } else { + metrics.RecordArtifactCacheMiss(gitEcosystem) + } + lease.ServeInfoRefs(w, r) +} + +func (h *GitHandler) parse(r *http.Request) (gitRequest, int, string) { + path := strings.TrimPrefix(r.URL.Path, "/") + var req gitRequest + switch { + case strings.HasSuffix(path, gitInfoRefs): + path = strings.TrimSuffix(path, gitInfoRefs) + req.infoRefs = true + switch r.URL.Query().Get("service") { + case "git-upload-pack": + case "git-receive-pack": + return req, http.StatusForbidden, "pushing is not supported" + default: + return req, http.StatusForbidden, "only the smart HTTP protocol is supported" + } + if r.Method != http.MethodGet { + return req, http.StatusMethodNotAllowed, "method not allowed" + } + case strings.HasSuffix(path, gitUploadPack): + path = strings.TrimSuffix(path, gitUploadPack) + if r.Method != http.MethodPost { + return req, http.StatusMethodNotAllowed, "method not allowed" + } + if r.Header.Get("Content-Type") != gitRequestType { + return req, http.StatusUnsupportedMediaType, "unsupported content type" + } + case strings.HasSuffix(path, gitReceivePack): + return req, http.StatusForbidden, "pushing is not supported" + default: + return req, http.StatusNotFound, "not found" + } + + repo, status, msg := h.repository(path) + if status != 0 { + return req, status, msg + } + req.key = repo.key + req.repoURL = repo.url + req.fetchWants = repo.upstream.fetchWants + return req, 0, "" +} + +// gitRepository is a repository of an upstream.git host, as a request path +// names it. +type gitRepository struct { + // name is the upstream's name and repo the path under it, without .git. + name, repo string + upstream gitUpstream + // key names the repository in the cache: {name}-{URL hash}/{repo}.git, + // with any .git the client gave removed from repo first, so both + // spellings share one copy. + key string + // url is the upstream repository, spelled as the client spelled it, and + // escapedRepo is repo escaped for a URL path. + url, escapedRepo string +} + +// repository resolves {name}/{repo} to an upstream repository, or returns +// the status and message to refuse it with. +func (h *GitHandler) repository(path string) (gitRepository, int, string) { + name, repoPath, _ := strings.Cut(path, "/") + upstream, ok := h.upstreams[name] + if !ok { + return gitRepository{}, http.StatusNotFound, "unknown upstream" + } + segments := strings.Split(repoPath, "/") + last := len(segments) - 1 + suffix := "" + if trimmed, ok := strings.CutSuffix(segments[last], ".git"); ok { + segments[last], suffix = trimmed, ".git" + } + escaped := make([]string, len(segments)) + for i, segment := range segments { + if !validGitSegment(segment, i == last) { + return gitRepository{}, http.StatusNotFound, "invalid repository path" + } + escaped[i] = url.PathEscape(segment) + } + repo := strings.Join(segments, "/") + if !upstream.AllowsRepo(repo) { + // As for a missing repository, so a prober learns nothing about + // the allowlist. + return gitRepository{}, http.StatusNotFound, "repository not found" + } + escapedRepo := strings.Join(escaped, "/") + return gitRepository{ + name: name, + repo: repo, + upstream: upstream, + key: upstream.dir + "/" + repo + ".git", + url: upstream.URL + "/" + escapedRepo + suffix, + escapedRepo: escapedRepo, + }, 0, "" +} + +// validGitSegment checks one segment of a repository path, which becomes both +// part of a directory under the cache and part of the upstream URL. Only the +// last segment may end in .git, so one repository's directory never sits +// inside another's. +func validGitSegment(segment string, last bool) bool { + if segment == "" || segment == "." || segment == ".." || (!last && strings.HasSuffix(segment, ".git")) { + return false + } + for _, r := range segment { + if r < ' ' || r == 0x7f || r == '\\' { + return false + } + } + return true +} + +// serveRequestError answers an upload-pack request whose body could not be +// read. +func (h *GitHandler) serveRequestError(w http.ResponseWriter, req gitRequest, err error) { + if errors.Is(err, gitcache.ErrRequestTooLarge) { + h.proxy.Logger.Warn("git: request body passed the limit", "repository", req.key) + http.Error(w, "request body too large", http.StatusRequestEntityTooLarge) + return + } + http.Error(w, "cannot read the request body", http.StatusBadRequest) +} + +// stallWriter bounds each write of a response by stall, where the response +// as a whole may take until deadline. +type stallWriter struct { + http.ResponseWriter + rc *http.ResponseController + stall time.Duration + deadline time.Time +} + +func (w *stallWriter) Write(p []byte) (int, error) { + _ = w.rc.SetWriteDeadline(time.Now().Add(w.stall)) + n, err := w.ResponseWriter.Write(p) + _ = w.rc.SetWriteDeadline(w.deadline) + return n, err +} + +func (w *stallWriter) Unwrap() http.ResponseWriter { + return w.ResponseWriter +} + +// serveError answers a request whose repository could not be opened. The +// cache has already logged why. +func (h *GitHandler) serveError(w http.ResponseWriter, r *http.Request, err error) { + if r.Context().Err() != nil { + return + } + switch { + case errors.Is(err, gitcache.ErrNotFound): + http.Error(w, "repository not found", http.StatusNotFound) + case errors.Is(err, gitcache.ErrRefused): + http.Error(w, "upstream refused the request", http.StatusBadGateway) + case errors.Is(err, gitcache.ErrTooLarge): + http.Error(w, "repository is larger than git.max_repo_size or git.max_size", http.StatusInsufficientStorage) + case errors.Is(err, gitcache.ErrCacheFull): + http.Error(w, "git cache is full", http.StatusInsufficientStorage) + default: + http.Error(w, "upstream unavailable", http.StatusBadGateway) + } +} diff --git a/internal/handler/git_lfs.go b/internal/handler/git_lfs.go new file mode 100644 index 0000000..d4f6fe6 --- /dev/null +++ b/internal/handler/git_lfs.go @@ -0,0 +1,559 @@ +package handler + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "net/url" + "slices" + "strconv" + "strings" + "sync" + "time" +) + +const ( + // gitLFSPath separates a repository from the Git LFS API below it, as + // git-lfs derives the API URL from a remote: {remote}.git/info/lfs. + gitLFSPath = "/info/lfs/" + gitLFSMediaType = "application/vnd.git-lfs+json" + gitLFSTransfer = "basic" + gitLFSHashAlgo = "sha256" + // gitLFSObjectMediaType is what objects are served as. + gitLFSObjectMediaType = "application/octet-stream" + + // gitLFSMaxBatchRequest bounds a client's batch request. git-lfs sends + // 100 objects per batch by default, a few kilobytes. + gitLFSMaxBatchRequest = 1 << 20 + // gitLFSMaxBatchResponse bounds an upstream batch response, which holds + // an href and headers per object. + gitLFSMaxBatchResponse = 16 << 20 + + gitLFSOIDLength = 64 +) + +// lfsBatchRequest is a Git LFS batch API request. +type lfsBatchRequest struct { + Operation string `json:"operation"` + Transfers []string `json:"transfers,omitempty"` + Ref json.RawMessage `json:"ref,omitempty"` + Objects []lfsObject `json:"objects"` + HashAlgo string `json:"hash_algo,omitempty"` +} + +type lfsObject struct { + OID string `json:"oid"` + Size int64 `json:"size"` +} + +// lfsBatchResponse is a Git LFS batch API response. +type lfsBatchResponse struct { + Transfer string `json:"transfer,omitempty"` + Objects []lfsObjectResponse `json:"objects"` + HashAlgo string `json:"hash_algo,omitempty"` +} + +type lfsObjectResponse struct { + OID string `json:"oid"` + Size int64 `json:"size"` + Authenticated bool `json:"authenticated,omitempty"` + Actions map[string]lfsAction `json:"actions,omitempty"` + Error *lfsObjectError `json:"error,omitempty"` +} + +type lfsAction struct { + Href string `json:"href"` + Header map[string]string `json:"header,omitempty"` + ExpiresIn int64 `json:"expires_in,omitempty"` + ExpiresAt string `json:"expires_at,omitempty"` +} + +type lfsObjectError struct { + Code int `json:"code"` + Message string `json:"message"` +} + +// lfsUpstreamError is a batch request the upstream answered with an error +// status. +type lfsUpstreamError struct { + status int +} + +func (e *lfsUpstreamError) Error() string { + return fmt.Sprintf("LFS batch API answered %d", e.status) +} + +// WithBaseURL sets the URL clients reach the proxy at, which LFS batch +// responses send them back to for each object. +func (h *GitHandler) WithBaseURL(baseURL string) *GitHandler { + h.baseURL = strings.TrimSuffix(baseURL, "/") + return h +} + +// serveLFS answers a request to the Git LFS API of a repository: batch +// downloads, and the objects the batch responses point at. Objects are +// stored in the artifact cache, checked against their sha256 object ID. +// Uploads and locking are refused. +func (h *GitHandler) serveLFS(w http.ResponseWriter, r *http.Request, repoPath, endpoint string) { + repo, status, msg := h.repository(repoPath) + if status != 0 { + lfsError(w, status, msg) + return + } + if endpoint == "objects/batch" { + if r.Method != http.MethodPost { + lfsError(w, http.StatusMethodNotAllowed, "method not allowed") + return + } + h.serveLFSBatch(w, r, repo) + return + } + oid, sizeText, ok := strings.Cut(strings.TrimPrefix(endpoint, "objects/"), "/") + size, err := strconv.ParseInt(sizeText, 10, 64) + if !strings.HasPrefix(endpoint, "objects/") || !ok || err != nil || size < 0 || !validLFSOID(oid) { + lfsError(w, http.StatusNotFound, "not found") + return + } + if r.Method != http.MethodGet && r.Method != http.MethodHead { + lfsError(w, http.StatusMethodNotAllowed, "method not allowed") + return + } + h.serveLFSObject(w, r, repo, lfsObject{OID: oid, Size: size}) +} + +// serveLFSBatch forwards a download batch upstream and points every object +// the upstream offers at this proxy. The upstream answers for the +// repository, so a client only gets objects it could get from there. +func (h *GitHandler) serveLFSBatch(w http.ResponseWriter, r *http.Request, repo gitRepository) { + var req lfsBatchRequest + if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, gitLFSMaxBatchRequest)).Decode(&req); err != nil { + var tooLarge *http.MaxBytesError + if errors.As(err, &tooLarge) { + lfsError(w, http.StatusRequestEntityTooLarge, "batch request too large") + return + } + lfsError(w, http.StatusBadRequest, "invalid batch request") + return + } + switch { + case req.Operation != "download": + lfsError(w, http.StatusForbidden, "pushing is not supported") + return + case req.HashAlgo != "" && req.HashAlgo != gitLFSHashAlgo: + lfsError(w, http.StatusConflict, "only sha256 objects are supported") + return + case len(req.Transfers) > 0 && !slices.Contains(req.Transfers, gitLFSTransfer): + lfsError(w, http.StatusUnprocessableEntity, "only the basic transfer is supported") + return + } + requested := make(map[string]int64, len(req.Objects)) + for _, object := range req.Objects { + if !validLFSOID(object.OID) || object.Size < 0 { + lfsError(w, http.StatusUnprocessableEntity, "invalid object") + return + } + requested[object.OID] = object.Size + } + + upstream, err := h.lfsBatch(r.Context(), repo, req.Ref, req.Objects) + if err != nil { + if resp, ok := h.lfsBatchFromCache(r, repo, req.Objects, err); ok { + writeLFSBatch(w, resp) + return + } + h.serveLFSUpstreamError(w, r, repo, err) + return + } + resp := newLFSBatchResponse() + for _, object := range upstream.Objects { + // Only objects the client asked for, at the size it gave, so a + // response can't point the client at anything else. + size, ok := requested[object.OID] + if !ok || size != object.Size { + continue + } + out := lfsObjectResponse{OID: object.OID, Size: object.Size, Error: object.Error} + if download, ok := object.Actions["download"]; ok && object.Error == nil && download.Href != "" { + out.Authenticated = true + out.Actions = map[string]lfsAction{"download": {Href: h.lfsObjectURL(repo, object.OID, object.Size)}} + // Kept so the client's GET for the object needs no second + // batch request. + h.lfsDownloads.put(repo.key, lfsObject{OID: object.OID, Size: object.Size}, download, time.Now()) + } + resp.Objects = append(resp.Objects, out) + } + writeLFSBatch(w, resp) +} + +// lfsBatchFromCache answers a batch the upstream couldn't, because it was +// unreachable or failing, from the objects cached for repo. This is what a +// GET of each object would serve anyway. A refusal by the upstream is not +// overridden, and a batch none of whose objects are cached is left to fail. +func (h *GitHandler) lfsBatchFromCache(r *http.Request, repo gitRepository, objects []lfsObject, err error) (lfsBatchResponse, bool) { + var refused *lfsUpstreamError + if r.Context().Err() != nil || (errors.As(err, &refused) && refused.status < http.StatusInternalServerError) { + return lfsBatchResponse{}, false + } + resp := newLFSBatchResponse() + seen := make(map[string]bool, len(objects)) + cached := 0 + for _, object := range objects { + if seen[object.OID] { + continue + } + seen[object.OID] = true + out := lfsObjectResponse{OID: object.OID, Size: object.Size} + if ok, _ := h.proxy.HasCachedArtifact(r.Context(), gitEcosystem, repo.lfsName(), object.OID, object.OID); ok { + out.Authenticated = true + out.Actions = map[string]lfsAction{"download": {Href: h.lfsObjectURL(repo, object.OID, object.Size)}} + cached++ + } else { + out.Error = &lfsObjectError{Code: http.StatusBadGateway, Message: "upstream unavailable and object not cached"} + } + resp.Objects = append(resp.Objects, out) + } + if cached == 0 { + return lfsBatchResponse{}, false + } + h.proxy.Logger.Warn("git: LFS batch request failed, answering from the cache", + "repository", repo.key, "cached", cached, "objects", len(resp.Objects), "error", err) + return resp, true +} + +func newLFSBatchResponse() lfsBatchResponse { + return lfsBatchResponse{Transfer: gitLFSTransfer, Objects: []lfsObjectResponse{}, HashAlgo: gitLFSHashAlgo} +} + +func writeLFSBatch(w http.ResponseWriter, resp lfsBatchResponse) { + w.Header().Set("Content-Type", gitLFSMediaType) + _ = json.NewEncoder(w).Encode(resp) +} + +// serveLFSObject serves an object from the artifact cache. On a miss it +// takes the download URL from the client's batch, or asks the upstream batch +// API for a fresh one, and caches the object from there, or from a copy +// already stored under another repository, once its content matches its +// object ID. +func (h *GitHandler) serveLFSObject(w http.ResponseWriter, r *http.Request, repo gitRepository, object lfsObject) { + cached, err := h.proxy.GetCachedArtifact(r.Context(), gitEcosystem, repo.lfsName(), object.OID, object.OID) + if err != nil { + h.proxy.serveArtifactError(w, err, "failed to read cached LFS object") + return + } + if cached == nil { + var ok bool + if cached, ok = h.fetchLFSObject(w, r, repo, object); !ok { + return + } + } + serveGenericArtifact(w, r, cached) +} + +// fetchLFSObject caches an object the cache doesn't have. When it can't, or +// the request is a HEAD, it answers the request and returns false. +func (h *GitHandler) fetchLFSObject(w http.ResponseWriter, r *http.Request, repo gitRepository, object lfsObject) (*CacheResult, bool) { + download, kept := h.lfsDownloads.get(repo.key, object, time.Now()) + if !kept { + var ok bool + if download, ok = h.lfsFreshDownload(w, r, repo, object); !ok { + return nil, false + } + } + if r.Method == http.MethodHead { + // The upstream has the object, and a HEAD needs no more than that: + // fetching it is left to a GET. + w.Header().Set("Content-Type", gitLFSObjectMediaType) + w.Header().Set("Content-Length", strconv.FormatInt(object.Size, 10)) + return nil, false + } + h.lfsDownloads.drop(repo.key, object.OID) + cached, err := h.cacheLFSObject(r.Context(), repo, object, download) + if err != nil && kept && retryLFSDownload(r.Context(), err) { + // The kept URL may have expired early or been revoked. + var ok bool + if download, ok = h.lfsFreshDownload(w, r, repo, object); !ok { + return nil, false + } + cached, err = h.cacheLFSObject(r.Context(), repo, object, download) + } + if err != nil { + h.proxy.serveArtifactError(w, err, "failed to fetch LFS object") + return nil, false + } + return cached, true +} + +// lfsFreshDownload asks the upstream batch API for object's download. When +// there is none it answers the request and returns false. +func (h *GitHandler) lfsFreshDownload(w http.ResponseWriter, r *http.Request, repo gitRepository, object lfsObject) (lfsAction, bool) { + upstream, err := h.lfsBatch(r.Context(), repo, nil, []lfsObject{object}) + if err != nil { + h.serveLFSUpstreamError(w, r, repo, err) + return lfsAction{}, false + } + download, status, msg := lfsDownload(upstream, object) + if status != 0 { + lfsError(w, status, msg) + return lfsAction{}, false + } + return download, true +} + +// cacheLFSObject caches object, which the upstream offers as download. A +// copy already stored under another name, such as by a fork of the +// repository, saves the download. +func (h *GitHandler) cacheLFSObject(ctx context.Context, repo gitRepository, object lfsObject, download lfsAction) (*CacheResult, error) { + header := make(http.Header, len(download.Header)) + for key, value := range download.Header { + header.Set(key, value) + } + // Download URLs are often signed, granting access to the object until + // they expire, so only the URL without its query is logged and + // recorded. The object must have the size the client asked for. + ctx, recorded := withSignedDownload(ctx, download.Href, object.Size) + if !h.proxy.StreamArtifacts { + stored, err := h.proxy.DB.FindStoredContent(object.OID) + if err != nil { + h.proxy.Logger.Warn("git: looking up a stored copy of an LFS object failed", "oid", object.OID, "error", err) + } + if stored != nil && stored.Size == object.Size { + cached, err := h.proxy.cacheStoredCopy(ctx, gitEcosystem, repo.lfsName(), object.OID, object.OID, + recorded, object.OID, stored) + if err == nil { + return cached, nil + } + h.proxy.Logger.Warn("git: copying a stored LFS object failed, downloading it", "oid", object.OID, "error", err) + } + } + return h.proxy.getOrFetchArtifactFromURL(ctx, gitEcosystem, repo.lfsName(), object.OID, object.OID, + recorded, header, object.OID, "") +} + +// retryLFSDownload reports whether a download from a kept URL failed in a way +// a fresh URL might not. +func retryLFSDownload(ctx context.Context, err error) bool { + return ctx.Err() == nil && + !errors.Is(err, ErrArtifactDigestMismatch) && + !errors.Is(err, errDownloadSize) && + !errors.Is(err, ErrVersionDenied) && + !errors.Is(err, ErrArtifactBlocked) +} + +// lfsDownload returns the download action the upstream gave for object, or +// the status and message to answer with when it gave none. +func lfsDownload(resp *lfsBatchResponse, object lfsObject) (lfsAction, int, string) { + for _, got := range resp.Objects { + if got.OID != object.OID { + continue + } + if got.Error != nil { + if got.Error.Code == http.StatusNotFound || got.Error.Code == http.StatusGone { + return lfsAction{}, http.StatusNotFound, "object not found" + } + return lfsAction{}, http.StatusBadGateway, "upstream refused the object" + } + download, ok := got.Actions["download"] + if !ok || !validLFSHref(download.Href) { + return lfsAction{}, http.StatusBadGateway, "upstream gave no download for the object" + } + return download, 0, "" + } + return lfsAction{}, http.StatusNotFound, "object not found" +} + +// validLFSHref reports whether href is an absolute HTTP(S) URL. +func validLFSHref(href string) bool { + u, err := url.Parse(href) + return err == nil && (u.Scheme == "https" || u.Scheme == "http") && u.Host != "" +} + +// lfsBatch asks the upstream's LFS batch API for download actions for +// objects. upstream.auth applies to it as to the repository. +func (h *GitHandler) lfsBatch(ctx context.Context, repo gitRepository, ref json.RawMessage, objects []lfsObject) (*lfsBatchResponse, error) { + body, err := json.Marshal(lfsBatchRequest{ + Operation: "download", + Transfers: []string{gitLFSTransfer}, + Ref: ref, + Objects: objects, + HashAlgo: gitLFSHashAlgo, + }) + if err != nil { + return nil, err + } + batchURL := strings.TrimSuffix(repo.url, ".git") + ".git" + gitLFSPath + "objects/batch" + req, err := http.NewRequestWithContext(ctx, http.MethodPost, batchURL, bytes.NewReader(body)) + if err != nil { + return nil, err + } + req.Header.Set("Accept", gitLFSMediaType) + req.Header.Set("Content-Type", gitLFSMediaType) + resp, err := h.proxy.HTTPClient.Do(req) + if err != nil { + return nil, err + } + defer func() { _ = resp.Body.Close() }() + if resp.StatusCode != http.StatusOK { + return nil, &lfsUpstreamError{status: resp.StatusCode} + } + var batch lfsBatchResponse + if err := json.NewDecoder(io.LimitReader(resp.Body, gitLFSMaxBatchResponse)).Decode(&batch); err != nil { + return nil, fmt.Errorf("reading LFS batch response: %w", err) + } + if batch.Transfer != "" && batch.Transfer != gitLFSTransfer { + return nil, fmt.Errorf("LFS batch response uses the %q transfer", batch.Transfer) + } + return &batch, nil +} + +// serveLFSUpstreamError answers a request whose upstream batch request +// failed. +func (h *GitHandler) serveLFSUpstreamError(w http.ResponseWriter, r *http.Request, repo gitRepository, err error) { + if r.Context().Err() != nil { + return + } + h.proxy.Logger.Warn("git: LFS batch request failed", "repository", repo.key, "error", err) + var upstream *lfsUpstreamError + switch { + case errors.As(err, &upstream) && upstream.status == http.StatusNotFound: + lfsError(w, http.StatusNotFound, "repository not found") + case errors.As(err, &upstream) && upstream.status < http.StatusInternalServerError: + lfsError(w, http.StatusBadGateway, "upstream refused the request") + default: + lfsError(w, http.StatusBadGateway, "upstream unavailable") + } +} + +// lfsName names repo's LFS objects in the artifact cache. Objects are cached +// per repository: having one cached for another repository says nothing +// about whether this one has it. +func (repo gitRepository) lfsName() string { + return repo.name + "/" + repo.repo +} + +// lfsObjectURL is where this proxy serves an object of repo. +func (h *GitHandler) lfsObjectURL(repo gitRepository, oid string, size int64) string { + return fmt.Sprintf("%s/git/%s/%s.git%sobjects/%s/%d", + h.baseURL, url.PathEscape(repo.name), repo.escapedRepo, gitLFSPath, oid, size) +} + +// validLFSOID reports whether oid is a sha256 object ID in lowercase hex. +func validLFSOID(oid string) bool { + if len(oid) != gitLFSOIDLength { + return false + } + for _, c := range oid { + if (c < '0' || c > '9') && (c < 'a' || c > 'f') { + return false + } + } + return true +} + +// lfsError answers with a Git LFS error document, which git-lfs shows. +func lfsError(w http.ResponseWriter, status int, msg string) { + w.Header().Set("Content-Type", gitLFSMediaType) + w.WriteHeader(status) + _ = json.NewEncoder(w).Encode(map[string]string{"message": msg}) +} + +const ( + // gitLFSKeptDownloads bounds how many download URLs from batch responses + // are kept for the GETs that follow them. + gitLFSKeptDownloads = 4096 + // gitLFSKeptTTL is how long a download URL is kept when the upstream + // gives no expiry, and gitLFSKeptMaxTTL how long at most. + gitLFSKeptTTL = 5 * time.Minute + gitLFSKeptMaxTTL = time.Hour + // gitLFSExpiryMargin is how long before its expiry a URL is no longer + // used, so a download started with it can finish. + gitLFSExpiryMargin = 30 * time.Second +) + +// lfsDownloads keeps the download actions of recent batch responses, so the +// GET for an object a client just got in a batch needs no second batch +// request. They stay in memory, never reach a client and expire with the +// URLs. +type lfsDownloads struct { + mu sync.Mutex + entries map[lfsDownloadKey]lfsKeptDownload +} + +type lfsDownloadKey struct { + repo, oid string +} + +type lfsKeptDownload struct { + size int64 + action lfsAction + expires time.Time +} + +// put keeps action for object of repo until shortly before it expires. +func (d *lfsDownloads) put(repo string, object lfsObject, action lfsAction, now time.Time) { + if !validLFSHref(action.Href) { + return + } + expires := now.Add(gitLFSKeptTTL) + if action.ExpiresIn > 0 || action.ExpiresAt != "" { + expires = now.Add(gitLFSKeptMaxTTL) + } + if action.ExpiresIn > 0 { + expires = minTime(expires, now.Add(time.Duration(action.ExpiresIn)*time.Second)) + } + if at, err := time.Parse(time.RFC3339, action.ExpiresAt); err == nil { + expires = minTime(expires, at) + } + expires = expires.Add(-gitLFSExpiryMargin) + if !expires.After(now) { + return + } + d.mu.Lock() + defer d.mu.Unlock() + if d.entries == nil { + d.entries = make(map[lfsDownloadKey]lfsKeptDownload) + } + if len(d.entries) >= gitLFSKeptDownloads { + for key, kept := range d.entries { + if !kept.expires.After(now) { + delete(d.entries, key) + } + } + } + if len(d.entries) >= gitLFSKeptDownloads { + // Still full: make room by dropping any one. + for key := range d.entries { + delete(d.entries, key) + break + } + } + d.entries[lfsDownloadKey{repo, object.OID}] = lfsKeptDownload{size: object.Size, action: action, expires: expires} +} + +// get returns the action kept for object of repo, if it hasn't expired. +func (d *lfsDownloads) get(repo string, object lfsObject, now time.Time) (lfsAction, bool) { + d.mu.Lock() + defer d.mu.Unlock() + kept, ok := d.entries[lfsDownloadKey{repo, object.OID}] + if !ok || kept.size != object.Size || !kept.expires.After(now) { + return lfsAction{}, false + } + return kept.action, true +} + +// drop forgets the action kept for oid of repo, once a GET has used it. +func (d *lfsDownloads) drop(repo, oid string) { + d.mu.Lock() + defer d.mu.Unlock() + delete(d.entries, lfsDownloadKey{repo, oid}) +} + +func minTime(a, b time.Time) time.Time { + if b.Before(a) { + return b + } + return a +} diff --git a/internal/handler/git_lfs_test.go b/internal/handler/git_lfs_test.go new file mode 100644 index 0000000..37bc6aa --- /dev/null +++ b/internal/handler/git_lfs_test.go @@ -0,0 +1,483 @@ +package handler + +import ( + "bytes" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "io" + "log/slog" + "net/http" + "net/http/httptest" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/git-pkgs/proxy/internal/config" + "github.com/git-pkgs/registries/fetch" +) + +const lfsTestContent = "large file content" + +// lfsSignature is the signature in the upstream's download URLs, which must +// not reach logs or the database. +const lfsSignature = "s3cr3t-signature" + +// lfsUpstream is a Git host with an LFS batch API whose download hrefs point +// at a separate object store, as GitHub's do. The store only serves objects +// to requests carrying the header and signed URL the batch response gave. +type lfsUpstream struct { + git, store *httptest.Server + oid string + content atomic.Value // string the store serves for oid + batches atomic.Int32 + downloads atomic.Int32 + // batchStatus, when set, is the status the batch API fails with. + batchStatus atomic.Int32 + // signature is the signature the batch API hands out and the store + // accepts; changing it expires the URLs handed out before. + signature atomic.Value + // lastBatch is the last batch request the upstream got. + lastBatch atomic.Value + // logs is what the proxy logged. + logs bytes.Buffer +} + +func newLFSUpstream(t *testing.T) *lfsUpstream { + t.Helper() + sum := sha256.Sum256([]byte(lfsTestContent)) + u := &lfsUpstream{oid: hex.EncodeToString(sum[:])} + u.content.Store(lfsTestContent) + u.signature.Store(lfsSignature) + u.store = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/objects/"+u.oid || r.Header.Get("X-Signed") != "token" || + r.URL.Query().Get("Signature") != u.signature.Load().(string) { + http.Error(w, "forbidden", http.StatusForbidden) + return + } + u.downloads.Add(1) + _, _ = io.WriteString(w, u.content.Load().(string)) + })) + u.git = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + // acme/widget has the object, as does its fork; stranger/widget + // exists but doesn't have it. + repo, _, _ := strings.Cut(r.URL.Path, ".git/info/lfs/objects/batch") + hasObject, exists := map[string]bool{"/acme/widget": true, "/fork/widget": true, "/stranger/widget": false}[repo] + if r.Method != http.MethodPost || !exists { + http.NotFound(w, r) + return + } + u.batches.Add(1) + if status := u.batchStatus.Load(); status != 0 { + http.Error(w, "failing", int(status)) + return + } + var req lfsBatchRequest + if err := json.NewDecoder(r.Body).Decode(&req); err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + u.lastBatch.Store(req) + resp := lfsBatchResponse{Transfer: "basic"} + for _, object := range req.Objects { + if object.OID != u.oid || !hasObject { + resp.Objects = append(resp.Objects, lfsObjectResponse{OID: object.OID, Size: object.Size, + Error: &lfsObjectError{Code: http.StatusNotFound, Message: "Object does not exist"}}) + continue + } + resp.Objects = append(resp.Objects, lfsObjectResponse{OID: object.OID, Size: object.Size, + Actions: map[string]lfsAction{"download": { + Href: u.store.URL + "/objects/" + u.oid + "?Expires=1&Signature=" + u.signature.Load().(string), + Header: map[string]string{"X-Signed": "token"}, + }}}) + } + // An object nobody asked for is not passed on. + resp.Objects = append(resp.Objects, lfsObjectResponse{OID: strings.Repeat("e", 64), Size: 1, + Actions: map[string]lfsAction{"download": {Href: u.store.URL + "/other"}}}) + w.Header().Set("Content-Type", gitLFSMediaType) + _ = json.NewEncoder(w).Encode(resp) + })) + t.Cleanup(u.git.Close) + t.Cleanup(u.store.Close) + return u +} + +func newLFSHandler(t *testing.T, u *lfsUpstream, repos ...string) *GitHandler { + t.Helper() + proxy, _, store, _ := setupTestProxy(t) + store.seekable = true + proxy.Logger = slog.New(slog.NewTextHandler(&u.logs, nil)) + proxy.HTTPClient = u.git.Client() + fetcher := fetch.NewFetcher(fetch.WithHTTPClient(u.store.Client()), fetch.WithMaxRetries(0)) + proxy.Fetcher = fetcher + t.Cleanup(func() { _ = fetcher.Close() }) + return NewGitHandler(proxy, nil, config.UpstreamConfig{Git: map[string]config.GitUpstream{ + "up": {URL: u.git.URL, Repos: repos}, + }}).WithBaseURL("http://proxy.test/") +} + +func lfsRequest(h *GitHandler, method, target, body string) *httptest.ResponseRecorder { + r := httptest.NewRequest(method, target, strings.NewReader(body)) + r.Header.Set("Content-Type", gitLFSMediaType) + w := httptest.NewRecorder() + h.Routes().ServeHTTP(w, r) + return w +} + +func lfsBatchBody(operation string, objects ...lfsObject) string { + body, _ := json.Marshal(lfsBatchRequest{Operation: operation, Transfers: []string{"basic"}, + Ref: json.RawMessage(`{"name":"refs/heads/main"}`), Objects: objects}) + return string(body) +} + +func TestGitLFSBatchPointsObjectsAtTheProxy(t *testing.T) { + u := newLFSUpstream(t) + h := newLFSHandler(t, u) + missing := strings.Repeat("0", 64) + size := int64(len(lfsTestContent)) + + w := lfsRequest(h, http.MethodPost, "/up/acme/widget.git/info/lfs/objects/batch", + lfsBatchBody("download", lfsObject{OID: u.oid, Size: size}, lfsObject{OID: missing, Size: 3})) + if w.Code != http.StatusOK || w.Header().Get("Content-Type") != gitLFSMediaType { + t.Fatalf("batch: status %d, type %q, body %s", w.Code, w.Header().Get("Content-Type"), w.Body) + } + var resp lfsBatchResponse + if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil { + t.Fatal(err) + } + if len(resp.Objects) != 2 { + t.Fatalf("objects = %+v, want the two requested", resp.Objects) + } + got, notFound := resp.Objects[0], resp.Objects[1] + want := fmt.Sprintf("http://proxy.test/git/up/acme/widget.git/info/lfs/objects/%s/%d", u.oid, size) + if download := got.Actions["download"]; download.Href != want || len(download.Header) != 0 || !got.Authenticated { + t.Errorf("download = %+v, authenticated %v; want %s without the upstream's headers", download, got.Authenticated, want) + } + if notFound.Error == nil || notFound.Error.Code != http.StatusNotFound || notFound.Actions != nil { + t.Errorf("missing object = %+v, want the upstream's 404", notFound) + } + if req, _ := u.lastBatch.Load().(lfsBatchRequest); string(req.Ref) != `{"name":"refs/heads/main"}` { + t.Errorf("upstream got ref %s, want the client's", req.Ref) + } +} + +func TestGitLFSObjectIsCached(t *testing.T) { + u := newLFSUpstream(t) + h := newLFSHandler(t, u) + path := fmt.Sprintf("/up/acme/widget.git/info/lfs/objects/%s/%d", u.oid, len(lfsTestContent)) + + w := lfsRequest(h, http.MethodGet, path, "") + if w.Code != http.StatusOK || w.Body.String() != lfsTestContent { + t.Fatalf("first GET: status %d, body %q", w.Code, w.Body) + } + if u.batches.Load() != 1 || u.downloads.Load() != 1 { + t.Errorf("batches %d, downloads %d; want one of each", u.batches.Load(), u.downloads.Load()) + } + + u.git.Close() + u.store.Close() + w = lfsRequest(h, http.MethodGet, path, "") + if w.Code != http.StatusOK || w.Body.String() != lfsTestContent { + t.Errorf("GET with the upstream down: status %d, body %q; want it from the cache", w.Code, w.Body) + } +} + +func TestGitLFSObjectRefusesWrongContent(t *testing.T) { + u := newLFSUpstream(t) + u.content.Store("tampered content!!") + h := newLFSHandler(t, u) + path := fmt.Sprintf("/up/acme/widget.git/info/lfs/objects/%s/%d", u.oid, len(lfsTestContent)) + + for range 2 { + if w := lfsRequest(h, http.MethodGet, path, ""); w.Code == http.StatusOK && w.Body.String() == "tampered content!!" { + t.Fatal("served content that does not match its object ID") + } + } + if u.downloads.Load() != 2 { + t.Errorf("downloads = %d, want 2: the mismatching object must not be cached", u.downloads.Load()) + } +} + +func TestGitLFSRefusals(t *testing.T) { + u := newLFSUpstream(t) + h := newLFSHandler(t, u, "acme/*") + object := lfsObject{OID: u.oid, Size: int64(len(lfsTestContent))} + tests := []struct { + name, method, target, body string + status int + }{ + {"upload", http.MethodPost, "/up/acme/widget.git/info/lfs/objects/batch", lfsBatchBody("upload", object), http.StatusForbidden}, + {"sha512 objects", http.MethodPost, "/up/acme/widget.git/info/lfs/objects/batch", + `{"operation":"download","objects":[],"hash_algo":"sha512"}`, http.StatusConflict}, + {"other transfers", http.MethodPost, "/up/acme/widget.git/info/lfs/objects/batch", + `{"operation":"download","transfers":["ssh"],"objects":[]}`, http.StatusUnprocessableEntity}, + {"invalid oid", http.MethodPost, "/up/acme/widget.git/info/lfs/objects/batch", + lfsBatchBody("download", lfsObject{OID: "../x", Size: 1}), http.StatusUnprocessableEntity}, + {"batch GET", http.MethodGet, "/up/acme/widget.git/info/lfs/objects/batch", "", http.StatusMethodNotAllowed}, + {"repository outside repos", http.MethodPost, "/up/other/widget.git/info/lfs/objects/batch", lfsBatchBody("download", object), http.StatusNotFound}, + {"unknown repository", http.MethodPost, "/up/acme/missing.git/info/lfs/objects/batch", lfsBatchBody("download", object), http.StatusNotFound}, + {"object without size", http.MethodGet, "/up/acme/widget.git/info/lfs/objects/" + u.oid, "", http.StatusNotFound}, + {"uppercase oid", http.MethodGet, "/up/acme/widget.git/info/lfs/objects/" + strings.ToUpper(u.oid) + "/1", "", http.StatusNotFound}, + {"object PUT", http.MethodPut, "/up/acme/widget.git/info/lfs/objects/" + u.oid + "/1", "", http.StatusMethodNotAllowed}, + {"locks", http.MethodPost, "/up/acme/widget.git/info/lfs/locks/verify", "{}", http.StatusNotFound}, + {"missing object", http.MethodGet, "/up/acme/widget.git/info/lfs/objects/" + strings.Repeat("0", 64) + "/3", "", http.StatusNotFound}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + w := lfsRequest(h, tt.method, tt.target, tt.body) + if w.Code != tt.status || w.Header().Get("Content-Type") != gitLFSMediaType { + t.Errorf("status %d, type %q, body %s; want %d", w.Code, w.Header().Get("Content-Type"), w.Body, tt.status) + } + }) + } + if u.downloads.Load() != 0 { + t.Errorf("downloads = %d, want none", u.downloads.Load()) + } +} + +func TestGitLFSKeepsSignedURLsOutOfLogsAndDatabase(t *testing.T) { + u := newLFSUpstream(t) + h := newLFSHandler(t, u) + path := fmt.Sprintf("/up/acme/widget.git/info/lfs/objects/%s/%d", u.oid, len(lfsTestContent)) + + if w := lfsRequest(h, http.MethodGet, path, ""); w.Code != http.StatusOK { + t.Fatalf("GET: status %d, body %s", w.Code, w.Body) + } + _, versionPURL, err := packagePURLStrings(gitEcosystem, "up/acme/widget", u.oid) + if err != nil { + t.Fatal(err) + } + record, err := h.proxy.DB.GetArtifact(versionPURL, u.oid) + if err != nil || record == nil { + t.Fatalf("artifact record: %v, %v", record, err) + } + if want := u.store.URL + "/objects/" + u.oid; record.UpstreamURL != want { + t.Errorf("recorded upstream URL %q, want %q", record.UpstreamURL, want) + } + + // A failed download is logged without the signature too, although the + // connection error names the URL. + other := newLFSUpstream(t) + other.store.Close() + h = newLFSHandler(t, other) + if w := lfsRequest(h, http.MethodGet, path, ""); w.Code == http.StatusOK { + t.Fatalf("GET from an unreachable store: status %d", w.Code) + } + if !strings.Contains(other.logs.String(), other.store.URL+"/objects/"+other.oid) { + t.Fatalf("logs don't name the failed download:\n%s", other.logs.String()) + } + for _, logs := range []string{u.logs.String(), other.logs.String()} { + if strings.Contains(logs, lfsSignature) { + t.Errorf("logs contain the download URL's signature:\n%s", logs) + } + } +} + +func TestGitLFSBatchFromCacheWhenUpstreamFails(t *testing.T) { + u := newLFSUpstream(t) + h := newLFSHandler(t, u) + size := int64(len(lfsTestContent)) + missing := strings.Repeat("0", 64) + batch := lfsBatchBody("download", lfsObject{OID: u.oid, Size: size}, lfsObject{OID: missing, Size: 3}) + const batchPath = "/up/acme/widget.git/info/lfs/objects/batch" + + // Nothing cached yet: a failing upstream fails the batch. + u.batchStatus.Store(http.StatusServiceUnavailable) + if w := lfsRequest(h, http.MethodPost, batchPath, batch); w.Code != http.StatusBadGateway { + t.Fatalf("batch with nothing cached: status %d, body %s; want 502", w.Code, w.Body) + } + u.batchStatus.Store(0) + if w := lfsRequest(h, http.MethodGet, fmt.Sprintf("/up/acme/widget.git/info/lfs/objects/%s/%d", u.oid, size), ""); w.Code != http.StatusOK { + t.Fatalf("GET: status %d, body %s", w.Code, w.Body) + } + + // A refusal is the upstream's answer, not an outage. + u.batchStatus.Store(http.StatusForbidden) + if w := lfsRequest(h, http.MethodPost, batchPath, batch); w.Code != http.StatusBadGateway { + t.Errorf("batch the upstream refused: status %d, body %s; want 502", w.Code, w.Body) + } + + u.git.Close() + w := lfsRequest(h, http.MethodPost, batchPath, batch) + if w.Code != http.StatusOK { + t.Fatalf("batch with the upstream down: status %d, body %s", w.Code, w.Body) + } + var resp lfsBatchResponse + if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil { + t.Fatal(err) + } + if len(resp.Objects) != 2 { + t.Fatalf("objects = %+v, want the two requested", resp.Objects) + } + want := fmt.Sprintf("http://proxy.test/git/up/acme/widget.git/info/lfs/objects/%s/%d", u.oid, size) + if got := resp.Objects[0]; got.Actions["download"].Href != want || !got.Authenticated || got.Error != nil { + t.Errorf("cached object = %+v, want a download from %s", got, want) + } + if got := resp.Objects[1]; got.Actions != nil || got.Error == nil { + t.Errorf("uncached object = %+v, want an error", got) + } +} + +func TestGitLFSHeadDoesNotDownload(t *testing.T) { + u := newLFSUpstream(t) + h := newLFSHandler(t, u) + path := fmt.Sprintf("/up/acme/widget.git/info/lfs/objects/%s/%d", u.oid, len(lfsTestContent)) + + w := lfsRequest(h, http.MethodHead, path, "") + if w.Code != http.StatusOK || w.Header().Get("Content-Length") != fmt.Sprint(len(lfsTestContent)) { + t.Errorf("HEAD: status %d, Content-Length %q", w.Code, w.Header().Get("Content-Length")) + } + if u.downloads.Load() != 0 { + t.Errorf("downloads = %d, want none for a HEAD", u.downloads.Load()) + } + missing := fmt.Sprintf("/up/acme/widget.git/info/lfs/objects/%s/3", strings.Repeat("0", 64)) + if w := lfsRequest(h, http.MethodHead, missing, ""); w.Code != http.StatusNotFound { + t.Errorf("HEAD of a missing object: status %d, want 404", w.Code) + } +} + +func TestGitLFSObjectAfterBatchNeedsNoSecondBatch(t *testing.T) { + u := newLFSUpstream(t) + h := newLFSHandler(t, u) + size := int64(len(lfsTestContent)) + path := fmt.Sprintf("/up/acme/widget.git/info/lfs/objects/%s/%d", u.oid, size) + batch := lfsBatchBody("download", lfsObject{OID: u.oid, Size: size}) + + if w := lfsRequest(h, http.MethodPost, "/up/acme/widget.git/info/lfs/objects/batch", batch); w.Code != http.StatusOK { + t.Fatalf("batch: status %d, body %s", w.Code, w.Body) + } + if w := lfsRequest(h, http.MethodGet, path, ""); w.Code != http.StatusOK || w.Body.String() != lfsTestContent { + t.Fatalf("GET: status %d, body %q", w.Code, w.Body) + } + if u.batches.Load() != 1 || u.downloads.Load() != 1 { + t.Errorf("batches %d, downloads %d; want the client's batch and one download", u.batches.Load(), u.downloads.Load()) + } + + // A URL that stopped working before its time is replaced by a fresh one. + other := newLFSUpstream(t) + h = newLFSHandler(t, other) + if w := lfsRequest(h, http.MethodPost, "/up/acme/widget.git/info/lfs/objects/batch", batch); w.Code != http.StatusOK { + t.Fatalf("batch: status %d, body %s", w.Code, w.Body) + } + other.signature.Store("rotated") + if w := lfsRequest(h, http.MethodGet, path, ""); w.Code != http.StatusOK || w.Body.String() != lfsTestContent { + t.Fatalf("GET with a revoked URL: status %d, body %q", w.Code, w.Body) + } + if other.batches.Load() != 2 { + t.Errorf("batches = %d, want a second one for a fresh URL", other.batches.Load()) + } +} + +func TestGitLFSKeptDownloadsExpire(t *testing.T) { + now := time.Date(2026, 10, 25, 12, 0, 0, 0, time.UTC) + object := lfsObject{OID: strings.Repeat("a", 64), Size: 3} + href := "https://objects.example/a?sig=1" + tests := []struct { + name string + action lfsAction + at time.Duration + kept bool + }{ + {"no expiry", lfsAction{Href: href}, 4 * time.Minute, true}, + {"no expiry, later", lfsAction{Href: href}, 5 * time.Minute, false}, + {"expires_in", lfsAction{Href: href, ExpiresIn: 600}, 9 * time.Minute, true}, + {"expires_in, within the margin", lfsAction{Href: href, ExpiresIn: 600}, 10*time.Minute - 10*time.Second, false}, + {"expires_in too short to use", lfsAction{Href: href, ExpiresIn: 10}, 0, false}, + {"expires_at", lfsAction{Href: href, ExpiresAt: now.Add(20 * time.Minute).Format(time.RFC3339)}, 19 * time.Minute, true}, + {"expires_at, past", lfsAction{Href: href, ExpiresAt: now.Add(20 * time.Minute).Format(time.RFC3339)}, 20 * time.Minute, false}, + {"long expiry capped", lfsAction{Href: href, ExpiresIn: 86400}, 2 * time.Hour, false}, + {"relative href", lfsAction{Href: "/a"}, 0, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + var d lfsDownloads + d.put("repo", object, tt.action, now) + if _, kept := d.get("repo", object, now.Add(tt.at)); kept != tt.kept { + t.Errorf("kept = %v, want %v", kept, tt.kept) + } + }) + } + + var d lfsDownloads + d.put("repo", object, lfsAction{Href: href}, now) + if _, kept := d.get("repo", lfsObject{OID: object.OID, Size: 4}, now); kept { + t.Error("kept for another size") + } + if _, kept := d.get("other", object, now); kept { + t.Error("kept for another repository") + } + for i := range gitLFSKeptDownloads + 10 { + d.put("repo", lfsObject{OID: fmt.Sprintf("%064x", i), Size: 1}, lfsAction{Href: href}, now) + } + if len(d.entries) > gitLFSKeptDownloads { + t.Errorf("%d entries kept, want at most %d", len(d.entries), gitLFSKeptDownloads) + } +} + +func TestGitLFSObjectOfAnotherSizeIsRefused(t *testing.T) { + u := newLFSUpstream(t) + h := newLFSHandler(t, u) + path := fmt.Sprintf("/up/acme/widget.git/info/lfs/objects/%s/%d", u.oid, len(lfsTestContent)-1) + + if w := lfsRequest(h, http.MethodGet, path, ""); w.Code == http.StatusOK { + t.Fatalf("GET at the wrong size: status %d, body %q", w.Code, w.Body) + } + if u.downloads.Load() != 1 || u.batches.Load() != 1 { + t.Errorf("downloads %d, batches %d; want one of each, without a retry", u.downloads.Load(), u.batches.Load()) + } +} + +func TestExactSizeBody(t *testing.T) { + for _, tt := range []struct { + body string + size int64 + ok bool + }{ + {"abcdef", 6, true}, + {"abcdef", 5, false}, + {"abcdef", 7, false}, + {"", 0, true}, + {"a", 0, false}, + } { + got, err := io.ReadAll(&exactSizeBody{ReadCloser: io.NopCloser(strings.NewReader(tt.body)), left: tt.size}) + if (err == nil) != tt.ok || (err != nil && !errors.Is(err, errDownloadSize)) { + t.Errorf("%q at size %d: err %v, want ok %v", tt.body, tt.size, err, tt.ok) + } + if int64(len(got)) > tt.size+1 { + t.Errorf("%q at size %d: read %d bytes", tt.body, tt.size, len(got)) + } + } +} + +func TestGitLFSObjectCopiedFromAnotherRepository(t *testing.T) { + u := newLFSUpstream(t) + h := newLFSHandler(t, u) + object := func(repo string) string { + return fmt.Sprintf("/up/%s.git/info/lfs/objects/%s/%d", repo, u.oid, len(lfsTestContent)) + } + + if w := lfsRequest(h, http.MethodGet, object("acme/widget"), ""); w.Code != http.StatusOK { + t.Fatalf("GET: status %d, body %s", w.Code, w.Body) + } + w := lfsRequest(h, http.MethodGet, object("fork/widget"), "") + if w.Code != http.StatusOK || w.Body.String() != lfsTestContent { + t.Fatalf("GET from the fork: status %d, body %q", w.Code, w.Body) + } + if u.downloads.Load() != 1 || u.batches.Load() != 2 { + t.Errorf("downloads %d, batches %d; want the fork's object copied after its own batch", u.downloads.Load(), u.batches.Load()) + } + cached, err := h.proxy.GetCachedArtifact(t.Context(), gitEcosystem, "up/fork/widget", u.oid, u.oid) + if err != nil || cached == nil { + t.Fatalf("fork's object not cached: %v, %v", cached, err) + } + _ = cached.Reader.Close() + + // A repository the upstream says lacks the object doesn't get it, though + // a copy is stored. + if w := lfsRequest(h, http.MethodGet, object("stranger/widget"), ""); w.Code != http.StatusNotFound { + t.Errorf("GET from a repository without the object: status %d, body %s; want 404", w.Code, w.Body) + } +} diff --git a/internal/handler/git_mirror.go b/internal/handler/git_mirror.go new file mode 100644 index 0000000..38be233 --- /dev/null +++ b/internal/handler/git_mirror.go @@ -0,0 +1,149 @@ +package handler + +import ( + "context" + "fmt" + "log/slog" + "net/url" + "path" + "strings" + + "github.com/git-pkgs/proxy/internal/gitcache" +) + +// maxSubmoduleDepth bounds how deeply Mirror follows submodules of +// submodules. +const maxSubmoduleDepth = 8 + +// Mirror caches the repository at location, a host and path such as +// github.com/acme/widgets as a pkg:git PURL names it, from the upstream.git +// host serving it. With version, a full commit ID or a tag, it caches that +// commit too, and the commits its submodules pin, from the upstream.git +// hosts serving them. A submodule no upstream.git host serves is skipped. +// Clones through /git are then served from those copies. +func (h *GitHandler) Mirror(ctx context.Context, location, version string) (gitcache.MirrorResult, error) { + return h.mirror(ctx, location, version, map[string]bool{}, 0) +} + +func (h *GitHandler) mirror(ctx context.Context, location, version string, seen map[string]bool, depth int) (gitcache.MirrorResult, error) { + repo, err := h.mirrorRepository(location) + if err != nil { + return gitcache.MirrorResult{}, err + } + result, err := h.cache.Mirror(ctx, repo.key, repo.url, version, repo.upstream.fetchWants) + if err != nil { + return result, err + } + for _, sub := range result.Submodules { + subLocation, err := gitSubmoduleLocation(repo.url, sub.URL) + if err == nil { + _, err = h.mirrorRepository(subLocation) + } + if err != nil { + h.logger().Warn("git mirror: skipping submodule", "repository", location, "submodule", sub.Path, "url", sub.URL, "error", err) + continue + } + if seen[subLocation+"@"+sub.Commit] { + continue + } + seen[subLocation+"@"+sub.Commit] = true + if depth >= maxSubmoduleDepth { + return result, fmt.Errorf("submodule %s: nested more than %d deep", sub.Path, maxSubmoduleDepth) + } + subResult, err := h.mirror(ctx, subLocation, sub.Commit, seen, depth+1) + if err != nil { + return result, fmt.Errorf("submodule %s: %w", sub.Path, err) + } + result.Cached = result.Cached && subResult.Cached + result.Bytes += subResult.Bytes + } + return result, nil +} + +func (h *GitHandler) logger() *slog.Logger { + if h.proxy != nil && h.proxy.Logger != nil { + return h.proxy.Logger + } + return slog.Default() +} + +// gitSubmoduleLocation turns the URL .gitmodules gives a submodule into a +// location as Mirror takes it. A relative URL is resolved against the +// superproject's repoURL, as git does; ssh, git and scp-like URLs name the +// host and path the repository has there. +func gitSubmoduleLocation(repoURL, submoduleURL string) (string, error) { + var host, repoPath string + switch { + case strings.HasPrefix(submoduleURL, "./"), strings.HasPrefix(submoduleURL, "../"): + u, err := url.Parse(repoURL) + if err != nil { + return "", err + } + host, repoPath = u.Host, path.Join(u.Path, submoduleURL) + case strings.Contains(submoduleURL, "://"): + u, err := url.Parse(submoduleURL) + if err != nil { + return "", err + } + switch u.Scheme { + case "http", "https": + host = u.Host + case "ssh", "git", "git+ssh", "ssh+git": + host = u.Hostname() + default: + return "", fmt.Errorf("unsupported submodule URL %q", submoduleURL) + } + repoPath = u.Path + default: + // scp-like: [user@]host:path + hostPart, p, ok := strings.Cut(submoduleURL, ":") + if !ok || strings.Contains(hostPart, "/") { + return "", fmt.Errorf("unsupported submodule URL %q", submoduleURL) + } + _, host, _ = strings.Cut(hostPart, "@") + if host == "" { + host = hostPart + } + repoPath = p + } + repoPath = strings.Trim(path.Clean("/"+repoPath), "/") + if host == "" || repoPath == "" { + return "", fmt.Errorf("unsupported submodule URL %q", submoduleURL) + } + return strings.ToLower(host) + "/" + repoPath, nil +} + +// mirrorRepository resolves location to a repository of the upstream.git +// host whose URL it starts with, the longest such URL if several do. +func (h *GitHandler) mirrorRepository(location string) (gitRepository, error) { + var best, bestPrefix, rest string + for name, upstream := range h.upstreams { + prefix := gitLocationPrefix(upstream.URL) + path, ok := strings.CutPrefix(location, prefix) + if prefix == "" || !ok || path == "" { + continue + } + if len(prefix) > len(bestPrefix) || (len(prefix) == len(bestPrefix) && name < best) { + best, bestPrefix, rest = name, prefix, path + } + } + if best == "" { + return gitRepository{}, fmt.Errorf("no upstream.git host serves %s", location) + } + repo, status, msg := h.repository(best + "/" + rest) + if status != 0 { + return gitRepository{}, fmt.Errorf("%s: %s", location, msg) + } + return repo, nil +} + +// gitLocationPrefix is how a pkg:git PURL names the repositories under an +// upstream URL: its host and path, ending in a slash. Empty for a URL +// without a host. +func gitLocationPrefix(upstreamURL string) string { + u, err := url.Parse(upstreamURL) + if err != nil || u.Host == "" { + return "" + } + return strings.ToLower(u.Host) + strings.TrimSuffix(u.Path, "/") + "/" +} diff --git a/internal/handler/git_mirror_test.go b/internal/handler/git_mirror_test.go new file mode 100644 index 0000000..227bd71 --- /dev/null +++ b/internal/handler/git_mirror_test.go @@ -0,0 +1,154 @@ +package handler + +import ( + "context" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/git-pkgs/proxy/internal/config" +) + +func TestGitMirrorLocation(t *testing.T) { + h := NewGitHandler(nil, nil, config.UpstreamConfig{Git: map[string]config.GitUpstream{ + "github": {URL: "https://github.com"}, + "wikimedia": {URL: "https://gitlab.wikimedia.org", Repos: []string{"mediawiki/**"}}, + "sub": {URL: "https://git.example/r/"}, + "nested": {URL: "https://git.example/r/deep"}, + }}) + tests := []struct { + location string + ok bool + key, repoURL string + }{ + {"github.com/acme/widgets", true, h.upstreams["github"].dir + "/acme/widgets.git", "https://github.com/acme/widgets"}, + {"github.com/acme/widgets.git", true, h.upstreams["github"].dir + "/acme/widgets.git", "https://github.com/acme/widgets.git"}, + {"gitlab.wikimedia.org/mediawiki/skins/Vector", true, h.upstreams["wikimedia"].dir + "/mediawiki/skins/Vector.git", "https://gitlab.wikimedia.org/mediawiki/skins/Vector"}, + {"gitlab.wikimedia.org/other/repo", false, "", ""}, + {"git.example/r/a", true, h.upstreams["sub"].dir + "/a.git", "https://git.example/r/a"}, + // The longest matching upstream URL wins. + {"git.example/r/deep/a", true, h.upstreams["nested"].dir + "/a.git", "https://git.example/r/deep/a"}, + {"git.example/other", false, "", ""}, + {"git.example/r", false, "", ""}, + {"github.com.evil/acme/widgets", false, "", ""}, + {"github.com/acme/../widgets", false, "", ""}, + {"codeberg.org/forgejo/forgejo", false, "", ""}, + } + for _, tt := range tests { + t.Run(tt.location, func(t *testing.T) { + repo, err := h.mirrorRepository(tt.location) + if (err == nil) != tt.ok { + t.Fatalf("error %v, want ok %v", err, tt.ok) + } + if tt.ok && (repo.key != tt.key || repo.url != tt.repoURL) { + t.Errorf("key %q, URL %q; want %q, %q", repo.key, repo.url, tt.key, tt.repoURL) + } + }) + } +} + +func TestGitMirrorCachesCommitForClones(t *testing.T) { + g := newGitTestSetup(t, 0, 0) + sha := runGitCommand(t, g.work, "rev-parse", "HEAD") + location := strings.TrimPrefix(g.upstreamURL, "http://") + "/repo" + + got, err := g.handler.Mirror(context.Background(), location, sha) + if err != nil { + t.Fatalf("Mirror: %v", err) + } + if got.Cached { + t.Errorf("first mirror = %+v, want fetched", got) + } + got, err = g.handler.Mirror(context.Background(), location, sha) + if err != nil || !got.Cached { + t.Errorf("second mirror = %+v, %v, want cached", got, err) + } + + // With the upstream gone, a clone through the proxy gets the mirrored copy. + g.upstream.Close() + clone := t.TempDir() + runGitCommand(t, "", "clone", "--quiet", g.url(), clone) + if head := runGitCommand(t, clone, "rev-parse", "HEAD"); head != sha { + t.Errorf("cloned HEAD %s, want %s", head, sha) + } +} + +func TestGitSubmoduleLocation(t *testing.T) { + tests := []struct { + repoURL, submoduleURL, want string + }{ + {"https://github.com/acme/widgets", "../lib.git", "github.com/acme/lib.git"}, + {"https://github.com/acme/widgets.git", "../../other/lib", "github.com/other/lib"}, + {"https://github.com/acme/widgets", "./vendored", "github.com/acme/widgets/vendored"}, + {"http://127.0.0.1:8080/team/repo", "../lib.git", "127.0.0.1:8080/team/lib.git"}, + {"https://github.com/acme/widgets", "https://GitLab.com/group/lib.git/", "gitlab.com/group/lib.git"}, + {"https://github.com/acme/widgets", "ssh://git@github.com:22/acme/lib.git", "github.com/acme/lib.git"}, + {"https://github.com/acme/widgets", "git://git.example/lib", "git.example/lib"}, + {"https://github.com/acme/widgets", "git@github.com:acme/lib.git", "github.com/acme/lib.git"}, + {"https://github.com/acme/widgets", "/srv/git/lib.git", ""}, + {"https://github.com/acme/widgets", "file:///srv/git/lib.git", ""}, + {"https://github.com/acme/widgets", "", ""}, + } + for _, tt := range tests { + got, err := gitSubmoduleLocation(tt.repoURL, tt.submoduleURL) + if tt.want == "" { + if err == nil { + t.Errorf("location of %q = %q, want an error", tt.submoduleURL, got) + } + continue + } + if err != nil || got != tt.want { + t.Errorf("location of %q from %s = %q, %v; want %q", tt.submoduleURL, tt.repoURL, got, err, tt.want) + } + } +} + +// TestGitMirrorCachesSubmodules mirrors a commit with a submodule served by +// the same upstream and one on a host no upstream.git serves, which is +// skipped. +func TestGitMirrorCachesSubmodules(t *testing.T) { + g := newGitTestSetup(t, 0, 0) + libBare := filepath.Join(g.root, "lib.git") + runGitCommand(t, "", "init", "--quiet", "--bare", "--initial-branch=main", libBare) + libWork := t.TempDir() + runGitCommand(t, "", "clone", "--quiet", libBare, libWork) + runGitCommand(t, libWork, "commit", "--quiet", "--allow-empty", "-m", "lib") + runGitCommand(t, libWork, "push", "--quiet", "origin", "HEAD:main") + libCommit := runGitCommand(t, libWork, "rev-parse", "HEAD") + + gitmodules := "[submodule \"lib\"]\n\tpath = lib\n\turl = ../lib.git\n" + + "[submodule \"elsewhere\"]\n\tpath = elsewhere\n\turl = https://elsewhere.example/x.git\n" + if err := os.WriteFile(filepath.Join(g.work, ".gitmodules"), []byte(gitmodules), 0o600); err != nil { + t.Fatal(err) + } + runGitCommand(t, g.work, "add", ".gitmodules") + runGitCommand(t, g.work, "update-index", "--add", "--cacheinfo", "160000,"+libCommit+",lib") + runGitCommand(t, g.work, "update-index", "--add", "--cacheinfo", "160000,"+strings.Repeat("ab", 20)+",elsewhere") + runGitCommand(t, g.work, "commit", "--quiet", "-m", "submodules") + runGitCommand(t, g.work, "push", "--quiet", "origin", "HEAD:main") + sha := runGitCommand(t, g.work, "rev-parse", "HEAD") + location := strings.TrimPrefix(g.upstreamURL, "http://") + "/repo" + + got, err := g.handler.Mirror(context.Background(), location, sha) + if err != nil { + t.Fatalf("Mirror: %v", err) + } + if got.Cached { + t.Errorf("first mirror = %+v, want fetched", got) + } + if got, err = g.handler.Mirror(context.Background(), location, sha); err != nil || !got.Cached { + t.Errorf("second mirror = %+v, %v, want cached", got, err) + } + if !strings.Contains(g.logs.String(), "elsewhere.example") { + t.Errorf("log doesn't name the skipped submodule:\n%s", g.logs.String()) + } + + // With the upstream gone, the submodule's commit is served from the cache. + g.upstream.Close() + clone := t.TempDir() + runGitCommand(t, "", "clone", "--quiet", g.server.URL+"/git/up/lib", clone) + if head := runGitCommand(t, clone, "rev-parse", "HEAD"); head != libCommit { + t.Errorf("cloned lib HEAD %s, want %s", head, libCommit) + } +} diff --git a/internal/handler/git_test.go b/internal/handler/git_test.go new file mode 100644 index 0000000..aeec2bc --- /dev/null +++ b/internal/handler/git_test.go @@ -0,0 +1,341 @@ +package handler + +import ( + "bufio" + "fmt" + "io" + "log/slog" + "math/rand/v2" + "net" + "net/http" + "net/http/cgi" + "net/http/httptest" + "os" + "os/exec" + "path/filepath" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/git-pkgs/proxy/internal/config" + "github.com/git-pkgs/proxy/internal/gitcache" +) + +func TestParseGitRequest(t *testing.T) { + h := NewGitHandler(nil, nil, config.UpstreamConfig{Git: map[string]config.GitUpstream{ + "up": {URL: "https://git.example/r/"}, + "limited": {URL: "https://git.example", Repos: []string{"allowed/*"}}, + }}) + up, limited := h.upstreams["up"].dir, h.upstreams["limited"].dir + tests := []struct { + method, target string + status int + key, repoURL string + }{ + {"GET", "/up/repo.git/info/refs?service=git-upload-pack", 0, up + "/repo.git", "https://git.example/r/repo.git"}, + {"GET", "/up/a/b/info/refs?service=git-upload-pack", 0, up + "/a/b.git", "https://git.example/r/a/b"}, + {"POST", "/up/a/b%20c/git-upload-pack", 0, up + "/a/b c.git", "https://git.example/r/a/b%20c"}, + {"GET", "/up/a.git/b/info/refs?service=git-upload-pack", http.StatusNotFound, "", ""}, + {"GET", "/up/a/../b/info/refs?service=git-upload-pack", http.StatusNotFound, "", ""}, + {"GET", "/up/a//b/info/refs?service=git-upload-pack", http.StatusNotFound, "", ""}, + {"GET", "/up/.git/info/refs?service=git-upload-pack", http.StatusNotFound, "", ""}, + {"GET", "/other/repo/info/refs?service=git-upload-pack", http.StatusNotFound, "", ""}, + {"GET", "/up/info/refs?service=git-upload-pack", http.StatusNotFound, "", ""}, + {"GET", "/up/repo/info/refs?service=git-receive-pack", http.StatusForbidden, "", ""}, + {"POST", "/up/repo/git-receive-pack", http.StatusForbidden, "", ""}, + {"GET", "/up/repo/info/refs", http.StatusForbidden, "", ""}, + {"GET", "/up/repo/objects/info/packs", http.StatusNotFound, "", ""}, + {"POST", "/up/repo/info/refs?service=git-upload-pack", http.StatusMethodNotAllowed, "", ""}, + {"GET", "/up/repo/git-upload-pack", http.StatusMethodNotAllowed, "", ""}, + {"GET", "/limited/allowed/repo/info/refs?service=git-upload-pack", 0, limited + "/allowed/repo.git", "https://git.example/allowed/repo"}, + {"GET", "/limited/other/repo/info/refs?service=git-upload-pack", http.StatusNotFound, "", ""}, + } + for _, tt := range tests { + t.Run(tt.method+" "+tt.target, func(t *testing.T) { + r := httptest.NewRequest(tt.method, tt.target, nil) + r.Header.Set("Content-Type", gitRequestType) + req, status, _ := h.parse(r) + if status != tt.status { + t.Fatalf("status %d, want %d", status, tt.status) + } + if status == 0 && (req.key != tt.key || req.repoURL != tt.repoURL) { + t.Errorf("key %q, URL %q; want %q, %q", req.key, req.repoURL, tt.key, tt.repoURL) + } + }) + } + + r := httptest.NewRequest(http.MethodPost, "/up/repo/git-upload-pack", nil) + if _, status, _ := h.parse(r); status != http.StatusUnsupportedMediaType { + t.Errorf("POST without the request content type: status %d, want 415", status) + } +} + +// TestGitUpstreamCacheDirectory checks the cache directory follows the +// upstream's URL, so repointing an upstream does not serve the old host's +// repositories. +func TestGitUpstreamCacheDirectory(t *testing.T) { + dir := func(url string) string { + h := NewGitHandler(nil, nil, config.UpstreamConfig{Git: map[string]config.GitUpstream{"up": {URL: url}}}) + return h.upstreams["up"].dir + } + if a, b := dir("https://git.example"), dir("https://other.example"); a == b || !strings.HasPrefix(a, "up-") { + t.Errorf("directories %q and %q, want distinct ones named after the upstream", a, b) + } + if a, b := dir("https://git.example"), dir("https://git.example/"); a != b { + t.Errorf("a trailing slash changed the directory: %q, %q", a, b) + } +} + +// TestGitFetchByIDOffWithCredentials checks commits are not fetched by ID +// for an upstream that upstream.auth has credentials for: there a fetch by +// ID could reach repositories outside its repos allowlist. +func TestGitFetchByIDOffWithCredentials(t *testing.T) { + h := NewGitHandler(nil, nil, config.UpstreamConfig{ + Git: map[string]config.GitUpstream{ + "public": {URL: "https://github.com"}, + "private": {URL: "https://git.example", Repos: []string{"team/*"}}, + "scoped": {URL: "https://other.example", Repos: []string{"team/*"}}, + }, + Auth: map[string]config.AuthConfig{ + "https://git.example": {Type: "bearer", Token: "t"}, + "https://other.example/team": {Type: "bearer", Token: "t"}, + }, + }) + for name, want := range map[string]bool{"public": true, "private": false, "scoped": false} { + if got := h.upstreams[name].fetchWants; got != want { + t.Errorf("%s: fetchWants = %v, want %v", name, got, want) + } + } +} + +func runGitCommand(t *testing.T, dir string, args ...string) string { + t.Helper() + cmd := exec.Command("git", args...) + cmd.Dir = dir + cmd.Env = []string{ + "PATH=" + os.Getenv("PATH"), "HOME=" + t.TempDir(), "GIT_CONFIG_NOSYSTEM=1", + "GIT_AUTHOR_NAME=test", "GIT_AUTHOR_EMAIL=test@example.com", + "GIT_COMMITTER_NAME=test", "GIT_COMMITTER_EMAIL=test@example.com", + } + out, err := cmd.CombinedOutput() + if err != nil { + t.Fatalf("git %s: %v\n%s", strings.Join(args, " "), err, out) + } + return strings.TrimSpace(string(out)) +} + +// gitTestSetup is a GitHandler in front of a cache of one upstream +// repository, "repo", served by git http-backend. +type gitTestSetup struct { + work string + // root holds the upstream's bare repositories. + root string + server *httptest.Server + // upstream serves the repository, at upstreamURL/repo, and handler is + // the GitHandler under test. + upstream *httptest.Server + upstreamURL string + handler *GitHandler + logs *syncLog + // slow delays every upstream request by half a second. + slow atomic.Bool + // active counts the requests the handler is serving. + active atomic.Int32 +} + +// newGitTestSetup serves the cache with the given server read timeout and, +// unless zero, GitHandler.writeStall. +func newGitTestSetup(t *testing.T, readTimeout, writeStall time.Duration) *gitTestSetup { + t.Helper() + execPath := runGitCommand(t, "", "--exec-path") + backendPath := "" + for _, name := range []string{"git-http-backend", "git-http-backend.exe"} { + if path := filepath.Join(execPath, name); fileExists(path) { + backendPath = path + } + } + if backendPath == "" { + t.Skip("git http-backend is not installed") + } + root := t.TempDir() + bare := filepath.Join(root, "repo.git") + runGitCommand(t, "", "init", "--quiet", "--bare", "--initial-branch=main", bare) + runGitCommand(t, bare, "config", "uploadpack.allowAnySHA1InWant", "true") + g := &gitTestSetup{work: t.TempDir(), root: root, logs: &syncLog{}} + runGitCommand(t, "", "clone", "--quiet", bare, g.work) + runGitCommand(t, g.work, "commit", "--quiet", "--allow-empty", "-m", "first") + runGitCommand(t, g.work, "push", "--quiet", "origin", "HEAD:main") + + backend := &cgi.Handler{ + Path: backendPath, + Env: []string{"PATH=" + os.Getenv("PATH"), "GIT_PROJECT_ROOT=" + root, "GIT_HTTP_EXPORT_ALL=1"}, + } + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if g.slow.Load() { + time.Sleep(500 * time.Millisecond) + } + backend.ServeHTTP(w, r) + })) + t.Cleanup(upstream.Close) + g.upstream, g.upstreamURL = upstream, upstream.URL + + logger := slog.New(slog.NewTextHandler(g.logs, nil)) + cache, err := gitcache.New(gitcache.Options{ + CacheDir: t.TempDir(), + RefreshWait: 5 * time.Second, + StaleMaxAge: time.Hour, + Client: &http.Client{}, + Logger: logger, + Upstreams: map[string]string{"up": gitcache.UpstreamDir("up", upstream.URL)}, + }) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = cache.Close() }) + h := NewGitHandler(&Proxy{Logger: logger}, cache, config.UpstreamConfig{Git: map[string]config.GitUpstream{"up": {URL: upstream.URL}}}) + if writeStall > 0 { + h.writeStall = writeStall + } + g.handler = h + routes := http.StripPrefix("/git", h.Routes()) + g.server = httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + g.active.Add(1) + defer g.active.Add(-1) + routes.ServeHTTP(w, r) + })) + g.server.Config.ReadTimeout = readTimeout + g.server.Start() + t.Cleanup(g.server.Close) + return g +} + +func (g *gitTestSetup) url() string { + return g.server.URL + "/git/up/repo" +} + +type syncLog struct { + mu sync.Mutex + buf strings.Builder +} + +func (l *syncLog) Write(p []byte) (int, error) { + l.mu.Lock() + defer l.mu.Unlock() + return l.buf.Write(p) +} + +func (l *syncLog) String() string { + l.mu.Lock() + defer l.mu.Unlock() + return l.buf.String() +} + +// TestGitRequestBodyOutlastsServerReadTimeout sends a protocol v0 request +// whose haves come after a want the cache must fetch first, so upload-pack +// reads them after the server's read timeout has passed. +func TestGitRequestBodyOutlastsServerReadTimeout(t *testing.T) { + g := newGitTestSetup(t, 200*time.Millisecond, 0) + runGitCommand(t, g.work, "commit", "--quiet", "--allow-empty", "-m", "pull request") + runGitCommand(t, g.work, "push", "--quiet", "origin", "HEAD:refs/pull/1/head") + sha := runGitCommand(t, g.work, "rev-parse", "HEAD") + runGitCommand(t, "", "clone", "--quiet", g.url(), filepath.Join(t.TempDir(), "clone")) + + var body strings.Builder + body.WriteString(pktLine("want "+sha+" side-band-64k\n") + "0000") + for i := range 2000 { + body.WriteString(pktLine(fmt.Sprintf("have %040x\n", i+1))) + } + body.WriteString(pktLine("done\n")) + + g.slow.Store(true) + resp, err := http.Post(g.url()+"/git-upload-pack", gitRequestType, strings.NewReader(body.String())) + if err != nil { + t.Fatal(err) + } + defer func() { _ = resp.Body.Close() }() + out, _ := io.ReadAll(resp.Body) + if resp.StatusCode != http.StatusOK || !strings.Contains(string(out), "PACK") { + t.Errorf("status %d, no pack in %d bytes: %.200q", resp.StatusCode, len(out), out) + } +} + +// TestGitSlowRequestBodyStartsNothing sends part of a request body and then +// nothing. The request ends at the server's read timeout, without an +// upload-pack waiting for the rest. +func TestGitSlowRequestBodyStartsNothing(t *testing.T) { + g := newGitTestSetup(t, 200*time.Millisecond, 0) + runGitCommand(t, "", "clone", "--quiet", g.url(), filepath.Join(t.TempDir(), "clone")) + + conn, err := net.Dial("tcp", g.server.Listener.Addr().String()) + if err != nil { + t.Fatal(err) + } + defer func() { _ = conn.Close() }() + part := pktLine("command=ls-refs\n") + _, err = fmt.Fprintf(conn, "POST /git/up/repo/git-upload-pack HTTP/1.1\r\nHost: proxy\r\n"+ + "Content-Type: %s\r\nGit-Protocol: version=2\r\nContent-Length: 100\r\n\r\n%s", gitRequestType, part) + if err != nil { + t.Fatal(err) + } + _ = conn.SetReadDeadline(time.Now().Add(10 * time.Second)) + resp, err := http.ReadResponse(bufio.NewReader(conn), nil) + if err != nil { + t.Fatalf("no answer to a request whose body stopped: %v", err) + } + _ = resp.Body.Close() + if resp.StatusCode != http.StatusBadRequest { + t.Errorf("status %d, want %d", resp.StatusCode, http.StatusBadRequest) + } +} + +// TestGitStalledClientIsDropped fetches a pack larger than the connection +// buffers and never reads it. The request ends once a write has waited +// writeStall, rather than holding upload-pack. +func TestGitStalledClientIsDropped(t *testing.T) { + g := newGitTestSetup(t, 0, 200*time.Millisecond) + data := make([]byte, 16<<20) + _, _ = rand.NewChaCha8([32]byte{}).Read(data) + if err := os.WriteFile(filepath.Join(g.work, "large"), data, 0o600); err != nil { + t.Fatal(err) + } + runGitCommand(t, g.work, "add", "large") + runGitCommand(t, g.work, "commit", "--quiet", "-m", "large") + runGitCommand(t, g.work, "push", "--quiet", "origin", "HEAD:main") + sha := runGitCommand(t, g.work, "rev-parse", "HEAD") + runGitCommand(t, "", "clone", "--quiet", g.url(), filepath.Join(t.TempDir(), "clone")) + + conn, err := net.Dial("tcp", g.server.Listener.Addr().String()) + if err != nil { + t.Fatal(err) + } + defer func() { _ = conn.Close() }() + body := pktLine("want "+sha+" side-band-64k\n") + "0000" + pktLine("done\n") + _, err = fmt.Fprintf(conn, "POST /git/up/repo/git-upload-pack HTTP/1.1\r\nHost: proxy\r\n"+ + "Content-Type: %s\r\nContent-Length: %d\r\n\r\n%s", gitRequestType, len(body), body) + if err != nil { + t.Fatal(err) + } + for deadline := time.Now().Add(10 * time.Second); g.active.Load() == 0; { + if time.Now().After(deadline) { + t.Fatal("request never reached the handler") + } + time.Sleep(10 * time.Millisecond) + } + for deadline := time.Now().Add(10 * time.Second); g.active.Load() != 0; { + if time.Now().After(deadline) { + t.Fatal("the handler still serves a client that stopped reading") + } + time.Sleep(10 * time.Millisecond) + } +} + +func pktLine(payload string) string { + return fmt.Sprintf("%04x%s", len(payload)+4, payload) +} + +func fileExists(path string) bool { + _, err := os.Stat(path) + return err == nil +} diff --git a/internal/handler/go.go b/internal/handler/go.go index c528472..08dae57 100644 --- a/internal/handler/go.go +++ b/internal/handler/go.go @@ -1,13 +1,20 @@ package handler import ( + "crypto/sha256" + "encoding/hex" "errors" "fmt" "net/http" + "net/url" "strings" + "github.com/git-pkgs/proxy/internal/database" + "github.com/git-pkgs/proxy/internal/packageurl" "github.com/git-pkgs/proxy/internal/retention" + "github.com/git-pkgs/purl" "github.com/git-pkgs/registries/fetch" + gomodule "golang.org/x/mod/module" ) const ( @@ -15,15 +22,13 @@ const ( asciiCaseOffset = 32 // difference between lowercase and uppercase ASCII letters ) -// Module zips are stored under pkg:golang/{module path}, which the PURL -// rules lowercase, so a package rule covers a module whatever case either -// is written in. A major version suffix (/v2) is part of the module path -// and so a module of its own. A key in the escaped form proxy URLs and the -// module cache use (github.com/!azure) does not survive the default -// mapping's round trip and is refused; the handler stores decoded paths, -// so such a key could never match. func init() { - retention.Default.Register(retention.Spec{Key: "golang", CanonicalPackage: retention.DefaultCanonical("golang")}) + retention.Default.Register(retention.Spec{Key: "golang", CanonicalPackage: golangRetentionKey}) +} + +func golangRetentionKey(p *purl.PURL) (string, bool) { + key, ok := retention.DefaultCanonical("golang")(p) + return packageurl.PolicyPackageKey(key), ok } // GoHandler handles Go module proxy protocol requests. @@ -34,6 +39,7 @@ type GoHandler struct { sumDBs map[string]string sumDBOffline bool sumDBProbes goSumDBProbes + vulnDBURL string } // NewGoHandler creates a new Go module proxy handler. @@ -43,6 +49,7 @@ func NewGoHandler(proxy *Proxy, proxyURL string) *GoHandler { upstreamURL: goUpstream, proxyURL: strings.TrimSuffix(proxyURL, "/"), sumDBs: map[string]string{defaultGoSumDBName: defaultGoSumDBURL}, + vulnDBURL: defaultGoVulnDBURL, } } @@ -57,7 +64,9 @@ func NewGoHandlerWithUpstream(proxy *Proxy, proxyURL, upstreamURL string) *GoHan func (h *GoHandler) Routes() http.Handler { // Go module paths can contain slashes, so just use the handler directly return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if r.Method != http.MethodGet { + // govulncheck sends HEAD for index/modules.json.gz to check that a + // -db other than vuln.go.dev is a vulnerability database. + if r.Method != http.MethodGet && (r.Method != http.MethodHead || !strings.HasPrefix(r.URL.Path, "/vulndb/")) { http.Error(w, "method not allowed", http.StatusMethodNotAllowed) return } @@ -75,24 +84,47 @@ func (h *GoHandler) handleRequest(w http.ResponseWriter, r *http.Request) { return } + // So do vulnerability database requests, which govulncheck sends when + // -db points at /go/vulndb. A module path's first element holds a + // dot, so neither prefix can be a module. + if rest, ok := strings.CutPrefix(path, "vulndb/"); ok { + h.handleVulnDB(w, r, rest) + return + } + // Check for @v/ pattern to identify module requests if idx := strings.Index(path, "/@v/"); idx >= 0 { module := path[:idx] rest := path[idx+4:] // after "/@v/" decodedMod := decodeGoModule(module) + cooldown := h.cooldownEnabled() switch { + case rest == "list" && cooldown: + h.serveCooldownList(w, r, module, decodedMod) + case rest == "list": // GET /{module}/@v/list - list versions h.proxyCached(w, r, decodedMod+"/@v/list") + case strings.HasSuffix(rest, ".info") && cooldown: + h.serveCooldownInfo(w, r, module, decodedMod, rest) + case strings.HasSuffix(rest, ".info"): // GET /{module}/@v/{version}.info - version metadata - h.proxyCached(w, r, decodedMod+"/@v/"+rest) + h.proxyVersionFile(w, r, decodedMod+"/@v/"+rest, strings.TrimSuffix(rest, ".info")) case strings.HasSuffix(rest, ".mod"): // GET /{module}/@v/{version}.mod - go.mod file - h.proxyCached(w, r, decodedMod+"/@v/"+rest) + version, err := gomodule.UnescapeVersion(strings.TrimSuffix(rest, ".mod")) + if err != nil { + http.NotFound(w, r) + return + } + if h.checkCooldown(w, r, module, decodedMod, version) { + return + } + h.proxyVersionFile(w, r, decodedMod+"/@v/"+rest, strings.TrimSuffix(rest, ".mod")) case strings.HasSuffix(rest, ".zip"): // GET /{module}/@v/{version}.zip - source archive (cache this) @@ -108,6 +140,10 @@ func (h *GoHandler) handleRequest(w http.ResponseWriter, r *http.Request) { // Check for @latest if strings.HasSuffix(path, "/@latest") { module := strings.TrimSuffix(path, "/@latest") + if h.cooldownEnabled() { + h.serveCooldownLatest(w, r, module, decodeGoModule(module)) + return + } h.proxyCached(w, r, decodeGoModule(module)+"/@latest") return } @@ -119,12 +155,30 @@ func (h *GoHandler) handleRequest(w http.ResponseWriter, r *http.Request) { func (h *GoHandler) handleDownload(w http.ResponseWriter, r *http.Request, module, version string) { // Decode module path (! followed by lowercase = uppercase) decodedModule := decodeGoModule(module) - filename := fmt.Sprintf("%s@%s.zip", lastComponent(decodedModule), version) + filename := goZipFilename(decodedModule, version) - h.proxy.Logger.Info("go module download request", + h.proxy.Logger.Debug("go module download request", "module", decodedModule, "version", version) + // The URL escapes uppercase letters in the version (v1.0.0-!r!c1 for + // v1.0.0-RC1), and the zip is cached under that form, so the denylist + // is checked against the version itself. + // A version that doesn't unescape can't be checked, so it isn't fetched. + unescaped, err := gomodule.UnescapeVersion(version) + if err != nil { + http.NotFound(w, r) + return + } + if h.proxy.versionDenied("golang", decodedModule, unescaped) { + http.Error(w, ErrVersionDenied.Error()+": "+canonicalVersionPURL("golang", decodedModule, unescaped), http.StatusForbidden) + return + } + if h.checkCooldown(w, r, module, decodedModule, unescaped) { + return + } + downloadURL := h.upstreamURL + r.URL.Path + h.discardOtherModulesZip(decodedModule, module, version, filename) result, err := h.proxy.GetOrFetchArtifactFromURL( r.Context(), "golang", decodedModule, version, filename, downloadURL, ) @@ -148,11 +202,111 @@ func (h *GoHandler) handleDownload(w http.ResponseWriter, r *http.Request, modul ServeArtifactRequest(w, r, result) } +// Keep the module spelling hash used by caches with lowercased PURL keys. +func goZipFilename(module, version string) string { + base := lastComponent(module) + "@" + version + if module == strings.ToLower(module) { + return base + ".zip" + } + digest := sha256.Sum256([]byte(module)) + return base + "~" + hex.EncodeToString(digest[:goModuleHashBytes]) + ".zip" +} + +// goModuleHashBytes is how much of a module path's hash a cached zip's +// filename carries: enough to tell apart paths that differ only in case. +const goModuleHashBytes = 8 + +// An old cache key may combine case-distinct modules. The upstream path +// identifies which module owns an individual archive. +func (p *Proxy) rekeyLegacyGoArtifact(pkgPURL, versionPURL, filename string) (bool, error) { + if !strings.HasPrefix(versionPURL, "pkg:golang/") { + return false, nil + } + parsed, err := purl.Parse(versionPURL) + if err != nil || parsed.FullName() == strings.ToLower(parsed.FullName()) { + return false, nil + } + name := parsed.FullName() + _, legacyVersion, err := packagePURLStrings("golang", strings.ToLower(name), parsed.Version) + if err != nil { + return false, err + } + record, err := p.DB.GetArtifact(legacyVersion, filename) + if err != nil { + return false, fmt.Errorf("reading legacy Go artifact: %w", err) + } + if record == nil || !record.StoragePath.Valid || record.Source != database.SourceUpstream { + return false, nil + } + escaped, err := gomodule.EscapePath(name) + if err != nil { + return false, nil + } + upstream, err := url.Parse(record.UpstreamURL) + if err != nil || !strings.HasSuffix(upstream.Path, "/"+escaped+"/@v/"+parsed.Version+".zip") { + return false, nil + } + return p.DB.RekeyCachedArtifact(record, &database.Package{PURL: pkgPURL, Ecosystem: "golang", Name: name}, + &database.Version{PURL: versionPURL, PackagePURL: pkgPURL}) +} + +// discardOtherModulesZip drops a cached zip that another module stored +// under filename. Before module paths kept their case, a module with +// uppercase letters was cached under the plain filename of its lowercase +// twin, and whichever came first was served for both. The upstream URL a +// zip was fetched from names its module in escaped form, so a record whose +// URL names a different module is discarded and fetched again. Only the +// module path is compared, so pointing upstream.go elsewhere keeps the cache. +func (h *GoHandler) discardOtherModulesZip(module, escapedModule, version, filename string) { + _, versionPURL, err := packagePURLStrings("golang", module, version) + if err != nil { + return + } + record, err := h.proxy.DB.GetArtifact(versionPURL, filename) + if err != nil || record == nil || !record.StoragePath.Valid || record.Source == database.SourceLocal { + return + } + // Only a URL that names another Go module proves the zip is someone + // else's; a record of unknown origin is kept. + if !strings.Contains(record.UpstreamURL, "/@v/") || + strings.HasSuffix(record.UpstreamURL, "/"+escapedModule+"/@v/"+version+".zip") { + return + } + h.proxy.Logger.Warn("cached zip belongs to a module that differs only in case, discarding", + "module", module, "version", version, "cached_from", record.UpstreamURL) + if err := h.proxy.DB.DiscardArtifact(versionPURL, filename, record.StoragePath.String); err != nil { + h.proxy.Logger.Warn("failed to discard cached zip", "module", module, "version", version, "error", err) + } +} + // proxyCached forwards a request with metadata caching. func (h *GoHandler) proxyCached(w http.ResponseWriter, r *http.Request, cacheKey string) { h.proxy.ProxyCached(w, r, h.upstreamURL+r.URL.Path, "golang", cacheKey, "*/*") } +// proxyVersionFile serves a version's .info or .mod. For a canonical version +// it never changes, so it is served from the cache without revalidation. +func (h *GoHandler) proxyVersionFile(w http.ResponseWriter, r *http.Request, cacheKey, escapedVersion string) { + if goVersionImmutable(escapedVersion) { + h.proxy.proxyImmutable(w, r, h.upstreamURL+r.URL.Path, "golang", cacheKey, "*/*") + return + } + h.proxyCached(w, r, cacheKey) +} + +// goVersionImmutable reports whether escapedVersion, as it appears in a +// proxy URL, names a canonical version, whose .info and .mod the module +// proxy protocol and the checksum database fix for good. This includes +// pseudo-versions, which name a commit by its hash, and +incompatible +// versions. Anything else, such as a branch name or v1.2 for v1.2.0, is a +// query that can resolve to another version later and stays on the TTL. +// The .zip of a canonical version is cached for good already, and a .mod +// that changed upstream would no longer match it. +func goVersionImmutable(escapedVersion string) bool { + version, err := gomodule.UnescapeVersion(escapedVersion) + return err == nil && version != "" && gomodule.CanonicalVersion(version) == version +} + // decodeGoModule decodes an encoded module path. // In the encoding, uppercase letters are represented as "!" followed by lowercase. func decodeGoModule(encoded string) string { diff --git a/internal/handler/go_case_test.go b/internal/handler/go_case_test.go new file mode 100644 index 0000000..91bac44 --- /dev/null +++ b/internal/handler/go_case_test.go @@ -0,0 +1,204 @@ +package handler + +import ( + "context" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync/atomic" + "testing" + + "github.com/git-pkgs/proxy/internal/database" + "github.com/git-pkgs/registries/fetch" +) + +const ( + upperLogrusPath = "/github.com/!sirupsen/logrus/@v/v1.0.6.zip" + lowerLogrusPath = "/github.com/sirupsen/logrus/@v/v1.0.6.zip" +) + +func TestGoZipFilenameKeepsCase(t *testing.T) { + lower := goZipFilename("github.com/sirupsen/logrus", "v1.0.6") + if lower != "logrus@v1.0.6.zip" { + t.Errorf("lowercase module filename = %q, want the plain name", lower) + } + upper := goZipFilename("github.com/Sirupsen/logrus", "v1.0.6") + if upper == lower || !strings.HasPrefix(upper, "logrus@v1.0.6~") || !strings.HasSuffix(upper, ".zip") { + t.Errorf("uppercase module filename = %q, want logrus@v1.0.6~{hash}.zip", upper) + } + if other := goZipFilename("github.com/SIRUPSEN/logrus", "v1.0.6"); other == upper { + t.Errorf("differently cased modules share filename %q", other) + } +} + +// goCaseUpstream serves different bytes for each module path and counts +// requests per path. +func goCaseUpstream(t *testing.T) (*httptest.Server, map[string]*atomic.Int32) { + t.Helper() + counts := map[string]*atomic.Int32{upperLogrusPath: {}, lowerLogrusPath: {}} + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + count, ok := counts[r.URL.Path] + if !ok { + http.NotFound(w, r) + return + } + count.Add(1) + _, _ = io.WriteString(w, "zip of "+r.URL.Path) + })) + t.Cleanup(srv.Close) + return srv, counts +} + +func newGoCaseHandler(t *testing.T, upstream *httptest.Server) (http.Handler, *Proxy) { + t.Helper() + proxy, _, store, _ := setupTestProxy(t) + store.seekable = true + proxy.HTTPClient = upstream.Client() + fetcher := fetch.NewFetcher(fetch.WithHTTPClient(upstream.Client()), fetch.WithMaxRetries(0)) + proxy.Fetcher = fetcher + t.Cleanup(func() { _ = fetcher.Close() }) + return NewGoHandlerWithUpstream(proxy, "http://localhost", upstream.URL).Routes(), proxy +} + +func getGo(h http.Handler, path string) *httptest.ResponseRecorder { + w := httptest.NewRecorder() + h.ServeHTTP(w, httptest.NewRequest(http.MethodGet, path, nil)) + return w +} + +func TestGoModulesDifferingInCaseAreCachedApart(t *testing.T) { + upstream, counts := goCaseUpstream(t) + h, _ := newGoCaseHandler(t, upstream) + + for range 2 { + for _, path := range []string{upperLogrusPath, lowerLogrusPath} { + if w := getGo(h, path); w.Code != http.StatusOK || w.Body.String() != "zip of "+path { + t.Fatalf("GET %s: status = %d, body = %q", path, w.Code, w.Body) + } + } + } + for path, count := range counts { + if n := count.Load(); n != 1 { + t.Errorf("%s fetched %d times, want once and then cached", path, n) + } + } +} + +// Before module paths kept their case, the uppercase module was cached under +// the lowercase module's plain filename. The lowercase module must not be +// served those bytes. +func TestGoZipCachedForAnotherModuleIsRefetched(t *testing.T) { + upstream, counts := goCaseUpstream(t) + h, proxy := newGoCaseHandler(t, upstream) + seedGoZip(t, proxy, "https://proxy.golang.org"+upperLogrusPath, "zip of "+upperLogrusPath) + + if w := getGo(h, lowerLogrusPath); w.Code != http.StatusOK || w.Body.String() != "zip of "+lowerLogrusPath { + t.Fatalf("status = %d, body = %q, want the lowercase module's zip", w.Code, w.Body) + } + if n := counts[lowerLogrusPath].Load(); n != 1 { + t.Errorf("lowercase module fetched %d times, want 1", n) + } +} + +// A zip cached from another upstream host for the same module stays valid: +// only the module path decides whether a cached zip belongs to the request. +func TestGoZipFromAnotherUpstreamHostIsKept(t *testing.T) { + upstream, counts := goCaseUpstream(t) + h, proxy := newGoCaseHandler(t, upstream) + seedGoZip(t, proxy, "https://old-proxy.example"+lowerLogrusPath, "zip of "+lowerLogrusPath) + + if w := getGo(h, lowerLogrusPath); w.Code != http.StatusOK || w.Body.String() != "zip of "+lowerLogrusPath { + t.Fatalf("status = %d, body = %q", w.Code, w.Body) + } + if n := counts[lowerLogrusPath].Load(); n != 0 { + t.Errorf("zip fetched %d times, want it served from the cache", n) + } +} + +func TestGoLegacyCacheKeepsCaseDistinctModules(t *testing.T) { + upstream, counts := goCaseUpstream(t) + h, proxy := newGoCaseHandler(t, upstream) + seedGoZip(t, proxy, upstream.URL+lowerLogrusPath, "zip of "+lowerLogrusPath) + old := seedLegacyUpperGoZip(t, proxy, "https://old-proxy.example"+upperLogrusPath, "zip of "+upperLogrusPath) + upstream.Close() + + for range 2 { + for _, path := range []string{upperLogrusPath, lowerLogrusPath} { + if w := getGo(h, path); w.Code != http.StatusOK || w.Body.String() != "zip of "+path { + t.Fatalf("GET %s: status = %d, body = %q", path, w.Code, w.Body) + } + } + } + current, err := proxy.DB.GetArtifact("pkg:golang/github.com/Sirupsen/logrus@v1.0.6", old.Filename) + if err != nil || current == nil { + t.Fatalf("moved artifact = %+v, %v", current, err) + } + if current.ID != old.ID || current.StoragePath != old.StoragePath || current.FetchedAt != old.FetchedAt || current.HitCount != old.HitCount+2 { + t.Errorf("artifact history changed: before=%+v, after=%+v", old, current) + } + legacy, err := proxy.DB.GetArtifact(old.VersionPURL, old.Filename) + if err != nil || legacy != nil { + t.Fatalf("legacy artifact = %+v, %v", legacy, err) + } + for path, count := range counts { + if count.Load() != 0 { + t.Errorf("unexpected upstream request: %s", path) + } + } +} + +func TestGoLegacyCacheRequiresExactModuleOrigin(t *testing.T) { + for _, origin := range []string{"", "https://proxy.example" + lowerLogrusPath} { + t.Run(origin, func(t *testing.T) { + upstream, counts := goCaseUpstream(t) + h, proxy := newGoCaseHandler(t, upstream) + seedLegacyUpperGoZip(t, proxy, origin, "another module") + if w := getGo(h, upperLogrusPath); w.Code != http.StatusOK || w.Body.String() != "zip of "+upperLogrusPath { + t.Fatalf("status = %d, body = %q", w.Code, w.Body) + } + if counts[upperLogrusPath].Load() != 1 { + t.Fatal("archive with unproven identity was reused") + } + }) + } +} + +func seedLegacyUpperGoZip(t *testing.T, proxy *Proxy, upstreamURL, content string) *database.Artifact { + t.Helper() + const packagePURL = "pkg:golang/github.com/sirupsen/logrus" + const versionPURL = packagePURL + "@v1.0.6" + const storagePath = "golang/logrus/v1.0.6/legacy/upper.zip" + filename := goZipFilename("github.com/Sirupsen/logrus", "v1.0.6") + if _, _, err := proxy.Storage.Store(context.Background(), storagePath, strings.NewReader(content)); err != nil { + t.Fatal(err) + } + artifact := testArtifact(content, versionPURL, filename, "application/zip") + if err := proxy.updateCacheDB("golang", "github.com/Sirupsen/logrus", packagePURL, upstreamURL, storagePath, artifact, ""); err != nil { + t.Fatal(err) + } + old, err := proxy.DB.GetArtifact(versionPURL, filename) + if err != nil || old == nil { + t.Fatalf("seeded artifact = %+v, %v", old, err) + } + return old +} + +// seedGoZip caches content as github.com/sirupsen/logrus v1.0.6 under the +// plain filename, recorded as fetched from upstreamURL. +func seedGoZip(t *testing.T, proxy *Proxy, upstreamURL, content string) { + t.Helper() + const storagePath = "golang/logrus/v1.0.6/seed/logrus@v1.0.6.zip" + store := proxy.Storage.(*mockStorage) + if _, _, err := store.Store(context.Background(), storagePath, strings.NewReader(content)); err != nil { + t.Fatalf("seeding storage: %v", err) + } + pkgPURL, versionPURL, err := packagePURLStrings("golang", "github.com/sirupsen/logrus", "v1.0.6") + if err != nil { + t.Fatalf("packagePURLStrings: %v", err) + } + artifact := testArtifact(content, versionPURL, "logrus@v1.0.6.zip", "application/zip") + if err := proxy.updateCacheDB("golang", "github.com/sirupsen/logrus", pkgPURL, upstreamURL, storagePath, artifact, ""); err != nil { + t.Fatalf("seeding cache record: %v", err) + } +} diff --git a/internal/handler/go_cooldown.go b/internal/handler/go_cooldown.go new file mode 100644 index 0000000..efcc1e1 --- /dev/null +++ b/internal/handler/go_cooldown.go @@ -0,0 +1,289 @@ +package handler + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "net/http" + "strings" + "time" + + gomodule "golang.org/x/mod/module" + "golang.org/x/mod/semver" + "golang.org/x/sync/errgroup" +) + +// Go cooldown measures a version by the Time in its .info, which the module +// proxy takes from the commit the version points at. That is when the code +// was committed, not when the version was tagged or first fetched. +// +// Versions in cooldown are left out of @v/list and @latest, and their .info, +// .mod and .zip are answered with 403. The go command falls back to the next +// GOPROXY entry on 404 and 410, so with GOPROXY=proxy,direct a 404 would let +// it fetch the version directly. + +// goInfoFetchLimit bounds the .info requests made at once to filter a list. +const goInfoFetchLimit = 8 + +const errGoCooldown = "version is in cooldown" + +// goInfo is the JSON served for a version's .info and for @latest. +type goInfo struct { + Version string `json:"Version"` + Time time.Time `json:"Time"` +} + +func (h *GoHandler) cooldownEnabled() bool { + return h.proxy.Cooldown != nil && h.proxy.Cooldown.Enabled() +} + +func (h *GoHandler) allowedAt(module string, published time.Time) bool { + if published.IsZero() { + return true + } + return h.proxy.cooldown().IsAllowed("golang", canonicalPackagePURL("golang", module), published) +} + +// writeGoMetadataError answers a failed upstream metadata fetch. +func (h *GoHandler) writeGoMetadataError(w http.ResponseWriter, err error) { + if errors.Is(err, ErrUpstreamNotFound) { + http.Error(w, "not found", http.StatusNotFound) + return + } + if writeUpstreamHeld(w, err) { + return + } + h.proxy.Logger.Error("go metadata fetch failed", "error", err) + http.Error(w, "failed to fetch from upstream", http.StatusBadGateway) +} + +// fetchGoMetadata reads a module's @v/list, @latest, or a version's .info. +// The .info of a canonical version comes from the cache whatever its age, +// like proxyVersionFile serves it. +func (h *GoHandler) fetchGoMetadata(ctx context.Context, escapedModule, module, rest string) ([]byte, error) { + cacheKey, upstreamURL := module+"/"+rest, h.upstreamURL+"/"+escapedModule+"/"+rest + if v, ok := strings.CutPrefix(rest, "@v/"); ok && strings.HasSuffix(v, ".info") && goVersionImmutable(strings.TrimSuffix(v, ".info")) { + res := h.proxy.fetchImmutableMetadata(ctx, "golang", cacheKey, upstreamURL, "*/*") + return res.body, res.err + } + body, _, err := h.proxy.FetchOrCacheMetadata(ctx, "golang", cacheKey, upstreamURL, "*/*") + return body, err +} + +// Keep escaped module paths in publish-time keys for cache compatibility. +// Only canonical versions are stored; branch queries can resolve differently. +func (h *GoHandler) goTimeKey(module, version string) (versionPURL, packagePURL string, ok bool) { + if h.proxy.DB == nil || gomodule.CanonicalVersion(version) != version { + return "", "", false + } + escaped, err := gomodule.EscapePath(module) + if err != nil { + return "", "", false + } + return canonicalVersionPURL("golang", escaped, version), canonicalPackagePURL("golang", escaped), true +} + +// publishTime returns a version's time from the versions table, or from its +// .info, which is then stored. A version upstream doesn't know, or whose +// .info has no time, gets the zero time and is let through, as in the other +// ecosystems. A failed fetch is an error, so a flaky or rate-limited +// upstream can't let a version through. +func (h *GoHandler) publishTime(ctx context.Context, escapedModule, module, version string) (time.Time, error) { + if versionPURL, _, ok := h.goTimeKey(module, version); ok { + if ver, err := h.proxy.DB.GetVersionByPURL(versionPURL); err == nil && ver != nil && ver.PublishedAt.Valid { + return ver.PublishedAt.Time, nil + } + } + + escapedVersion, err := gomodule.EscapeVersion(version) + if err != nil { + return time.Time{}, nil + } + body, err := h.fetchGoMetadata(ctx, escapedModule, module, "@v/"+escapedVersion+".info") + if errors.Is(err, ErrUpstreamNotFound) { + return time.Time{}, nil + } + if err != nil { + return time.Time{}, err + } + var info goInfo + if err := json.Unmarshal(body, &info); err != nil { + return time.Time{}, err + } + if !info.Time.IsZero() { + h.storePublishTime(module, version, info.Time) + } + return info.Time, nil +} + +func (h *GoHandler) storePublishTime(module, version string, published time.Time) { + versionPURL, packagePURL, ok := h.goTimeKey(module, version) + if !ok { + return + } + if err := h.proxy.DB.SetVersionPublishedAt(versionPURL, packagePURL, published); err != nil { + h.proxy.Logger.Warn("cooldown: could not store go publish time", + "module", module, "version", version, "error", err) + } +} + +// checkCooldown answers a request for an exact version in cooldown, or whose +// time couldn't be read, and reports whether it did. +func (h *GoHandler) checkCooldown(w http.ResponseWriter, r *http.Request, escapedModule, module, version string) bool { + if !h.cooldownEnabled() { + return false + } + published, err := h.publishTime(r.Context(), escapedModule, module, version) + if err != nil { + h.proxy.Logger.Warn("cooldown: could not read go version time", + "module", module, "version", version, "error", err) + http.Error(w, "failed to check cooldown", http.StatusBadGateway) + return true + } + if !h.allowedAt(module, published) { + h.refuseCooldown(w, module, version) + return true + } + return false +} + +func (h *GoHandler) refuseCooldown(w http.ResponseWriter, module, version string) { + h.proxy.Logger.Info("cooldown: withholding go module version", "module", module, "version", version) + http.Error(w, errGoCooldown+": "+canonicalVersionPURL("golang", module, version), http.StatusForbidden) +} + +// allowedVersions returns the listed versions of module that are out of +// cooldown, in their upstream order. +func (h *GoHandler) allowedVersions(ctx context.Context, escapedModule, module string) ([]string, error) { + body, err := h.fetchGoMetadata(ctx, escapedModule, module, "@v/list") + if err != nil { + return nil, err + } + var versions []string + for line := range strings.SplitSeq(string(body), "\n") { + if v := strings.TrimSpace(line); v != "" { + versions = append(versions, v) + } + } + + keep := make([]bool, len(versions)) + g, gctx := errgroup.WithContext(ctx) + g.SetLimit(goInfoFetchLimit) + for i, v := range versions { + g.Go(func() error { + published, err := h.publishTime(gctx, escapedModule, module, v) + if err != nil { + return fmt.Errorf("reading time of %s: %w", v, err) + } + keep[i] = h.allowedAt(module, published) + return nil + }) + } + if err := g.Wait(); err != nil { + return nil, err + } + + allowed := versions[:0] + for i, v := range versions { + if keep[i] { + allowed = append(allowed, v) + } else { + h.proxy.Logger.Info("cooldown: filtering go module version", "module", module, "version", v) + } + } + return allowed, nil +} + +// serveCooldownList serves @v/list without versions in cooldown. +func (h *GoHandler) serveCooldownList(w http.ResponseWriter, r *http.Request, escapedModule, module string) { + allowed, err := h.allowedVersions(r.Context(), escapedModule, module) + if err != nil { + h.writeGoMetadataError(w, err) + return + } + w.Header().Set(headerContentType, "text/plain; charset=utf-8") + if len(allowed) > 0 { + _, _ = w.Write([]byte(strings.Join(allowed, "\n") + "\n")) + } +} + +// serveCooldownInfo serves a .info, refusing it when the version it names is +// in cooldown. rest is the request after /@v/: an escaped version or a query +// such as a branch name, followed by .info. +func (h *GoHandler) serveCooldownInfo(w http.ResponseWriter, r *http.Request, escapedModule, module, rest string) { + body, err := h.fetchGoMetadata(r.Context(), escapedModule, module, "@v/"+rest) + if err != nil { + h.writeGoMetadataError(w, err) + return + } + var info goInfo + if err := json.Unmarshal(body, &info); err == nil && info.Version != "" { + if !h.allowedAt(module, info.Time) { + h.refuseCooldown(w, module, info.Version) + return + } + if !info.Time.IsZero() { + h.storePublishTime(module, info.Version, info.Time) + } + } + w.Header().Set(headerContentType, contentTypeJSON) + _, _ = w.Write(body) +} + +// serveCooldownLatest serves @latest. When upstream's answer is in cooldown, +// it serves the newest listed version out of cooldown instead: the highest +// release, or else the highest pre-release, which is how the go command +// picks from a list. +func (h *GoHandler) serveCooldownLatest(w http.ResponseWriter, r *http.Request, escapedModule, module string) { + body, err := h.fetchGoMetadata(r.Context(), escapedModule, module, "@latest") + if err != nil { + h.writeGoMetadataError(w, err) + return + } + var info goInfo + if err := json.Unmarshal(body, &info); err != nil || h.allowedAt(module, info.Time) { + w.Header().Set(headerContentType, contentTypeJSON) + _, _ = w.Write(body) + return + } + + allowed, err := h.allowedVersions(r.Context(), escapedModule, module) + if err != nil { + h.writeGoMetadataError(w, err) + return + } + best := newestGoVersion(allowed) + if best == "" { + h.refuseCooldown(w, module, info.Version) + return + } + escapedVersion, err := gomodule.EscapeVersion(best) + if err != nil { + h.refuseCooldown(w, module, info.Version) + return + } + h.serveCooldownInfo(w, r, escapedModule, module, escapedVersion+".info") +} + +// newestGoVersion returns the highest release in versions, or the highest +// pre-release when there is no release. +func newestGoVersion(versions []string) string { + var release, prerelease string + for _, v := range versions { + if !semver.IsValid(v) { + continue + } + if semver.Prerelease(v) == "" { + if release == "" || semver.Compare(v, release) > 0 { + release = v + } + } else if prerelease == "" || semver.Compare(v, prerelease) > 0 { + prerelease = v + } + } + if release != "" { + return release + } + return prerelease +} diff --git a/internal/handler/go_cooldown_test.go b/internal/handler/go_cooldown_test.go new file mode 100644 index 0000000..bedc334 --- /dev/null +++ b/internal/handler/go_cooldown_test.go @@ -0,0 +1,260 @@ +package handler + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + "time" + + "github.com/git-pkgs/cooldown" +) + +type goCooldownUpstream struct { + server *httptest.Server + mu sync.Mutex + hits map[string]int +} + +func (u *goCooldownUpstream) count(path string) int { + u.mu.Lock() + defer u.mu.Unlock() + return u.hits[path] +} + +// newGoCooldownUpstream serves example.com/mod with an old v1.0.0, a +// recent v1.1.0 and a recent v1.2.0-rc.1, and @latest pointing at v1.1.0. +func newGoCooldownUpstream(t *testing.T, latest string) *goCooldownUpstream { + t.Helper() + now := time.Now() + times := map[string]time.Time{ + "v1.0.0": now.Add(-10 * 24 * time.Hour), + "v1.1.0": now.Add(-time.Hour), + "v1.2.0-rc.1": now.Add(-2 * time.Hour), + } + u := &goCooldownUpstream{hits: map[string]int{}} + u.server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + u.mu.Lock() + u.hits[r.URL.Path]++ + u.mu.Unlock() + rest, ok := strings.CutPrefix(r.URL.Path, "/example.com/mod/") + if !ok { + http.NotFound(w, r) + return + } + writeInfo := func(v string) { + _ = json.NewEncoder(w).Encode(goInfo{Version: v, Time: times[v]}) + } + switch { + case rest == "@v/list": + _, _ = w.Write([]byte("v1.0.0\nv1.1.0\nv1.2.0-rc.1\n")) + case rest == "@latest": + writeInfo(latest) + case rest == "@v/main.info": + writeInfo("v1.1.0") + case strings.HasSuffix(rest, ".info"): + v := strings.TrimSuffix(strings.TrimPrefix(rest, "@v/"), ".info") + if _, ok := times[v]; !ok { + http.NotFound(w, r) + return + } + writeInfo(v) + case strings.HasSuffix(rest, ".mod"): + _, _ = w.Write([]byte("module example.com/mod\n")) + default: + http.NotFound(w, r) + } + })) + t.Cleanup(u.server.Close) + return u +} + +func goCooldownHandler(t *testing.T, u *goCooldownUpstream) (http.Handler, *mockFetcher, *Proxy) { + t.Helper() + proxy, _, _, fetcher := setupTestProxy(t) + proxy.Cooldown = &cooldown.Config{Default: "3d"} + return NewGoHandlerWithUpstream(proxy, "http://localhost:8080", u.server.URL).Routes(), fetcher, proxy +} + +func goGet(h http.Handler, path string) *httptest.ResponseRecorder { + w := httptest.NewRecorder() + h.ServeHTTP(w, httptest.NewRequest(http.MethodGet, path, nil)) + return w +} + +func TestGoCooldownFiltersList(t *testing.T) { + u := newGoCooldownUpstream(t, "v1.1.0") + h, _, _ := goCooldownHandler(t, u) + + w := goGet(h, "/example.com/mod/@v/list") + if w.Code != http.StatusOK { + t.Fatalf("status = %d", w.Code) + } + if got := w.Body.String(); got != "v1.0.0\n" { + t.Fatalf("list = %q, want only v1.0.0", got) + } + + // Publish times are stored, so a second list needs no .info requests. + _ = goGet(h, "/example.com/mod/@v/list") + if n := u.count("/example.com/mod/@v/v1.0.0.info"); n != 1 { + t.Errorf("v1.0.0.info fetched %d times, want 1", n) + } +} + +func TestGoCooldownRefusesVersions(t *testing.T) { + u := newGoCooldownUpstream(t, "v1.1.0") + h, fetcher, _ := goCooldownHandler(t, u) + + for _, p := range []string{ + "/example.com/mod/@v/v1.1.0.info", + "/example.com/mod/@v/v1.1.0.mod", + "/example.com/mod/@v/v1.1.0.zip", + "/example.com/mod/@v/main.info", + } { + w := goGet(h, p) + if w.Code != http.StatusForbidden || !strings.Contains(w.Body.String(), errGoCooldown) { + t.Errorf("%s: status = %d body %q, want 403 cooldown", p, w.Code, w.Body.String()) + } + } + if fetcher.fetchCalled { + t.Error("zip in cooldown was fetched") + } + + for _, p := range []string{"/example.com/mod/@v/v1.0.0.info", "/example.com/mod/@v/v1.0.0.mod"} { + if w := goGet(h, p); w.Code != http.StatusOK { + t.Errorf("%s: status = %d, want 200", p, w.Code) + } + } +} + +func TestGoCooldownLatest(t *testing.T) { + u := newGoCooldownUpstream(t, "v1.1.0") + h, _, _ := goCooldownHandler(t, u) + + w := goGet(h, "/example.com/mod/@latest") + if w.Code != http.StatusOK { + t.Fatalf("status = %d: %s", w.Code, w.Body) + } + var info goInfo + if err := json.Unmarshal(w.Body.Bytes(), &info); err != nil { + t.Fatal(err) + } + if info.Version != "v1.0.0" { + t.Fatalf("@latest = %s, want v1.0.0", info.Version) + } +} + +func TestGoCooldownLatestAllowed(t *testing.T) { + u := newGoCooldownUpstream(t, "v1.0.0") + h, _, _ := goCooldownHandler(t, u) + + w := goGet(h, "/example.com/mod/@latest") + var info goInfo + if err := json.Unmarshal(w.Body.Bytes(), &info); err != nil || info.Version != "v1.0.0" { + t.Fatalf("@latest = %d %s, want v1.0.0", w.Code, w.Body) + } + if n := u.count("/example.com/mod/@v/list"); n != 0 { + t.Errorf("list fetched %d times for an allowed @latest", n) + } +} + +func TestGoCooldownDisabledPassesThrough(t *testing.T) { + u := newGoCooldownUpstream(t, "v1.1.0") + h, _, proxy := goCooldownHandler(t, u) + proxy.Cooldown = nil + + if w := goGet(h, "/example.com/mod/@v/list"); w.Body.String() != "v1.0.0\nv1.1.0\nv1.2.0-rc.1\n" { + t.Fatalf("list = %q", w.Body.String()) + } + if w := goGet(h, "/example.com/mod/@v/v1.1.0.info"); w.Code != http.StatusOK { + t.Fatalf("info status = %d", w.Code) + } +} + +func TestNewestGoVersion(t *testing.T) { + tests := []struct { + versions []string + want string + }{ + {[]string{"v1.0.0", "v1.10.0", "v1.9.0", "v2.0.0-rc.1"}, "v1.10.0"}, + {[]string{"v1.0.0-alpha", "v1.0.0-beta"}, "v1.0.0-beta"}, + {[]string{"v2.0.0+incompatible", "v1.5.0"}, "v2.0.0+incompatible"}, + {nil, ""}, + } + for _, tt := range tests { + if got := newestGoVersion(tt.versions); got != tt.want { + t.Errorf("newestGoVersion(%v) = %q, want %q", tt.versions, got, tt.want) + } + } +} + +func TestGoCooldownFailsClosedOnUpstreamErrors(t *testing.T) { + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch { + case strings.HasSuffix(r.URL.Path, "/@v/list"): + _, _ = w.Write([]byte("v1.0.0\n")) + case strings.HasSuffix(r.URL.Path, ".info"): + http.Error(w, "slow down", http.StatusTooManyRequests) + default: + _, _ = w.Write([]byte("module example.com/mod\n")) + } + })) + defer upstream.Close() + + proxy, _, _, fetcher := setupTestProxy(t) + proxy.Cooldown = &cooldown.Config{Default: "3d"} + h := NewGoHandlerWithUpstream(proxy, "http://localhost:8080", upstream.URL).Routes() + + for _, p := range []string{ + "/example.com/mod/@v/list", + "/example.com/mod/@v/v1.0.0.mod", + "/example.com/mod/@v/v1.0.0.zip", + } { + if w := goGet(h, p); w.Code != http.StatusBadGateway { + t.Errorf("%s: status = %d, want 502", p, w.Code) + } + } + if fetcher.fetchCalled { + t.Error("zip was fetched without a known time") + } +} + +func TestGoCooldownStoresTimesPerExactModule(t *testing.T) { + u := newGoCooldownUpstream(t, "v1.1.0") + proxy, db, _, _ := setupTestProxy(t) + proxy.Cooldown = &cooldown.Config{Default: "3d"} + h := NewGoHandlerWithUpstream(proxy, "http://localhost:8080", u.server.URL).Routes() + + _ = goGet(h, "/example.com/mod/@v/list") + ver, err := db.GetVersionByPURL(canonicalVersionPURL("golang", "example.com/mod", "v1.0.0")) + if err != nil || ver == nil || !ver.PublishedAt.Valid { + t.Fatalf("time of v1.0.0 not stored: %v %v", ver, err) + } + + gh := &GoHandler{proxy: proxy} + upper, _, ok := gh.goTimeKey("github.com/Azure/sdk", "v1.0.0") + lower, _, _ := gh.goTimeKey("github.com/azure/sdk", "v1.0.0") + if !ok || upper == lower { + t.Errorf("modules differing in case share a key: %q %q", upper, lower) + } + for _, query := range []string{"master", "v1.2", "v1.0.0+meta"} { + if _, _, ok := gh.goTimeKey("example.com/mod", query); ok { + t.Errorf("time of non-canonical %q would be stored", query) + } + } +} + +func TestGoRejectsBadlyEscapedVersions(t *testing.T) { + u := newGoCooldownUpstream(t, "v1.1.0") + h, fetcher, _ := goCooldownHandler(t, u) + for _, p := range []string{"/example.com/mod/@v/V1.0.0.zip", "/example.com/mod/@v/V1.0.0.mod"} { + if w := goGet(h, p); w.Code != http.StatusNotFound { + t.Errorf("%s: status = %d, want 404", p, w.Code) + } + } + if fetcher.fetchCalled || u.count("/example.com/mod/@v/V1.0.0.mod") != 0 { + t.Error("badly escaped version reached upstream") + } +} diff --git a/internal/handler/go_policy_test.go b/internal/handler/go_policy_test.go new file mode 100644 index 0000000..0ce981f --- /dev/null +++ b/internal/handler/go_policy_test.go @@ -0,0 +1,47 @@ +package handler + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/git-pkgs/cooldown" + "github.com/git-pkgs/proxy/internal/config" +) + +func TestGoCooldownOverridesIgnoreModuleCase(t *testing.T) { + for _, tc := range []struct { + name, rule, fallback, override string + status int + }{ + {"lowercase restriction", "example.com/module", "0", "7d", http.StatusForbidden}, + {"mixed-case restriction", "example.com/Module", "0", "7d", http.StatusForbidden}, + {"lowercase exemption", "example.com/module", "7d", "0", http.StatusOK}, + {"mixed-case exemption", "example.com/Module", "7d", "0", http.StatusOK}, + } { + t.Run(tc.name, func(t *testing.T) { + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if strings.HasSuffix(r.URL.Path, ".info") { + _ = json.NewEncoder(w).Encode(goInfo{Version: "v1.0.0", Time: time.Now()}) + return + } + _, _ = w.Write([]byte("module zip")) + })) + defer upstream.Close() + h, proxy := newGoCaseHandler(t, upstream) + cfg := config.CooldownConfig{Packages: map[string]string{"pkg:golang/" + tc.rule: tc.override}} + proxy.Cooldown = &cooldown.Config{Default: tc.fallback, Packages: cfg.NormalizedPackages()} + for _, path := range []string{ + "/example.com/!module/@v/v1.0.0.zip", "/example.com/module/@v/v1.0.0.zip", + "/example.com/!module/@v/v1.0.0.info", "/example.com/module/@v/v1.0.0.info", + } { + if response := getGo(h, path); response.Code != tc.status { + t.Errorf("GET %s = %d %s, want %d", path, response.Code, response.Body, tc.status) + } + } + }) + } +} diff --git a/internal/handler/go_sumdb.go b/internal/handler/go_sumdb.go index 7de2513..e96e5ab 100644 --- a/internal/handler/go_sumdb.go +++ b/internal/handler/go_sumdb.go @@ -348,7 +348,7 @@ func (h *GoHandler) serveCachedSumDBTile(w http.ResponseWriter, r *http.Request, if check != nil && check(body) != nil { return false, true } - metrics.RecordCacheHit(goEcosystem) + metrics.RecordMetadataCacheHit(goEcosystem, len(body)) if entry.ETag.Valid { w.Header().Set(headerETag, entry.ETag.String) @@ -383,7 +383,9 @@ func (h *GoHandler) proxySumDB(w http.ResponseWriter, r *http.Request, name, ups // the upstream timeout before the fetch falls back to it. if h.sumDBOffline && h.sumDBProbes.recentlyFailed(name) { if entry, body, contentType, ok := h.readCachedSumDB(r.Context(), cacheKey, check); ok { - p.writeMetadataCachedResponseWithEncoding(w, r, goEcosystem, cacheKey, body, contentType, entry.ContentEncoding.String) + cm := p.cachedMetaFor(entry) + cm.stale = true // upstream was not asked + writeMetadataBody(w, r, cm, body, contentType, entry.ContentEncoding.String) return } } @@ -416,7 +418,7 @@ func (h *GoHandler) proxySumDB(w http.ResponseWriter, r *http.Request, name, ups return } - p.writeMetadataCachedResponseWithEncoding(w, r, goEcosystem, cacheKey, res.body, res.contentType, res.contentEncoding) + writeMetadataResult(w, r, res) } // fetchSumDB fetches a checksum database response through the metadata diff --git a/internal/handler/go_sumdb_test.go b/internal/handler/go_sumdb_test.go index 6a0c47b..d47e432 100644 --- a/internal/handler/go_sumdb_test.go +++ b/internal/handler/go_sumdb_test.go @@ -985,3 +985,26 @@ func TestGoSumDB_ClientRoundTrip(t *testing.T) { t.Fatalf("lookup from the proxy cache with the database down: %v", err) } } + +// TestGoSumDB_OfflineCopyMarkedStaleWithoutTTL: with metadata_ttl 0 the +// cached copy offline mode serves while the database is unreachable still +// carries the Warning header. +func TestGoSumDB_OfflineCopyMarkedStaleWithoutTTL(t *testing.T) { + const lookup = "/lookup/golang.org/x/text@v0.14.0" + db := newFakeSumDB(t, map[string]string{lookup: testSumDBRecord}) + h := newSumDBTestHandler(t, db.server.URL, true, 0) + h.sumDBOffline = true + + if w := serveGoRequest(h, "/sumdb/sum.example"+lookup); w.Code != http.StatusOK { + t.Fatalf("online: status = %d, want 200", w.Code) + } + db.down.Store(true) + serveGoRequest(h, "/sumdb/sum.example"+lookup) + if !h.sumDBProbes.recentlyFailed(testSumDBName) { + t.Fatal("the failure was not remembered") + } + w := serveGoRequest(h, "/sumdb/sum.example"+lookup) + if w.Code != http.StatusOK || w.Header().Get("Warning") != staleWarning { + t.Errorf("offline copy = %d Warning %q, want 200 %q", w.Code, w.Header().Get("Warning"), staleWarning) + } +} diff --git a/internal/handler/go_vulndb.go b/internal/handler/go_vulndb.go new file mode 100644 index 0000000..4cd2970 --- /dev/null +++ b/internal/handler/go_vulndb.go @@ -0,0 +1,128 @@ +package handler + +import ( + "bytes" + "compress/gzip" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "strings" +) + +const ( + // defaultGoVulnDBURL is the database govulncheck uses without -db. + defaultGoVulnDBURL = "https://vuln.go.dev" + + // goVulnDBMaxIDLength bounds an entry ID in a request path. Go IDs look + // like GO-2024-1234; other OSV databases use longer ones such as + // GHSA-xxxx-xxxx-xxxx. + goVulnDBMaxIDLength = 128 + + // goVulnDBMaxJSONSize bounds a decompressed .json.gz response while it is + // checked. index/modules.json, the largest file, is a few MB. + goVulnDBMaxJSONSize = 256 << 20 +) + +// SetVulnDB sets the Go vulnerability database served at /vulndb/. An empty +// URL keeps the default, vuln.go.dev. +func (h *GoHandler) SetVulnDB(vulnDBURL string) { + h.vulnDBURL = configuredUpstreamURL(vulnDBURL, defaultGoVulnDBURL) +} + +// handleVulnDB serves the Go vulnerability database at +// /vulndb/{path}. Only the files the database API defines are passed on: +// index/db.json, index/modules.json, index/vulns.json and ID/{id}.json, each +// also as .json.gz, which is what govulncheck fetches. Every file can change, +// so all of them follow the metadata TTL and fall back to the cached copy +// when the database cannot be reached. The bytes are stored and served +// unchanged: a .json.gz file is gzip data, not a gzip-encoded response. +func (h *GoHandler) handleVulnDB(w http.ResponseWriter, r *http.Request, path string) { + if !validGoVulnDBPath(path) { + http.NotFound(w, r) + return + } + upstreamURL := h.vulnDBURL + "/" + path + p := h.proxy + if !p.CacheMetadata { + p.proxyMetadataStream(w, r, upstreamURL, "identity", "*/*") + return + } + cacheKey := goVulnDBCacheKey(h.vulnDBURL, path) + res := p.lookupMetadata(r.Context(), goEcosystem, cacheKey, upstreamURL, "*/*", "identity", goVulnDBResponseCheck(path)) + if res.err != nil { + p.writeMetadataFetchError(w, res.err) + return + } + writeMetadataResult(w, r, res) +} + +// validGoVulnDBPath reports whether path is a file the vulnerability +// database API defines. Entry IDs are limited to letters, digits, '-' and +// '_', which keeps '.', '/', '%' and the like out of the upstream URL. +func validGoVulnDBPath(path string) bool { + name, ok := strings.CutSuffix(path, ".json.gz") + if !ok { + name, ok = strings.CutSuffix(path, ".json") + } + if !ok { + return false + } + switch name { + case "index/db", "index/modules", "index/vulns": + return true + } + id, ok := strings.CutPrefix(name, "ID/") + if !ok || id == "" || len(id) > goVulnDBMaxIDLength { + return false + } + for _, c := range id { + if !isASCIILetterOrDigit(c) && c != '-' && c != '_' { + return false + } + } + return true +} + +func isASCIILetterOrDigit(c rune) bool { + return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') +} + +// goVulnDBResponseCheck returns a check that a response to path is JSON, +// after decompressing it for a .json.gz path. A 200 that is something else +// (an egress proxy's block page, a cut-off download) is refused rather than +// cached, where it would also replace the copy kept for an outage. +func goVulnDBResponseCheck(path string) func([]byte) error { + compressed := strings.HasSuffix(path, ".gz") + return func(body []byte) error { + data := body + if compressed { + zr, err := gzip.NewReader(bytes.NewReader(body)) + if err != nil { + return fmt.Errorf("vulnerability database file %s is not gzip data: %w", path, err) + } + data, err = io.ReadAll(io.LimitReader(zr, goVulnDBMaxJSONSize+1)) + if err == nil && len(data) > goVulnDBMaxJSONSize { + err = errors.New("too large") + } + if err != nil { + return fmt.Errorf("vulnerability database file %s does not decompress: %w", path, err) + } + } + if !json.Valid(data) { + return fmt.Errorf("vulnerability database file %s is not JSON", path) + } + return nil + } +} + +// goVulnDBCacheKey hashes the database URL and the request path, as +// goSumDBCacheKey does, so repointing upstream.go_vulndb does not serve the +// old database's entries. +func goVulnDBCacheKey(vulnDBURL, path string) string { + digest := sha256.Sum256([]byte(vulnDBURL + "\x00" + path)) + return "vulndb/" + hex.EncodeToString(digest[:]) +} diff --git a/internal/handler/go_vulndb_test.go b/internal/handler/go_vulndb_test.go new file mode 100644 index 0000000..162ff9a --- /dev/null +++ b/internal/handler/go_vulndb_test.go @@ -0,0 +1,225 @@ +package handler + +import ( + "bytes" + "compress/gzip" + "io" + "net/http" + "net/http/httptest" + "testing" + "time" +) + +const ( + testVulnDBDB = `{"modified":"2026-10-21T00:27:29Z"}` + testVulnDBModules = `[{"path":"golang.org/x/text","vulns":[{"id":"GO-2021-0113","modified":"2026-10-21T00:27:29Z","fixed":"0.3.7"}]}]` + testVulnDBEntry = `{"schema_version":"1.3.1","id":"GO-2021-0113","modified":"2026-10-21T00:27:29Z"}` +) + +func gzipString(t *testing.T, s string) string { + t.Helper() + var buf bytes.Buffer + zw := gzip.NewWriter(&buf) + if _, err := io.WriteString(zw, s); err != nil { + t.Fatal(err) + } + if err := zw.Close(); err != nil { + t.Fatal(err) + } + return buf.String() +} + +// testVulnDBFiles is a small vulnerability database laid out as vuln.go.dev +// serves it: every file as .json and .json.gz, the latter as gzip data with a +// JSON content type and no Content-Encoding. +func testVulnDBFiles(t *testing.T) map[string]string { + t.Helper() + files := map[string]string{ + "/index/db.json": testVulnDBDB, + "/index/modules.json": testVulnDBModules, + "/index/vulns.json": `[{"id":"GO-2021-0113","modified":"2026-10-21T00:27:29Z"}]`, + "/ID/GO-2021-0113.json": testVulnDBEntry, + "/ID/GHSA-ppp9-7jff-5vj2.json": testVulnDBEntry, + } + all := make(map[string]string, 2*len(files)) + for path, body := range files { + all[path] = body + all[path+".gz"] = gzipString(t, body) + } + return all +} + +func newVulnDBTestHandler(t *testing.T, vulnDBURL string, cacheMetadata bool, ttl time.Duration) *GoHandler { + t.Helper() + proxy, _, _, _ := setupTestProxy(t) + proxy.HTTPClient = http.DefaultClient + proxy.CacheMetadata = cacheMetadata + proxy.MetadataTTL = ttl + h := NewGoHandler(proxy, "http://proxy.example") + h.SetVulnDB(vulnDBURL) + return h +} + +func TestGoVulnDB_DefaultsToVulnGoDev(t *testing.T) { + h := NewGoHandler(nil, "http://proxy.example") + if h.vulnDBURL != defaultGoVulnDBURL { + t.Errorf("vulnDBURL = %q, want %q", h.vulnDBURL, defaultGoVulnDBURL) + } + h.SetVulnDB("") + if h.vulnDBURL != defaultGoVulnDBURL { + t.Errorf("after SetVulnDB(\"\"): vulnDBURL = %q, want %q", h.vulnDBURL, defaultGoVulnDBURL) + } + h.SetVulnDB("https://vulndb.example/") + if h.vulnDBURL != "https://vulndb.example" { + t.Errorf("vulnDBURL = %q, want the trailing slash trimmed", h.vulnDBURL) + } +} + +func TestGoVulnDB_ServesFilesUnchanged(t *testing.T) { + files := testVulnDBFiles(t) + for _, cacheMetadata := range []bool{true, false} { + db := newFakeSumDB(t, files) + h := newVulnDBTestHandler(t, db.server.URL, cacheMetadata, time.Hour) + for path, want := range files { + w := serveGoRequest(h, "/vulndb"+path) + if w.Code != http.StatusOK || w.Body.String() != want { + t.Errorf("cache_metadata=%v %s: status = %d, body = %q, want 200 with the upstream bytes", cacheMetadata, path, w.Code, w.Body.String()) + } + if enc := w.Header().Get(headerContentEncoding); enc != "" { + t.Errorf("cache_metadata=%v %s: Content-Encoding = %q, want none", cacheMetadata, path, enc) + } + } + } +} + +func TestGoVulnDB_HeadForSchemaCheck(t *testing.T) { + db := newFakeSumDB(t, testVulnDBFiles(t)) + h := newVulnDBTestHandler(t, db.server.URL, true, time.Hour) + + w := httptest.NewRecorder() + h.Routes().ServeHTTP(w, httptest.NewRequest(http.MethodHead, "/vulndb/index/modules.json.gz", nil)) + if w.Code != http.StatusOK { + t.Errorf("HEAD index/modules.json.gz: status = %d, want 200", w.Code) + } + + w = httptest.NewRecorder() + h.Routes().ServeHTTP(w, httptest.NewRequest(http.MethodHead, "/golang.org/x/text/@v/list", nil)) + if w.Code != http.StatusMethodNotAllowed { + t.Errorf("HEAD on a module path: status = %d, want 405", w.Code) + } +} + +func TestGoVulnDB_CachedWithinTTL(t *testing.T) { + db := newFakeSumDB(t, testVulnDBFiles(t)) + h := newVulnDBTestHandler(t, db.server.URL, true, time.Hour) + + for range 3 { + if w := serveGoRequest(h, "/vulndb/index/modules.json.gz"); w.Code != http.StatusOK { + t.Fatalf("status = %d, want 200", w.Code) + } + } + if n := db.requests("/index/modules.json.gz"); n != 1 { + t.Errorf("upstream requests = %d, want 1", n) + } +} + +func TestGoVulnDB_RefreshedAfterTTL(t *testing.T) { + db := newFakeSumDB(t, testVulnDBFiles(t)) + h := newVulnDBTestHandler(t, db.server.URL, true, time.Nanosecond) + + serveGoRequest(h, "/vulndb/ID/GO-2021-0113.json") + updated := `{"id":"GO-2021-0113","modified":"2026-10-27T00:00:00Z"}` + db.setFile("/ID/GO-2021-0113.json", updated) + if w := serveGoRequest(h, "/vulndb/ID/GO-2021-0113.json"); w.Body.String() != updated { + t.Errorf("body = %q, want the modified entry %q", w.Body.String(), updated) + } +} + +func TestGoVulnDB_StaleFallbackWhenUnreachable(t *testing.T) { + files := testVulnDBFiles(t) + db := newFakeSumDB(t, files) + h := newVulnDBTestHandler(t, db.server.URL, true, time.Nanosecond) + + for path := range files { + if w := serveGoRequest(h, "/vulndb"+path); w.Code != http.StatusOK { + t.Fatalf("%s online: status = %d, want 200", path, w.Code) + } + } + + db.down.Store(true) + for path, want := range files { + w := serveGoRequest(h, "/vulndb"+path) + if w.Code != http.StatusOK || w.Body.String() != want { + t.Errorf("%s offline: status = %d, body = %q, want 200 with the cached copy", path, w.Code, w.Body.String()) + } + if w.Header().Get("Warning") == "" { + t.Errorf("%s offline: no Warning header, want the response marked stale", path) + } + } + if w := serveGoRequest(h, "/vulndb/ID/GO-2099-0001.json.gz"); w.Code != http.StatusBadGateway { + t.Errorf("uncached entry offline: status = %d, want 502", w.Code) + } +} + +func TestGoVulnDB_RefusesNonJSON(t *testing.T) { + const blockPage = "blocked by policy" + db := newFakeSumDB(t, map[string]string{ + "/index/db.json": blockPage, + "/index/db.json.gz": blockPage, + "/index/modules.json.gz": gzipString(t, blockPage), + "/ID/GO-2021-0113.json.gz": gzipString(t, testVulnDBEntry)[:20], + }) + h := newVulnDBTestHandler(t, db.server.URL, true, time.Hour) + + for _, path := range []string{"/index/db.json", "/index/db.json.gz", "/index/modules.json.gz", "/ID/GO-2021-0113.json.gz"} { + if w := serveGoRequest(h, "/vulndb"+path); w.Code != http.StatusBadGateway { + t.Errorf("%s: status = %d, want 502", path, w.Code) + } + } + + // Nothing bad was cached: once upstream serves the real file, it is used. + db.setFile("/index/db.json", testVulnDBDB) + if w := serveGoRequest(h, "/vulndb/index/db.json"); w.Code != http.StatusOK || w.Body.String() != testVulnDBDB { + t.Errorf("after fix: status = %d, body = %q, want 200 with %q", w.Code, w.Body.String(), testVulnDBDB) + } +} + +func TestGoVulnDB_NotFound(t *testing.T) { + db := newFakeSumDB(t, nil) + h := newVulnDBTestHandler(t, db.server.URL, true, time.Hour) + if w := serveGoRequest(h, "/vulndb/ID/GO-2099-0001.json.gz"); w.Code != http.StatusNotFound { + t.Errorf("status = %d, want 404", w.Code) + } +} + +func TestGoVulnDB_InvalidPathsNeverReachUpstream(t *testing.T) { + db := newFakeSumDB(t, nil) + h := newVulnDBTestHandler(t, db.server.URL, true, time.Hour) + + for _, target := range []string{ + "/vulndb", + "/vulndb/", + "/vulndb/index", + "/vulndb/index/db", + "/vulndb/index/db.json.zip", + "/vulndb/index/other.json", + "/vulndb/vulndb.zip", + "/vulndb/ID/", + "/vulndb/ID/.json", + "/vulndb/ID/GO-2021-0113", + "/vulndb/ID/GO-2021-0113.txt", + "/vulndb/ID/../index/db.json", + "/vulndb/ID/..%2Findex%2Fdb.json", + "/vulndb/ID/GO.2021.json", + "/vulndb/ID/a/b.json", + "/vulndb/ID/GO%3F.json", + "/vulndb/ID/" + string(bytes.Repeat([]byte("A"), goVulnDBMaxIDLength+1)) + ".json", + } { + if w := serveGoRequest(h, target); w.Code != http.StatusNotFound { + t.Errorf("%s: status = %d, want 404", target, w.Code) + } + } + if n := db.totalRequests(); n != 0 { + t.Errorf("upstream requests = %d, want 0", n) + } +} diff --git a/internal/handler/gradle.go b/internal/handler/gradle.go index e251209..cd3e78a 100644 --- a/internal/handler/gradle.go +++ b/internal/handler/gradle.go @@ -106,11 +106,11 @@ func (h *GradleBuildCacheHandler) handleGetOrHead(w http.ResponseWriter, r *http return } if !exists { - metrics.RecordCacheMiss("gradle") + metrics.RecordArtifactCacheMiss("gradle") http.NotFound(w, r) return } - metrics.RecordCacheHit("gradle") + metrics.RecordArtifactCacheHit("gradle") sizeStart := time.Now() size, err := h.proxy.Storage.Size(r.Context(), storagePath) @@ -130,7 +130,7 @@ func (h *GradleBuildCacheHandler) handleGetOrHead(w http.ResponseWriter, r *http metrics.RecordStorageOperation("read", time.Since(readStart)) if err != nil { if errors.Is(err, storage.ErrNotFound) { - metrics.RecordCacheMiss("gradle") + metrics.RecordArtifactCacheMiss("gradle") http.NotFound(w, r) return } @@ -140,7 +140,7 @@ func (h *GradleBuildCacheHandler) handleGetOrHead(w http.ResponseWriter, r *http return } defer func() { _ = reader.Close() }() - metrics.RecordCacheHit("gradle") + metrics.RecordArtifactCacheHit("gradle") w.WriteHeader(http.StatusOK) _, _ = io.Copy(w, reader) diff --git a/internal/handler/gradle_test.go b/internal/handler/gradle_test.go index a05d07e..a4b95c2 100644 --- a/internal/handler/gradle_test.go +++ b/internal/handler/gradle_test.go @@ -237,8 +237,8 @@ func TestGradleBuildCacheHandler_RecordsMetrics(t *testing.T) { srv := httptest.NewServer(h.Routes()) defer srv.Close() - hitsBefore := testutil.ToFloat64(metrics.CacheHits.WithLabelValues("gradle")) - missesBefore := testutil.ToFloat64(metrics.CacheMisses.WithLabelValues("gradle")) + hitsBefore := testutil.ToFloat64(metrics.CacheHits.WithLabelValues("gradle", metrics.CacheKindArtifact)) + missesBefore := testutil.ToFloat64(metrics.CacheMisses.WithLabelValues("gradle", metrics.CacheKindArtifact)) key := "metrics-key" putReq, err := http.NewRequest(http.MethodPut, srv.URL+"/"+key, strings.NewReader("payload")) @@ -273,8 +273,8 @@ func TestGradleBuildCacheHandler_RecordsMetrics(t *testing.T) { } _ = missResp.Body.Close() - hitsAfter := testutil.ToFloat64(metrics.CacheHits.WithLabelValues("gradle")) - missesAfter := testutil.ToFloat64(metrics.CacheMisses.WithLabelValues("gradle")) + hitsAfter := testutil.ToFloat64(metrics.CacheHits.WithLabelValues("gradle", metrics.CacheKindArtifact)) + missesAfter := testutil.ToFloat64(metrics.CacheMisses.WithLabelValues("gradle", metrics.CacheKindArtifact)) if diff := hitsAfter - hitsBefore; diff != 2 { t.Fatalf("cache hits delta = %.0f, want 2", diff) diff --git a/internal/handler/handler.go b/internal/handler/handler.go index 62d63ae..d9284e2 100644 --- a/internal/handler/handler.go +++ b/internal/handler/handler.go @@ -4,7 +4,9 @@ package handler import ( "bytes" "context" + "crypto/sha256" "database/sql" + "encoding/hex" "errors" "fmt" "io" @@ -14,13 +16,14 @@ import ( "strconv" "strings" "sync" + "sync/atomic" "time" "github.com/git-pkgs/artifacts" "github.com/git-pkgs/cooldown" + "github.com/git-pkgs/integrity" "github.com/git-pkgs/proxy/internal/database" "github.com/git-pkgs/proxy/internal/denylist" - "github.com/git-pkgs/proxy/internal/httpclient" "github.com/git-pkgs/proxy/internal/metrics" "github.com/git-pkgs/proxy/internal/packageurl" "github.com/git-pkgs/proxy/internal/scanner" @@ -43,6 +46,18 @@ func containsPathTraversal(path string) bool { return false } +// rejectQueryChars refuses a decoded path containing '?' or '#', which would cut +// the upstream URL short and cache one file under another's name. +func rejectQueryChars(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if strings.ContainsAny(r.URL.Path, "?#") { + http.Error(w, "invalid path", http.StatusBadRequest) + return + } + next.ServeHTTP(w, r) + }) +} + func hasDotDotSegment(path string) bool { path = strings.ReplaceAll(path, "\\", "/") for segment := range strings.SplitSeq(path, "/") { @@ -129,6 +144,10 @@ func ifNoneMatchHits(header, etag string) bool { // defaultMetadataMaxSize is used when Proxy.MetadataMaxSize is unset. const defaultMetadataMaxSize = 100 << 20 +// defaultMetadataStreamMaxSize is used when Proxy.MetadataStreamMaxSize is +// unset. +const defaultMetadataStreamMaxSize = 1 << 30 + // ErrMetadataTooLarge is returned when upstream metadata exceeds the configured limit. var ErrMetadataTooLarge = errors.New("metadata response exceeds size limit") @@ -136,14 +155,57 @@ var ErrMetadataTooLarge = errors.New("metadata response exceeds size limit") // from unexpectedly large responses. Returns ErrMetadataTooLarge if the response // is truncated by the limit. func (p *Proxy) ReadMetadata(r io.Reader) ([]byte, error) { + return p.ReadMetadataSized(r, -1) +} + +// ReadMetadataSized is ReadMetadata for a body expected to be size bytes +// long, such as a cached document or a response with a Content-Length. +// Reading into a buffer of that size avoids io.ReadAll growing its buffer +// step by step, which peaks at more than twice the document size. size is +// only a hint: a negative one, or one above the limit, reads as ReadMetadata +// does, and a body of a different length is still read correctly. A body +// read through upstreamBodyReader that upstream cuts off fails, even though +// it ends like a body shorter than size. +func (p *Proxy) ReadMetadataSized(r io.Reader, size int64) ([]byte, error) { limit := p.MetadataMaxSize if limit <= 0 { limit = defaultMetadataMaxSize } - data, err := io.ReadAll(io.LimitReader(r, limit+1)) + if size < 0 || size > limit { + return readLimited(r, nil, limit) + } + // One byte more than expected, so a body of exactly size bytes ends in + // the buffer and a longer one is noticed. + buf := make([]byte, size+1) + n, err := io.ReadFull(r, buf) + var cut *upstreamBodyError + switch { + case errors.As(err, &cut): + return nil, err + case errors.Is(err, io.EOF) || errors.Is(err, io.ErrUnexpectedEOF): + if int64(n) < size/2 { + // The hint was far off; don't keep the oversized buffer alive. + return bytes.Clone(buf[:n]), nil + } + return buf[:n], nil + case err != nil: + return nil, err + } + return readLimited(r, buf, limit) +} + +// readLimited appends the rest of r to data, failing with +// ErrMetadataTooLarge once the total exceeds limit. +func readLimited(r io.Reader, data []byte, limit int64) ([]byte, error) { + rest, err := io.ReadAll(io.LimitReader(r, limit+1-int64(len(data)))) if err != nil { return nil, err } + if data == nil { + data = rest + } else { + data = append(data, rest...) + } if int64(len(data)) > limit { return nil, ErrMetadataTooLarge } @@ -152,19 +214,29 @@ func (p *Proxy) ReadMetadata(r io.Reader) ([]byte, error) { // Proxy provides shared functionality for protocol handlers. type Proxy struct { - DB *database.DB - Storage storage.Storage - Fetcher fetch.FetcherInterface - Resolver *fetch.Resolver - Logger *slog.Logger - Cooldown CooldownPolicy - Denylist *denylist.Policy - CacheMetadata bool - MetadataTTL time.Duration - MetadataMaxSize int64 - GradleReadOnly bool - HostedEnabled bool - GradleMaxUploadSize int64 + DB *database.DB + Storage storage.Storage + Fetcher fetch.FetcherInterface + Resolver *fetch.Resolver + // RouteFor returns how to fetch a package that doesn't come from the + // ecosystem's default upstream, such as an npm package in + // upstream.npm_routes, or nil to use Resolver. + RouteFor func(ecosystem, name string) *ArtifactRoute + Logger *slog.Logger + Cooldown CooldownPolicy + // ShortestCooldown is the shortest cooldown configured anywhere. It + // bounds how long a rewrite filtered by cooldown is cached. + ShortestCooldown time.Duration + Denylist *denylist.Policy + CacheMetadata bool + MetadataTTL time.Duration + MetadataMaxSize int64 + // MetadataStreamMaxSize caps a metadata document streamed from upstream + // into storage, which metadata_max_size doesn't cover. Default 1 GB. + MetadataStreamMaxSize int64 + GradleReadOnly bool + HostedEnabled bool + GradleMaxUploadSize int64 // NPMFullMetadata requests full npm packuments from upstream even when // cooldown is disabled, so served metadata carries publish times. NPMFullMetadata bool @@ -178,7 +250,7 @@ type Proxy struct { // RateLimits is the gate under the upstream clients. Artifact fetches // check it before calling Fetcher, so held hosts never reach its breaker. - RateLimits *httpclient.RateLimitGate + RateLimits UpstreamHolds // HostedNPMScopes and HostedComposerVendors name namespaces served from // pushed packages alone, without asking the upstream. @@ -222,10 +294,37 @@ type Proxy struct { // Nil leaves every request to rewrite its own copy. rewrites *rewriteCache + // publishIndexes keeps publish times read out of large metadata + // documents for the download cooldown check; see publishIndex. + publishIndexes publishIndexCache + // now is the clock rewritten metadata is dated by, and started the time // the process started; see metadataDate. now func() time.Time started time.Time + + // cooldownWatch holds the rewrites recording which versions cooldown + // holds back; see cooldown_expiry.go. + cooldownWatch cooldownWatch + shared *Proxy + + // viewCooldown is set on the shared proxy once a view of it has cooldown + // on; see anyCooldownEnabled. + viewCooldown atomic.Bool +} + +// cooldownEcosystems are the ecosystems whose handlers apply cooldown. Others +// have no publish time to check, so a configured cooldown has no effect there. +var cooldownEcosystems = map[string]bool{ + "cargo": true, "composer": true, "conda": true, "gem": true, + "golang": true, "helm": true, "hex": true, "maven": true, + "npm": true, "nuget": true, "pub": true, "pypi": true, +} + +// CooldownSupported reports whether the proxy applies cooldown to an +// ecosystem. +func CooldownSupported(ecosystem string) bool { + return cooldownEcosystems[ecosystem] } // CooldownPolicy supplies version-age filtering and package-specific durations. @@ -262,6 +361,9 @@ type CacheResult struct { Artifact artifacts.Artifact Cached bool storagePath string + // rangeable is set on a HEAD cache hit, which has no Reader, when the + // stored object would open as a seekable reader. + rangeable bool } // GetOrFetchArtifact retrieves an artifact from cache or fetches from upstream. @@ -291,6 +393,9 @@ func (p *Proxy) GetOrFetchArtifact(ctx context.Context, ecosystem, name, version if filename == "" { return nil, errors.New("resolved artifact has no filename") } + if route := p.routeFor(ecosystem, name); route != nil { + filename = route.FilenamePrefix + filename + } } if p.StreamArtifacts { if info == nil { @@ -308,7 +413,7 @@ func (p *Proxy) GetOrFetchArtifact(ctx context.Context, ecosystem, name, version } else if cached != nil { return cached, nil } - metrics.RecordCacheMiss(ecosystem) + metrics.RecordArtifactCacheMiss(ecosystem) key := artifactCoalesceKey(versionPURL, filename, "", "", "") recheck := func() (artifacts.Artifact, string, bool) { @@ -329,6 +434,44 @@ func (p *Proxy) GetCachedArtifact(ctx context.Context, ecosystem, name, version, return p.checkCache(ctx, pkgPURL, versionPURL, filename) } +// HasCachedArtifact reports whether an artifact is cached and its object is +// stored, without opening it or counting a cache hit, so a mirror run does +// not look like client traffic. +func (p *Proxy) HasCachedArtifact(ctx context.Context, ecosystem, name, version, filename string) (bool, error) { + pkgPURL, versionPURL, err := packagePURLStrings(ecosystem, name, version) + if err != nil { + return false, err + } + if p.Denylist.Denied(versionPURL) { + return false, fmt.Errorf("%w: %s", ErrVersionDenied, versionPURL) + } + if p.StreamArtifacts { + return false, nil + } + artifact, err := p.DB.GetCachedArtifact(pkgPURL, versionPURL, filename) + if err != nil { + return false, fmt.Errorf("checking artifact cache: %w", err) + } + if artifact == nil { + return false, nil + } + // An unusable record is a miss; the fetch that follows clears it. + if _, err := newIntegrityChecks(artifact.Artifact.Digest.Encoded(), artifact.Integrity.String); err != nil { + return false, nil + } + return p.Storage.Exists(ctx, artifact.StoragePath) +} + +// MarkMirrored records that a mirror run found an artifact cached, which +// keeps it from retention without counting as a cache hit. +func (p *Proxy) MarkMirrored(ecosystem, name, version, filename string) error { + _, versionPURL, err := packagePURLStrings(ecosystem, name, version) + if err != nil { + return err + } + return p.DB.MarkArtifactMirrored(versionPURL, filename) +} + // ClearCachedArtifact clears an artifact cache record after an external // integrity check fails, and queues its stored bytes for deletion. func (p *Proxy) ClearCachedArtifact(ecosystem, name, version, filename string) error { @@ -388,6 +531,12 @@ func (p *Proxy) lookupCache(ctx context.Context, pkgPURL, versionPURL, filename if p.StreamArtifacts { return nil, nil } + if cached, err := p.readStored(ctx, pkgPURL, versionPURL, filename); err != nil || cached != nil { + return cached, err + } + if moved, err := p.rekeyLegacyGoArtifact(pkgPURL, versionPURL, filename); err != nil || !moved { + return nil, err + } return p.readStored(ctx, pkgPURL, versionPURL, filename) } @@ -413,6 +562,12 @@ func (p *Proxy) readStored(ctx context.Context, pkgPURL, versionPURL, filename s storagePath: artifact.StoragePath, } + if servingHead(ctx) { + result.rangeable = readsSeekable(p.Storage) + p.recordCacheHit(artifact.Ecosystem, versionPURL, filename) + return result, nil + } + if p.DirectServe { signed, err := p.Storage.SignedURL(ctx, artifact.StoragePath, p.DirectServeTTL) if err == nil { @@ -437,7 +592,7 @@ func (p *Proxy) readStored(ctx context.Context, pkgPURL, versionPURL, filename s return nil, nil } - result.Reader, err = checks.wrap(reader, + result.Reader, err = checks.forStoredObject().wrapFailOnMismatch(reader, func(reason string) { p.Logger.Error("cached artifact failed integrity check", "purl", versionPURL, "filename", filename, @@ -479,7 +634,7 @@ func rewriteSignedURLHost(signed, baseURL string) string { func (p *Proxy) recordCacheHit(ecosystem, versionPURL, filename string) { _ = p.DB.RecordArtifactHit(versionPURL, filename) - metrics.RecordCacheHit(ecosystem) + metrics.RecordArtifactCacheHit(ecosystem) } func (p *Proxy) rejectUnusableCacheRecord(artifact *database.CachedArtifact, versionPURL, filename string, cause error) { @@ -493,8 +648,29 @@ func (p *Proxy) rejectUnusableCacheRecord(artifact *database.CachedArtifact, ver } } +// ArtifactRoute fetches a package from an upstream other than its +// ecosystem's default one. +type ArtifactRoute struct { + // Resolver finds the package's download URLs on that upstream. + Resolver *fetch.Resolver + // FilenamePrefix qualifies the artifact filename the way the handler + // does for the route, so clients are served what was fetched. + FilenamePrefix string +} + +func (p *Proxy) routeFor(ecosystem, name string) *ArtifactRoute { + if p.RouteFor == nil { + return nil + } + return p.RouteFor(ecosystem, name) +} + func (p *Proxy) resolveArtifact(ctx context.Context, ecosystem, name, version string) (*fetch.ArtifactInfo, error) { - info, err := p.Resolver.Resolve(ctx, ecosystem, name, version) + resolver := p.Resolver + if route := p.routeFor(ecosystem, name); route != nil { + resolver = route.Resolver + } + info, err := resolver.Resolve(ctx, ecosystem, name, version) if err != nil { if errors.Is(err, fetch.ErrNotFound) { return nil, ErrUpstreamNotFound @@ -515,7 +691,7 @@ func (p *Proxy) fetchAndCache(ctx context.Context, ecosystem, name, version, fil } } - if err := p.RateLimits.Held(info.URL); err != nil { + if err := p.upstreamHeld(info.URL); err != nil { return artifacts.Artifact{}, "", err } p.Logger.Info("fetching from upstream", @@ -537,7 +713,7 @@ func (p *Proxy) fetchAndCache(ctx context.Context, ecosystem, name, version, fil } metrics.RecordUpstreamFetch(ecosystem, fetchDuration) - return p.storeArtifact(ctx, ecosystem, name, version, filename, pkgPURL, versionPURL, info.URL, "", "", artifact) + return p.storeFetched(ctx, ecosystem, name, version, filename, pkgPURL, versionPURL, info.URL, "", "", artifact) } // storeArtifact writes a fetched artifact to storage, verifies it against @@ -614,17 +790,92 @@ func (p *Proxy) storeArtifact(ctx context.Context, ecosystem, name, version, fil // Update database if err := p.updateCacheDB(ecosystem, name, pkgPURL, upstreamURL, storagePath, sharedArtifact, declared); err != nil { - p.Logger.Warn("failed to update cache database", "error", err) + if errors.Is(err, database.ErrLocalArtifactExists) { + p.Logger.Info("artifact was pushed while it was fetched; keeping the pushed copy", + "purl", versionPURL, "filename", filename) + } else { + p.Logger.Warn("failed to update cache database", "error", err) + } // Continue anyway - we have the file. Queue it for deletion in case // no record points at it; the queue skips it while one does. - if qErr := p.DB.QueuePendingDelete(storagePath); qErr != nil { - p.Logger.Warn("failed to queue unrecorded artifact for deletion", "path", storagePath, "error", qErr) + if qErr := p.DB.QueuePendingDelete(storagePath); qErr != nil && !p.recordedAt(versionPURL, filename, storagePath) { + p.Logger.Warn("failed to queue unrecorded artifact for deletion, deleting it once served", + "path", storagePath, "error", qErr) + return sharedArtifact, storagePath, errUnrecorded + } + } else if mirrorFetch(ctx) { + if err := p.DB.MarkArtifactMirrored(versionPURL, filename); err != nil { + p.Logger.Warn("failed to record mirrored artifact", "error", err) } } return sharedArtifact, storagePath, nil } +// recordedAt reports whether the artifact's record points at storagePath. A +// commit can apply and still report an error, so storeArtifact checks before +// treating an object as unrecorded. A failed lookup counts as not recorded. +func (p *Proxy) recordedAt(versionPURL, filename, storagePath string) bool { + a, err := p.DB.GetArtifact(versionPURL, filename) + return err == nil && a != nil && a.StoragePath.Valid && a.StoragePath.String == storagePath +} + +// errUnrecorded comes back from storeArtifact together with a usable artifact +// and path when neither a record nor a queue entry could be written for it. +// Nothing else would ever delete the object, so the fetch serves it to +// everyone sharing it and deletes it when the last of them is done. +var errUnrecorded = errors.New("stored artifact has no record") + +// unrecordedObject deletes an unrecorded object once every caller sharing +// its fetch has released it. +type unrecordedObject struct { + refs atomic.Int32 + delete func() +} + +func (u *unrecordedObject) release() { + if u.refs.Add(-1) == 0 { + u.delete() + } +} + +// releaseOnClose releases an unrecorded object once its reader is closed. +type releaseOnClose struct { + io.ReadCloser + release func() +} + +func (r *releaseOnClose) Close() error { + err := r.ReadCloser.Close() + r.release() + return err +} + +// seekableReleaseOnClose keeps range requests working on a seekable reader. +type seekableReleaseOnClose struct { + releaseOnClose + io.Seeker +} + +// serveUnrecorded gives one caller its own reader over an unrecorded object +// and releases the caller's hold on it when that reader closes, or right away +// if it can't be opened. +func (p *Proxy) serveUnrecorded(ctx context.Context, u *unrecordedObject, artifact artifacts.Artifact, path string) (*CacheResult, error) { + res, err := p.openStoredArtifact(ctx, artifact, path) + if err != nil { + u.release() + return nil, err + } + // Once, so a second Close can't drop another caller's hold. + r := releaseOnClose{ReadCloser: res.Reader, release: sync.OnceFunc(u.release)} + if s, ok := res.Reader.(io.Seeker); ok { + res.Reader = &seekableReleaseOnClose{releaseOnClose: r, Seeker: s} + } else { + res.Reader = &r + } + return res, nil +} + // openStoredArtifact gives one caller its own reader over just-committed // bytes. Callers sharing a fetch cannot share a handle: it has one read // position, so they would consume each other's bytes and the first Close would @@ -676,13 +927,19 @@ func (p *Proxy) cachedArtifactRecord(pkgPURL, versionPURL, filename, upstreamHas // fetch panicked out of it. var errSharedFetchAbandoned = errors.New("shared upstream fetch did not complete") -// inflightFetch is one upstream fetch that concurrent callers share. val and -// err are written before done closes and read only after, so the close is the -// handoff. +// inflightFetch is one upstream fetch that concurrent callers share. val, err +// and unrecorded are written before done closes and read only after, so the +// close is the handoff. done closes under fetchMu, so a waiter leaving early +// knows whether it was counted in waiters. type inflightFetch struct { - done chan struct{} - val fetchedArtifact - err error + done chan struct{} + val fetchedArtifact + err error + unrecorded *unrecordedObject + + // waiters counts callers waiting on the fetch, guarded by fetchMu. + // Tests read it to know a caller has joined. + waiters int } // coalesceFetch runs commit at most once for concurrent callers sharing key, @@ -710,56 +967,132 @@ type inflightFetch struct { // proxy_cache_misses_total and upstream fetch observations is what coalescing // saved. func (p *Proxy) coalesceFetch(ctx context.Context, key string, recheck func() (artifacts.Artifact, string, bool), commit func(context.Context) (artifacts.Artifact, string, error)) (*CacheResult, error) { - p.fetchMu.Lock() - if p.inFlight == nil { - p.inFlight = make(map[string]*inflightFetch) + shared := p.sharedProxy() + shared.fetchMu.Lock() + if shared.inFlight == nil { + shared.inFlight = make(map[string]*inflightFetch) } - f, joined := p.inFlight[key] - if !joined { + f, joined := shared.inFlight[key] + if joined { + f.waiters++ + } else { f = &inflightFetch{done: make(chan struct{})} - p.inFlight[key] = f + shared.inFlight[key] = f } - p.fetchMu.Unlock() + shared.fetchMu.Unlock() if !joined { + if streamsCacheMiss(ctx) { + return p.runSharedFetchStreaming(ctx, key, f, recheck, commit) + } return p.runSharedFetch(ctx, key, f, recheck, commit) } select { case <-ctx.Done(): // This caller gave up; the fetch continues for everyone else. + p.leaveFetch(f) return nil, ctx.Err() case <-f.done: } if f.err != nil { return nil, f.err } + if f.unrecorded != nil { + return p.serveUnrecorded(ctx, f.unrecorded, f.val.artifact, f.val.storagePath) + } return p.openStoredArtifact(ctx, f.val.artifact, f.val.storagePath) } +// leaveFetch withdraws a waiter that gave up. Once the fetch has finished the +// waiter was counted as holding any unrecorded object, so it releases it. +func (p *Proxy) leaveFetch(f *inflightFetch) { + shared := p.sharedProxy() + shared.fetchMu.Lock() + select { + case <-f.done: + shared.fetchMu.Unlock() + if f.unrecorded != nil { + f.unrecorded.release() + } + default: + f.waiters-- + shared.fetchMu.Unlock() + } +} + // runSharedFetch performs the fetch that joined callers are waiting on. It is // never abandoned early, and always releases the key and wakes the waiters. func (p *Proxy) runSharedFetch(ctx context.Context, key string, f *inflightFetch, recheck func() (artifacts.Artifact, string, bool), commit func(context.Context) (artifacts.Artifact, string, error)) (*CacheResult, error) { + shared := p.sharedProxy() // Set before running so a panicking commit leaves waiters with an error // rather than a zero-valued artifact. f.err = errSharedFetchAbandoned defer func() { - p.fetchMu.Lock() - delete(p.inFlight, key) - p.fetchMu.Unlock() + shared.fetchMu.Lock() + delete(shared.inFlight, key) + if f.unrecorded != nil { + // Hand each waiter a hold, then drop the one kept while the + // waiters were still unknown. + f.unrecorded.refs.Add(int32(f.waiters)) + defer f.unrecorded.release() + } close(f.done) + shared.fetchMu.Unlock() }() // A caller checks the cache before reaching here, so a fetch that finished // in between would otherwise be repeated. Serve that record only if its // bytes are still present: a record can outlive them, and refetching is // the same recovery the cache lookup makes. - if stored, path, ok := recheck(); ok { - if res, err := p.openStoredArtifact(ctx, stored, path); err == nil { - f.val, f.err = fetchedArtifact{artifact: stored, storagePath: path}, nil - return res, nil + served := func(ctx context.Context) (*CacheResult, bool) { + stored, path, ok := recheck() + if !ok { + return nil, false } + res, err := p.openStoredArtifact(ctx, stored, path) + if err != nil { + return nil, false + } + f.val, f.err = fetchedArtifact{artifact: stored, storagePath: path}, nil + return res, true } + if res, ok := served(ctx); ok { + return res, nil + } + + // Another instance sharing the database may be fetching the same + // artifact. Wait for it to store the artifact rather than fetch it too. + // The wait makes no upstream request, so a detached fetch waits past + // its client too, bounded by the holder's fetch and the lease expiry; + // otherwise callers that joined this one would get its cancellation. + waitCtx := ctx + if upstreamFetchDetached(ctx) { + waitCtx = context.WithoutCancel(ctx) + } + var waitedFor *CacheResult + release, outcome, err := p.awaitFetchLease(waitCtx, metrics.CacheKindArtifact, key, func() bool { + res, ok := served(waitCtx) + waitedFor = res + return ok + }) + if err != nil { + f.err = err + return nil, err + } + if outcome == leaseStored { + return waitedFor, nil + } + // With leaseFailed, release is a no-op and this instance fetches on its + // own, so a failing upstream costs each instance one attempt in + // parallel. A rate-limited holder has published its hold by now, and + // rereading it makes commit refuse the fetch with the holder's + // Retry-After instead of sending one more request to the limited host. + if outcome == leaseFailed { + p.reloadUpstreamHolds() + } + failed := true + defer func() { release(failed) }() commitCtx := ctx if upstreamFetchDetached(ctx) && p.acquireDetachSlot() { @@ -767,13 +1100,79 @@ func (p *Proxy) runSharedFetch(ctx context.Context, key string, f *inflightFetch commitCtx = context.WithoutCancel(ctx) } stored, path, err := commit(commitCtx) + unrecorded := errors.Is(err, errUnrecorded) + if unrecorded { + err = nil + } + // Nothing an instance waiting on the lease could find was recorded, so + // an unrecorded object counts as failed for it. + failed = err != nil || unrecorded f.val, f.err = fetchedArtifact{artifact: stored, storagePath: path}, err if err != nil { return nil, err } + // A caller handed the stream already has the bytes; opening the stored + // copy would cost a read it never uses, a GET on S3 or GCS. + h := handoffFrom(ctx) + handedOver := h != nil && h.handedOver() + if unrecorded { + f.unrecorded = &unrecordedObject{delete: func() { p.deleteUnrecorded(path) }} + f.unrecorded.refs.Add(1) // until the waiters are counted + if handedOver { + h.holdUnrecorded(f.unrecorded) + return nil, nil + } + f.unrecorded.refs.Add(1) // this caller + return p.serveUnrecorded(ctx, f.unrecorded, stored, path) + } + if handedOver { + return nil, nil + } return p.openStoredArtifact(ctx, stored, path) } +func (p *Proxy) deleteUnrecorded(path string) { + if err := p.Storage.Delete(context.Background(), path); err != nil { + p.Logger.Warn("failed to delete unrecorded artifact", "path", path, "error", err) + } +} + +type servingHeadKey struct{} + +// ServingHead marks ctx as serving a HEAD request. A cache hit under it is +// answered from the artifact's database record without opening the stored +// object: on S3 or GCS opening it issues a GET whose unread body would only +// be thrown away. The server sets it on every HEAD request. +func ServingHead(ctx context.Context) context.Context { + return context.WithValue(ctx, servingHeadKey{}, true) +} + +func servingHead(ctx context.Context) bool { + head, _ := ctx.Value(servingHeadKey{}).(bool) + return head +} + +// readsSeekable reports whether store opens objects as seekable readers, so a +// HEAD response can advertise byte ranges exactly as the GET would. +func readsSeekable(store storage.Storage) bool { + s, ok := store.(storage.SeekableReads) + return ok && s.ReadsSeekable() +} + +type mirrorFetchKey struct{} + +// MirrorFetch marks ctx as a mirror run's rather than a client's. An +// artifact fetched under it is recorded as mirrored, so it doesn't count as +// downloaded by a client. +func MirrorFetch(ctx context.Context) context.Context { + return context.WithValue(ctx, mirrorFetchKey{}, true) +} + +func mirrorFetch(ctx context.Context) bool { + mirror, _ := ctx.Value(mirrorFetchKey{}).(bool) + return mirror +} + type detachUpstreamFetchKey struct{} // DetachUpstreamFetch marks ctx so that an artifact fetch started under it @@ -801,12 +1200,13 @@ func upstreamFetchDetached(ctx context.Context) bool { const maxDetachedFetches = 64 func (p *Proxy) acquireDetachSlot() bool { - p.fetchMu.Lock() - if p.detachSlots == nil { - p.detachSlots = make(chan struct{}, maxDetachedFetches) + shared := p.sharedProxy() + shared.fetchMu.Lock() + if shared.detachSlots == nil { + shared.detachSlots = make(chan struct{}, maxDetachedFetches) } - slots := p.detachSlots - p.fetchMu.Unlock() + slots := shared.detachSlots + shared.fetchMu.Unlock() select { case slots <- struct{}{}: @@ -817,7 +1217,8 @@ func (p *Proxy) acquireDetachSlot() bool { } func (p *Proxy) releaseDetachSlot() { - <-p.detachSlots + shared := p.sharedProxy() + <-shared.detachSlots } // fetchedArtifact is what a shared fetch hands its callers: metadata and a @@ -875,10 +1276,6 @@ func (p *Proxy) updateCacheDB(ecosystem, name, pkgPURL, upstreamURL, storagePath RegistryURL: sql.NullString{String: upstreamURL, Valid: true}, EnrichedAt: sql.NullTime{Time: now, Valid: true}, } - if err := p.DB.UpsertPackage(pkg); err != nil { - return fmt.Errorf("upserting package: %w", err) - } - // Upsert version ver := &database.Version{ PURL: artifact.PURL, @@ -886,10 +1283,6 @@ func (p *Proxy) updateCacheDB(ecosystem, name, pkgPURL, upstreamURL, storagePath Integrity: sql.NullString{String: declared, Valid: declared != ""}, EnrichedAt: sql.NullTime{Time: now, Valid: true}, } - if err := p.DB.UpsertVersion(ver); err != nil { - return fmt.Errorf("upserting version: %w", err) - } - // Upsert artifact art := &database.Artifact{ VersionPURL: artifact.PURL, @@ -901,10 +1294,11 @@ func (p *Proxy) updateCacheDB(ecosystem, name, pkgPURL, upstreamURL, storagePath ContentType: sql.NullString{String: artifact.MediaType, Valid: true}, FetchedAt: sql.NullTime{Time: now, Valid: true}, } - if err := p.DB.UpsertArtifact(art); err != nil { - return fmt.Errorf("upserting artifact: %w", err) + // One transaction, so a push that landed while this was fetched keeps + // both its artifact and its version's integrity. + if err := p.DB.RecordCachedArtifact(pkg, ver, art); err != nil { + return fmt.Errorf("recording artifact: %w", err) } - return nil } @@ -956,9 +1350,9 @@ func serveArtifactResponse(w http.ResponseWriter, method string, request *http.R if result.Reader != nil { seeker, _ = result.Reader.(io.Seeker) } - if seeker != nil && result.Artifact.Size >= 0 { + if (seeker != nil || result.rangeable) && result.Artifact.Size >= 0 { w.Header().Set("Accept-Ranges", "bytes") - if request != nil && serveArtifactRange(w, request, result, seeker) { + if seeker != nil && request != nil && serveArtifactRange(w, request, result, seeker) { return } } @@ -1107,6 +1501,21 @@ func copyArtifactBody(w http.ResponseWriter, reader io.Reader, expectedSize int6 } } +// upstreamRequest sends r's method to upstreamURL, copying only the +// forwardHeaders that r sets. +func (p *Proxy) upstreamRequest(r *http.Request, upstreamURL string, forwardHeaders []string) (*http.Response, error) { + req, err := http.NewRequestWithContext(r.Context(), r.Method, upstreamURL, nil) + if err != nil { + return nil, err + } + for _, header := range forwardHeaders { + if v := r.Header.Get(header); v != "" { + req.Header.Set(header, v) + } + } + return p.HTTPClient.Do(req) +} + // ProxyUpstream forwards a request to an upstream URL without caching. // It copies the request, forwards specified headers, and streams the response back. // forwardHeaders controls the request headers sent upstream. End-to-end response @@ -1114,20 +1523,13 @@ func copyArtifactBody(w http.ResponseWriter, reader io.Reader, expectedSize int6 func (p *Proxy) ProxyUpstream(w http.ResponseWriter, r *http.Request, upstreamURL string, forwardHeaders []string) { p.Logger.Debug("proxying to upstream", "url", upstreamURL) - req, err := http.NewRequestWithContext(r.Context(), r.Method, upstreamURL, nil) - if err != nil { - http.Error(w, "failed to create request", http.StatusInternalServerError) - return - } + resp, err := p.upstreamRequest(r, upstreamURL, forwardHeaders) + p.relayUpstream(w, r, resp, err) +} - // Copy request headers that affect content negotiation / caching - for _, header := range forwardHeaders { - if v := r.Header.Get(header); v != "" { - req.Header.Set(header, v) - } - } - - resp, err := p.HTTPClient.Do(req) +// relayUpstream writes the result of an upstream request: the response, or +// a 502 when the request failed. +func (p *Proxy) relayUpstream(w http.ResponseWriter, r *http.Request, resp *http.Response, err error) { if err != nil { if writeUpstreamHeld(w, err) { return @@ -1169,6 +1571,17 @@ func JSONError(w http.ResponseWriter, status int, message string) { _, _ = fmt.Fprintf(w, `{"error":%q}`, message) } +// staleWarning marks a response served from the metadata cache because the +// upstream could not be reached. +const staleWarning = `110 - "Response is Stale"` + +// markStale sets the stale warning on a metadata response when stale is set. +func markStale(w http.ResponseWriter, stale bool) { + if stale { + w.Header().Set("Warning", staleWarning) + } +} + // ErrUpstreamNotFound indicates the upstream returned 404. var ErrUpstreamNotFound = fmt.Errorf("upstream: %w", fetch.ErrNotFound) @@ -1231,19 +1644,13 @@ func (p *Proxy) serveArtifactError(w http.ResponseWriter, err error, clientMsg s // errStale304 is returned when upstream sends 304 but the cached file is missing. var errStale304 = fmt.Errorf("upstream returned 304 but cached file is missing") -// metadataStoragePath builds a storage path for cached metadata. -func metadataStoragePath(ecosystem, cacheKey string) string { - return "_metadata/" + ecosystem + "/" + cacheKey + "/metadata" -} - // FetchOrCacheMetadata fetches metadata from upstream with caching. // On success it returns the raw response bytes and content type. // If upstream fails and a cached copy exists, the cached version is returned. // cacheKey is typically the package name but can include subpath components. // Optional acceptHeaders specify the Accept header(s) to send; defaults to application/json. func (p *Proxy) FetchOrCacheMetadata(ctx context.Context, ecosystem, cacheKey, upstreamURL string, acceptHeaders ...string) ([]byte, string, error) { - body, contentType, _, err := p.fetchOrCacheMetadata(ctx, ecosystem, cacheKey, upstreamURL, "", nil, acceptHeaders...) - return body, contentType, err + return p.fetchOrCacheMetadata(ctx, ecosystem, cacheKey, upstreamURL, "", nil, acceptHeaders...) } // fetchOrCacheMetadata implements FetchOrCacheMetadata. acceptEncoding controls @@ -1259,20 +1666,21 @@ func (p *Proxy) FetchOrCacheMetadata(ctx context.Context, ecosystem, cacheKey, u // it can also decode the document into request-local state; a caller that // joined a fetch gets its own validation error directly. It must not modify the // body, which joined callers share. -func (p *Proxy) fetchOrCacheMetadata(ctx context.Context, ecosystem, cacheKey, upstreamURL, acceptEncoding string, validate func([]byte) error, acceptHeaders ...string) ([]byte, string, string, error) { +func (p *Proxy) fetchOrCacheMetadata(ctx context.Context, ecosystem, cacheKey, upstreamURL, acceptEncoding string, validate func([]byte) error, acceptHeaders ...string) ([]byte, string, error) { accept := contentTypeJSON if len(acceptHeaders) > 0 && acceptHeaders[0] != "" { accept = acceptHeaders[0] } res := p.lookupMetadata(ctx, ecosystem, cacheKey, upstreamURL, accept, acceptEncoding, validate) - return res.body, res.contentType, res.contentEncoding, res.err + return res.body, res.contentType, res.err } // fetchMetadataDocument is FetchOrCacheMetadata for callers that rewrite the // document and need to know which one they got: the result carries its -// digest along with the body. -func (p *Proxy) fetchMetadataDocument(ctx context.Context, ecosystem, cacheKey, upstreamURL, accept string) metadataResult { - return p.lookupMetadata(ctx, ecosystem, cacheKey, upstreamURL, accept, "", nil) +// digest along with the body. validate, which may be nil, is as for +// fetchOrCacheMetadata. +func (p *Proxy) fetchMetadataDocument(ctx context.Context, ecosystem, cacheKey, upstreamURL, accept string, validate func([]byte) error) metadataResult { + return p.lookupMetadata(ctx, ecosystem, cacheKey, upstreamURL, accept, "", validate) } // lookupMetadata implements fetchOrCacheMetadata and fetchMetadataDocument. @@ -1283,7 +1691,7 @@ func (p *Proxy) lookupMetadata(ctx context.Context, ecosystem, cacheKey, upstrea // Serve from cache if within TTL (skip upstream entirely) if _, hit := p.cachedMetadataState(ctx, ecosystem, cacheKey, validate); hit != nil { - metrics.RecordCacheHit(ecosystem) + metrics.RecordMetadataCacheHit(ecosystem, len(hit.body)) return *hit } p.recordMetadataCacheMiss(ecosystem) @@ -1304,7 +1712,41 @@ func (p *Proxy) coalescedMetadataMiss(ctx context.Context, ecosystem, cacheKey, if hit != nil { return *hit } - return p.fetchMetadataFromUpstream(fetchCtx, ecosystem, cacheKey, upstreamURL, accept, acceptEncoding, validate, entry) + // Another instance sharing the database may be fetching the same + // document. Only a stored copy within TTL can be served after + // waiting, so without that there is nothing to wait for. + release := func(bool) {} + if p.CacheMetadata && p.MetadataTTL > 0 { + var outcome leaseOutcome + var err error + release, outcome, err = p.awaitFetchLease(fetchCtx, metrics.CacheKindMetadata, key, func() bool { + entry, hit = p.cachedMetadataState(fetchCtx, ecosystem, cacheKey, validate) + return hit != nil + }) + if err != nil { + return metadataResult{err: err} + } + switch outcome { + case leaseStored: + return *hit + case leaseFailed: + // Serve the stale copy at once, as the holder did, rather + // than trying the failing upstream again. Without one, fetch, + // unless the holder was rate limited: its hold, read here, + // refuses the fetch with its Retry-After. + p.reloadUpstreamHolds() + if entry != nil { + if res := p.staleMetadata(fetchCtx, ecosystem, cacheKey, validate, entry, errFetchFailedElsewhere); res.err == nil { + return res + } + } + case leaseFetch: + } + } + res := metadataResult{err: errSharedFetchAbandoned} + defer func() { release(res.err != nil || res.stale) }() + res = p.fetchMetadataFromUpstream(fetchCtx, ecosystem, cacheKey, upstreamURL, accept, acceptEncoding, validate, entry) + return res }) // The fetch ran the first caller's validate. A caller that joined it runs // its own on the shared bytes, since validate may also decode them for it. @@ -1326,10 +1768,11 @@ func (p *Proxy) cachedMetadataState(ctx context.Context, ecosystem, cacheKey str return nil, nil } entry, _ := p.DB.GetMetadataCache(ecosystem, cacheKey) + entry = p.migrateLegacyMetadataEntry(ctx, ecosystem, cacheKey, entry) if entry != nil && p.MetadataTTL > 0 && entry.FetchedAt.Valid && time.Since(entry.FetchedAt.Time) < p.MetadataTTL { data, ct, err := p.readCachedMetadata(ctx, entry, validate) if err == nil { - hit := metadataResult{body: data, contentType: ct, contentEncoding: entry.ContentEncoding.String}.describedBy(entry) + hit := metadataResult{body: data, contentType: ct, contentEncoding: entry.ContentEncoding.String, fromCache: true}.describedBy(entry) return entry, &hit } if validate != nil { @@ -1340,27 +1783,70 @@ func (p *Proxy) cachedMetadataState(ctx context.Context, ecosystem, cacheKey str return entry, nil } +// refreshMetadata is lookupMetadata for a document whose cached copy is known +// to be out of date although it is within its TTL. It skips the TTL and asks +// upstream, revalidating the cached copy with its validators, and falls back +// to that copy if upstream fails, which the result reports as stale. +// Concurrent refreshes of one document share a fetch. +func (p *Proxy) refreshMetadata(ctx context.Context, ecosystem, cacheKey, upstreamURL, accept, acceptEncoding string, validate func([]byte) error) metadataResult { + if containsPathTraversal(cacheKey) { + return metadataResult{err: fmt.Errorf("invalid cache key: %q", cacheKey)} + } + key := metadataCoalesceKey(ecosystem, cacheKey, upstreamURL, accept, acceptEncoding, validate != nil) + "\x00refresh" + res, shared := p.coalesceMetadata(ctx, key, func(fetchCtx context.Context) metadataResult { + var entry *database.MetadataCacheEntry + if p.CacheMetadata && p.DB != nil { + entry, _ = p.DB.GetMetadataCache(ecosystem, cacheKey) + } + return p.fetchMetadataFromUpstream(fetchCtx, ecosystem, cacheKey, upstreamURL, accept, acceptEncoding, validate, entry) + }) + if shared && res.err == nil && validate != nil { + if err := validate(res.body); err != nil { + return metadataResult{err: err} + } + } + return res +} + // fetchMetadataFromUpstream fetches metadata after a cache miss, caches it, // and falls back to the cached copy if upstream fails. entry is the row to // revalidate against, or nil. func (p *Proxy) fetchMetadataFromUpstream(ctx context.Context, ecosystem, cacheKey, upstreamURL, accept, acceptEncoding string, validate func([]byte) error, entry *database.MetadataCacheEntry) metadataResult { - meta, err := p.fetchUpstreamMetadata(ctx, upstreamURL, entry, accept, acceptEncoding) - if errors.Is(err, errStale304) { - // 304 but cached file is gone; retry without ETag - meta, err = p.fetchUpstreamMetadata(ctx, upstreamURL, nil, accept, acceptEncoding) + fetch := func(entry *database.MetadataCacheEntry) (*upstreamMetadata, error) { + meta, err := p.fetchUpstreamMetadata(ctx, upstreamURL, entry, accept, acceptEncoding) + if err == nil && validate != nil { + err = validate(meta.body) + } + return meta, err } - if err == nil && validate != nil { - err = validate(meta.body) + meta, err := fetch(entry) + var digest string + // Validated first, so a 304 for a rejected copy doesn't mark it fresh. + if err == nil && p.CacheMetadata { + digest, err = p.refreshMetadataBlob(ecosystem, cacheKey, meta) + } + if errors.Is(err, errStale304) { + // 304 but the cached copy is gone or was replaced; retry without + // validators. + meta, err = fetch(nil) } if err == nil { - var digest string - if p.CacheMetadata { + if p.CacheMetadata && digest == "" { digest = p.cacheMetadataBlob(ctx, ecosystem, cacheKey, metadataStoragePath(ecosystem, cacheKey), meta) } - return metadataResult{body: meta.body, contentType: meta.contentType, contentEncoding: meta.contentEncoding, digest: digest} + return fetchedResult(meta, digest) } - // Upstream failed -- fall back to cache if available + return p.staleMetadata(ctx, ecosystem, cacheKey, validate, entry, err) +} + +// errFetchFailedElsewhere is the upstream error behind a stale copy served +// because another instance's fetch for it failed. +var errFetchFailedElsewhere = errors.New("upstream fetch failed on another instance") + +// staleMetadata falls back to the cached copy in entry after the upstream +// fetch failed with err. +func (p *Proxy) staleMetadata(ctx context.Context, ecosystem, cacheKey string, validate func([]byte) error, entry *database.MetadataCacheEntry, err error) metadataResult { if !p.CacheMetadata || entry == nil { return metadataResult{err: fmt.Errorf("upstream failed and no cached metadata: %w", err)} } @@ -1370,17 +1856,25 @@ func (p *Proxy) fetchMetadataFromUpstream(ctx context.Context, ecosystem, cacheK // Re-read the row so the encoding describes the blob as it is now: a // concurrent refetch may have replaced both since entry was read above - // (an identity blob swapped for a gzip one during rollout). - entry = p.currentMetadataEntry(ecosystem, cacheKey, entry) - - data, ct, readErr := p.readCachedMetadata(ctx, entry, validate) - if readErr != nil { - return metadataResult{err: fmt.Errorf("upstream failed and cached metadata unusable (%v): %w", readErr, err)} + // (an identity blob swapped for a gzip one during rollout). Bytes that + // don't match the row were replaced after it was read, so the row is + // read once more; if they still don't match, no row describes them. + for attempt := 0; ; attempt++ { + entry = p.currentMetadataEntry(ecosystem, cacheKey, entry) + data, ct, readErr := p.readCachedMetadata(ctx, entry, validate) + if readErr == nil && !matchesEntryDigest(entry, data) { + if attempt == 0 { + continue + } + readErr = errors.New("replaced while being read") + } + if readErr != nil { + return metadataResult{err: fmt.Errorf("upstream failed and cached metadata unusable (%v): %w", readErr, err)} + } + p.Logger.Info("serving metadata from cache", + "ecosystem", ecosystem, "key", cacheKey) + return metadataResult{body: data, contentType: ct, contentEncoding: entry.ContentEncoding.String, stale: true, upstreamErr: err}.describedBy(entry) } - - p.Logger.Info("serving metadata from cache", - "ecosystem", ecosystem, "key", cacheKey) - return metadataResult{body: data, contentType: ct, contentEncoding: entry.ContentEncoding.String, stale: true}.describedBy(entry) } // metadataResult is what a metadata lookup hands back. A shared fetch gives @@ -1393,20 +1887,54 @@ type metadataResult struct { // empty otherwise. digest string err error + // etag and lastModified are the validators of body: upstream's for a + // fetched document, the cache row's for a stored one. + etag string + lastModified time.Time // stale is set when the body is the cached copy served because upstream - // failed. - stale bool + // failed, and upstreamErr is that failure. + stale bool + upstreamErr error + // fromCache is set when the body is a stored copy within its TTL, read + // without asking upstream. + fromCache bool + // entry is the cache row of the stored document, for a lookup that + // leaves the document in storage (see storedMetadataDocument). body is + // nil then. + entry *database.MetadataCacheEntry } -// describedBy returns res with the digest that entry, the cache row its body -// was read for, records. +// describedBy returns res with the digest and validators that entry, the +// cache row its body was read for, records. func (res metadataResult) describedBy(entry *database.MetadataCacheEntry) metadataResult { if entry.ContentDigest.Valid { res.digest = entry.ContentDigest.String } + res.etag = entry.ETag.String + if entry.LastModified.Valid { + res.lastModified = entry.LastModified.Time + } return res } +// fetchedResult returns the result for meta, a document from upstream (or +// the stored copy it answered 304 for), cached under digest. +func fetchedResult(meta *upstreamMetadata, digest string) metadataResult { + return metadataResult{ + body: meta.body, + contentType: meta.contentType, + contentEncoding: meta.contentEncoding, + digest: digest, + etag: meta.etag, + lastModified: meta.lastModified, + } +} + +// cachedMeta returns the validators and staleness of res's body. +func (res metadataResult) cachedMeta() cachedMeta { + return cachedMeta{etag: res.etag, lastModified: res.lastModified, stale: res.stale} +} + // inflightMetadata is one metadata fetch that concurrent callers share. res is // written before done closes and read only after, so the close is the handoff. type inflightMetadata struct { @@ -1437,18 +1965,19 @@ func metadataCoalesceKey(ecosystem, cacheKey, upstreamURL, accept, acceptEncodin // fail when the first of them disconnects. It stays bounded by the HTTP // client's timeout. Waiters still leave when their own context ends. func (p *Proxy) coalesceMetadata(ctx context.Context, key string, fetch func(context.Context) metadataResult) (metadataResult, bool) { - p.metaMu.Lock() - if p.inFlightMeta == nil { - p.inFlightMeta = make(map[string]*inflightMetadata) + shared := p.sharedProxy() + shared.metaMu.Lock() + if shared.inFlightMeta == nil { + shared.inFlightMeta = make(map[string]*inflightMetadata) } - f, joined := p.inFlightMeta[key] + f, joined := shared.inFlightMeta[key] if joined { f.waiters++ } else { f = &inflightMetadata{done: make(chan struct{})} - p.inFlightMeta[key] = f + shared.inFlightMeta[key] = f } - p.metaMu.Unlock() + shared.metaMu.Unlock() if joined { select { @@ -1463,9 +1992,9 @@ func (p *Proxy) coalesceMetadata(ctx context.Context, key string, fetch func(con // rather than an empty body. f.res = metadataResult{err: errSharedFetchAbandoned} defer func() { - p.metaMu.Lock() - delete(p.inFlightMeta, key) - p.metaMu.Unlock() + shared.metaMu.Lock() + delete(shared.inFlightMeta, key) + shared.metaMu.Unlock() close(f.done) }() f.res = fetch(context.WithoutCancel(ctx)) @@ -1478,13 +2007,14 @@ func (p *Proxy) readCachedMetadata(ctx context.Context, entry *database.Metadata return nil, "", err } defer func() { _ = cached.Close() }() - data, err := p.ReadMetadata(cached) + data, err := p.ReadMetadataSized(cached, metadataEntrySize(entry)) if err == nil && validate != nil { err = validate(data) } if err != nil { return nil, "", err } + p.recordMetadataRead(entry) ct := contentTypeJSON if entry.ContentType.Valid { ct = entry.ContentType.String @@ -1492,9 +2022,26 @@ func (p *Proxy) readCachedMetadata(ctx context.Context, entry *database.Metadata return data, ct, nil } +// metadataEntrySize is the recorded size of a cached metadata document, or +// -1 when none is recorded. +func metadataEntrySize(entry *database.MetadataCacheEntry) int64 { + if !entry.Size.Valid { + return -1 + } + return entry.Size.Int64 +} + +// recordMetadataRead marks a cached metadata document as used, so size +// eviction drops the documents nobody asks for first. +func (p *Proxy) recordMetadataRead(entry *database.MetadataCacheEntry) { + if err := p.DB.RecordMetadataHit(entry.Ecosystem, entry.Name); err != nil { + p.Logger.Warn("failed to record metadata cache hit", "ecosystem", entry.Ecosystem, "key", entry.Name, "error", err) + } +} + func (p *Proxy) recordMetadataCacheMiss(ecosystem string) { if p.CacheMetadata { - metrics.RecordCacheMiss(ecosystem) + metrics.RecordMetadataCacheMiss(ecosystem) } } @@ -1505,6 +2052,11 @@ type upstreamMetadata struct { contentEncoding string etag string lastModified time.Time + // url is the upstream URL the document was fetched from. + url string + // notModified is the cache row upstream answered 304 for, whose stored + // bytes body holds. It is nil for a document upstream sent. + notModified *database.MetadataCacheEntry } // fetchUpstreamMetadata fetches metadata from upstream, using ETag for conditional revalidation. @@ -1514,6 +2066,67 @@ type upstreamMetadata struct { // alongside for the caller to store and replay. An empty acceptEncoding leaves Go to negotiate and // decompress transparently. func (p *Proxy) fetchUpstreamMetadata(ctx context.Context, upstreamURL string, entry *database.MetadataCacheEntry, accept, acceptEncoding string) (*upstreamMetadata, error) { + resp, err := p.requestUpstreamMetadata(ctx, upstreamURL, entry, accept, acceptEncoding) + if err != nil { + return nil, err + } + defer func() { _ = resp.Body.Close() }() + + // 304 Not Modified -- our cached copy is still good + if resp.StatusCode == http.StatusNotModified && entry != nil { + cached, readErr := p.Storage.Open(ctx, entry.StoragePath) + if readErr != nil { + return nil, errStale304 + } + defer func() { _ = cached.Close() }() + data, readErr := p.ReadMetadataSized(cached, metadataEntrySize(entry)) + if readErr != nil || !matchesEntryDigest(entry, data) { + // Gone, or replaced by another instance since entry was read. + return nil, errStale304 + } + meta := &upstreamMetadata{body: data, contentType: contentTypeJSON, etag: entry.ETag.String, url: upstreamURL, notModified: entry} + if entry.ContentType.Valid { + meta.contentType = entry.ContentType.String + } + if entry.ContentEncoding.Valid { + meta.contentEncoding = entry.ContentEncoding.String + } + if entry.LastModified.Valid { + meta.lastModified = entry.LastModified.Time + } + return meta, nil + } + + if err := upstreamMetadataStatus(resp); err != nil { + return nil, err + } + + // ContentLength is -1 when the transport decompresses the body, and + // otherwise the length of the bytes read here. + body, err := p.ReadMetadataSized(upstreamBodyReader{resp.Body}, resp.ContentLength) + if err != nil { + return nil, fmt.Errorf("reading response: %w", err) + } + + meta := &upstreamMetadata{ + body: body, + contentType: resp.Header.Get(headerContentType), + contentEncoding: resp.Header.Get(headerContentEncoding), + etag: resp.Header.Get(headerETag), + url: upstreamURL, + } + if meta.contentType == "" { + meta.contentType = contentTypeJSON + } + if lm := resp.Header.Get(headerLastModified); lm != "" { + meta.lastModified, _ = http.ParseTime(lm) + } + return meta, nil +} + +// requestUpstreamMetadata sends the request for a metadata document, +// revalidating entry when it is given. +func (p *Proxy) requestUpstreamMetadata(ctx context.Context, upstreamURL string, entry *database.MetadataCacheEntry, accept, acceptEncoding string) (*http.Response, error) { req, err := http.NewRequestWithContext(ctx, http.MethodGet, upstreamURL, nil) if err != nil { return nil, fmt.Errorf("creating request: %w", err) @@ -1533,72 +2146,86 @@ func (p *Proxy) fetchUpstreamMetadata(ctx context.Context, upstreamURL string, e if err != nil { return nil, fmt.Errorf("fetching metadata: %w", err) } - defer func() { _ = resp.Body.Close() }() + return resp, nil +} - // 304 Not Modified -- our cached copy is still good - if resp.StatusCode == http.StatusNotModified && entry != nil { - cached, readErr := p.Storage.Open(ctx, entry.StoragePath) - if readErr != nil { - return nil, errStale304 - } - defer func() { _ = cached.Close() }() - data, readErr := p.ReadMetadata(cached) - if readErr != nil { - return nil, errStale304 - } - meta := &upstreamMetadata{body: data, contentType: contentTypeJSON, etag: entry.ETag.String} - if entry.ContentType.Valid { - meta.contentType = entry.ContentType.String - } - if entry.ContentEncoding.Valid { - meta.contentEncoding = entry.ContentEncoding.String - } - if entry.LastModified.Valid { - meta.lastModified = entry.LastModified.Time - } - return meta, nil +// matchesEntryDigest reports whether data is the document entry records, +// when entry has a sha256 digest to check it by. +func matchesEntryDigest(entry *database.MetadataCacheEntry, data []byte) bool { + want, ok := strings.CutPrefix(entry.ContentDigest.String, "sha256:") + if !entry.ContentDigest.Valid || !ok { + return true } + sum := sha256.Sum256(data) + return hex.EncodeToString(sum[:]) == want +} - if resp.StatusCode == http.StatusNotFound { +// upstreamMetadataStatus returns the error for a metadata response other +// than 200. Callers handle a 304 they asked for before. +func upstreamMetadataStatus(resp *http.Response) error { + switch resp.StatusCode { + case http.StatusOK: + return nil + case http.StatusNotFound: body, _ := io.ReadAll(io.LimitReader(resp.Body, upstreamNotFoundBodyLimit)) - return nil, &upstreamNotFoundError{body: body} - } - if resp.StatusCode != http.StatusOK { - return nil, fmt.Errorf("upstream returned %d", resp.StatusCode) + return &upstreamNotFoundError{body: body} } + return fmt.Errorf("upstream returned %d", resp.StatusCode) +} - body, err := p.ReadMetadata(resp.Body) +// refreshMetadataBlob records that upstream answered 304 for the cached +// document meta was read from, by moving the row's fetched_at on. The bytes in +// storage are unchanged, so they are neither written nor hashed again. It +// returns the row's digest, or "" when the caller has to store meta as for a +// new document: when upstream sent one or the row records no digest. When +// a concurrent fetch has replaced the document since it was read, it returns +// errStale304: storing meta would put the old document back under the new +// one. A failed database write only leaves fetched_at behind, so the +// confirmed bytes are still served. +func (p *Proxy) refreshMetadataBlob(ecosystem, cacheKey string, meta *upstreamMetadata) (string, error) { + entry := meta.notModified + if entry == nil || p.DB == nil || !entry.ContentDigest.Valid { + return "", nil + } + refreshed, err := p.DB.RefreshMetadataCache(ecosystem, cacheKey, entry.ContentDigest.String, time.Now()) if err != nil { - return nil, fmt.Errorf("reading response: %w", err) + // The bytes were checked against the row and upstream confirmed + // them; only fetched_at stays behind, so they are still served. + p.Logger.Warn("failed to refresh cached metadata", "ecosystem", ecosystem, "key", cacheKey, "error", err) + return entry.ContentDigest.String, nil } - - meta := &upstreamMetadata{ - body: body, - contentType: resp.Header.Get(headerContentType), - contentEncoding: resp.Header.Get(headerContentEncoding), - etag: resp.Header.Get(headerETag), + if !refreshed { + return "", errStale304 } - if meta.contentType == "" { - meta.contentType = contentTypeJSON + if !entry.UpstreamURL.Valid && meta.url != "" { + if err := p.DB.SetMetadataUpstreamURL(ecosystem, cacheKey, meta.url); err != nil { + p.Logger.Warn("failed to record metadata upstream URL", "ecosystem", ecosystem, "key", cacheKey, "error", err) + } } - if lm := resp.Header.Get(headerLastModified); lm != "" { - meta.lastModified, _ = http.ParseTime(lm) - } - return meta, nil + p.recordMetadataRead(entry) + return entry.ContentDigest.String, nil } // cacheMetadataBlob stores metadata bytes in storage and updates the // database. It returns the digest it recorded for the bytes, or "" when they // were not cached. func (p *Proxy) cacheMetadataBlob(ctx context.Context, ecosystem, cacheKey, storagePath string, meta *upstreamMetadata) string { + digest, _ := p.storeMetadataBlob(ctx, ecosystem, cacheKey, storagePath, bytes.NewReader(meta.body), meta) + return digest +} + +// storeMetadataBlob is cacheMetadataBlob for a document read from body, +// which meta describes. It also returns the error that kept it from caching +// the document. +func (p *Proxy) storeMetadataBlob(ctx context.Context, ecosystem, cacheKey, storagePath string, body io.Reader, meta *upstreamMetadata) (string, error) { if p.DB == nil || p.Storage == nil { - return "" + return "", errMetadataNotStored } - size, hash, err := p.Storage.Store(ctx, storagePath, bytes.NewReader(meta.body)) + size, hash, err := p.Storage.Store(ctx, storagePath, body) if err != nil { p.Logger.Warn("failed to cache metadata", "ecosystem", ecosystem, "key", cacheKey, "error", err) - return "" + return "", err } var digest string if hash != "" { @@ -1615,6 +2242,7 @@ func (p *Proxy) cacheMetadataBlob(ctx context.Context, ecosystem, cacheKey, stor // The digest identifies the stored bytes, so a rewrite cached for them // can be found without reading them back (see storedRewrite). ContentDigest: sql.NullString{String: digest, Valid: digest != ""}, + UpstreamURL: sql.NullString{String: meta.url, Valid: meta.url != ""}, Size: sql.NullInt64{Int64: size, Valid: true}, LastModified: sql.NullTime{Time: meta.lastModified, Valid: !meta.lastModified.IsZero()}, FetchedAt: sql.NullTime{Time: time.Now(), Valid: true}, @@ -1628,9 +2256,9 @@ func (p *Proxy) cacheMetadataBlob(ctx context.Context, ecosystem, cacheKey, stor if delErr := p.Storage.Delete(ctx, storagePath); delErr != nil { p.Logger.Warn("failed to discard metadata blob", "ecosystem", ecosystem, "key", cacheKey, "error", delErr) } - return "" + return "", err } - return digest + return digest, nil } // currentMetadataEntry re-reads the metadata cache row and returns it, or @@ -1651,15 +2279,8 @@ type cachedMeta struct { stale bool } -// lookupCachedMeta retrieves cache validators for a metadata entry. -func (p *Proxy) lookupCachedMeta(ecosystem, cacheKey string) cachedMeta { - if p.DB == nil { - return cachedMeta{} - } - entry, err := p.DB.GetMetadataCache(ecosystem, cacheKey) - if err != nil || entry == nil { - return cachedMeta{} - } +// cachedMetaFor returns the cache validators and freshness state of entry. +func (p *Proxy) cachedMetaFor(entry *database.MetadataCacheEntry) cachedMeta { var cm cachedMeta if entry.ETag.Valid { cm.etag = entry.ETag.String @@ -1680,7 +2301,15 @@ func (p *Proxy) lookupCachedMeta(ecosystem, cacheKey string) cachedMeta { // When metadata caching is disabled, the response is streamed directly to avoid buffering // large metadata responses (e.g. npm packages with many versions) in memory. func (p *Proxy) ProxyCached(w http.ResponseWriter, r *http.Request, upstreamURL, ecosystem, cacheKey string, acceptHeaders ...string) { - p.proxyCachedWithEncoding(w, r, upstreamURL, ecosystem, cacheKey, "identity", acceptHeaders...) + p.proxyCachedWithEncoding(w, r, upstreamURL, ecosystem, cacheKey, "identity", nil, acceptHeaders...) +} + +// metadataHooks are optional callbacks for proxyCachedWithEncoding: hit runs +// after a fresh cached row is served, with that row and when it was read, and +// fetched runs with a fetched document before it is written. +type metadataHooks struct { + hit func(entry *database.MetadataCacheEntry, seen time.Time) + fetched func(body []byte, contentType, contentEncoding string) } // proxyCachedWithEncoding is ProxyCached with an explicit upstream Accept-Encoding. @@ -1688,44 +2317,83 @@ func (p *Proxy) ProxyCached(w http.ResponseWriter, r *http.Request, upstreamURL, // compressed for large, non-hash-pinned metadata whose clients decode gzip // (Homebrew API and Conda repodata). The stored bytes and Content-Encoding are // replayed verbatim either way. -func (p *Proxy) proxyCachedWithEncoding(w http.ResponseWriter, r *http.Request, upstreamURL, ecosystem, cacheKey, acceptEncoding string, acceptHeaders ...string) { +func (p *Proxy) proxyCachedWithEncoding(w http.ResponseWriter, r *http.Request, upstreamURL, ecosystem, cacheKey, acceptEncoding string, hooks *metadataHooks, acceptHeaders ...string) { if !p.CacheMetadata { // Stream directly without buffering when caching is off. p.proxyMetadataStream(w, r, upstreamURL, acceptEncoding, acceptHeaders...) return } - body, contentType, contentEncoding, err := p.fetchOrCacheMetadata(r.Context(), ecosystem, cacheKey, upstreamURL, acceptEncoding, nil, acceptHeaders...) - if err != nil { - if errors.Is(err, ErrUpstreamNotFound) { - http.Error(w, "not found", http.StatusNotFound) - return + if hooks != nil && hooks.hit != nil { + if entry := p.freshMetadataEntry(ecosystem, cacheKey); entry != nil { + seen := time.Now() + if p.serveCachedMetadata(w, r, ecosystem, cacheKey) { + hooks.hit(entry, seen) + return + } } - if writeUpstreamHeld(w, err) { - return - } - p.Logger.Error("metadata fetch failed", "error", err) - http.Error(w, "failed to fetch from upstream", http.StatusBadGateway) + } else if p.serveCachedMetadata(w, r, ecosystem, cacheKey) { return } - p.writeMetadataCachedResponseWithEncoding(w, r, ecosystem, cacheKey, body, contentType, contentEncoding) + accept := contentTypeJSON + if len(acceptHeaders) > 0 && acceptHeaders[0] != "" { + accept = acceptHeaders[0] + } + res := p.lookupMetadata(r.Context(), ecosystem, cacheKey, upstreamURL, accept, acceptEncoding, nil) + if res.err != nil { + p.writeMetadataFetchError(w, res.err) + return + } + + if hooks != nil && hooks.fetched != nil { + hooks.fetched(res.body, res.contentType, res.contentEncoding) + } + writeMetadataResult(w, r, res) } -// writeMetadataCachedResponse writes a cached metadata response and handles -// conditional request headers using metadata cache validators. -func (p *Proxy) writeMetadataCachedResponse(w http.ResponseWriter, r *http.Request, ecosystem, cacheKey string, body []byte, contentType string) { - p.writeMetadataCachedResponseWithEncoding(w, r, ecosystem, cacheKey, body, contentType, "") +// writeMetadataFetchError answers a failed metadata fetch. +func (p *Proxy) writeMetadataFetchError(w http.ResponseWriter, err error) { + if errors.Is(err, ErrUpstreamNotFound) { + http.Error(w, "not found", http.StatusNotFound) + return + } + if writeUpstreamHeld(w, err) { + return + } + p.Logger.Error("metadata fetch failed", "error", err) + http.Error(w, "failed to fetch from upstream", http.StatusBadGateway) } -// writeMetadataCachedResponseWithEncoding is writeMetadataCachedResponse with -// an explicit Content-Encoding. contentEncoding must describe the body being -// written; it is passed in rather than re-read from the cache row, which is -// missing or stale when the metadata cache write failed and would otherwise -// mislabel the bytes. -func (p *Proxy) writeMetadataCachedResponseWithEncoding(w http.ResponseWriter, r *http.Request, ecosystem, cacheKey string, body []byte, contentType, contentEncoding string) { - cm := p.lookupCachedMeta(ecosystem, cacheKey) +// writeMetadataResult writes the document res holds with its own validators +// and staleness, rather than the cache row's, which may describe other bytes +// when the cache write failed or another instance replaced it. +func writeMetadataResult(w http.ResponseWriter, r *http.Request, res metadataResult) { + writeMetadataBody(w, r, res.cachedMeta(), res.body, res.contentType, res.contentEncoding) +} +// writeMetadataBody writes a metadata document with the validators and +// staleness in cm. +func writeMetadataBody(w http.ResponseWriter, r *http.Request, cm cachedMeta, body []byte, contentType, contentEncoding string) { + if writeMetadataValidators(w, r, cm) { + return + } + + w.Header().Set(headerContentType, contentType) + w.Header().Set(headerContentLength, strconv.Itoa(len(body))) + if contentEncoding != "" { + w.Header().Set(headerContentEncoding, contentEncoding) + } + markStale(w, cm.stale) + w.WriteHeader(http.StatusOK) + if r.Method != http.MethodHead { + _, _ = w.Write(body) + } +} + +// writeMetadataValidators sets cm's ETag and Last-Modified on w and answers +// a conditional request they satisfy with 304, reporting whether it did. +func writeMetadataValidators(w http.ResponseWriter, r *http.Request, cm cachedMeta) bool { if cm.etag != "" { w.Header().Set(headerETag, cm.etag) } @@ -1734,29 +2402,17 @@ func (p *Proxy) writeMetadataCachedResponseWithEncoding(w http.ResponseWriter, r } if ifNoneMatchHits(r.Header.Get("If-None-Match"), cm.etag) { w.WriteHeader(http.StatusNotModified) - return + return true } if !cm.lastModified.IsZero() { if ims := r.Header.Get("If-Modified-Since"); ims != "" { if t, err := http.ParseTime(ims); err == nil && !cm.lastModified.After(t) { w.WriteHeader(http.StatusNotModified) - return + return true } } } - - w.Header().Set(headerContentType, contentType) - w.Header().Set(headerContentLength, strconv.Itoa(len(body))) - if contentEncoding != "" { - w.Header().Set(headerContentEncoding, contentEncoding) - } - if cm.stale { - w.Header().Set("Warning", `110 - "Response is Stale"`) - } - w.WriteHeader(http.StatusOK) - if r.Method != http.MethodHead { - _, _ = w.Write(body) - } + return false } // proxyMetadataStream forwards an upstream metadata response by streaming it to the client @@ -1819,15 +2475,69 @@ func (p *Proxy) GetOrFetchArtifactFromURLWithHeaders(ctx context.Context, ecosys return p.getOrFetchArtifactFromURL(ctx, ecosystem, name, version, filename, downloadURL, headers, "", "") } -// GetOrFetchArtifactFromURLWithDigest retrieves an artifact and verifies its -// SHA-256 digest before adding a newly fetched response to the cache. -// Non-sha256 digests are proxied without verification. -func (p *Proxy) GetOrFetchArtifactFromURLWithDigest(ctx context.Context, ecosystem, name, version, filename, downloadURL, digest string) (*CacheResult, error) { - upstreamHash, _ := strings.CutPrefix(digest, "sha256:") - if upstreamHash == digest { - upstreamHash = "" +// GetOrFetchArtifactFromURLWithDigest retrieves an artifact and verifies a +// newly fetched response against expected, an OCI-style digest such as +// "sha256:" or "sha512:", before serving or caching it. A digest +// whose algorithm can't be verified is refused with ErrUnsupportedDigest +// rather than fetched unverified. An empty expected fetches without +// verification. +func (p *Proxy) GetOrFetchArtifactFromURLWithDigest(ctx context.Context, ecosystem, name, version, filename, downloadURL, expected string) (*CacheResult, error) { + if expected == "" { + return p.getOrFetchArtifactFromURL(ctx, ecosystem, name, version, filename, downloadURL, nil, "", "") } - return p.getOrFetchArtifactFromURL(ctx, ecosystem, name, version, filename, downloadURL, nil, upstreamHash, "") + upstreamHash, declared, err := digestChecks(expected) + if err != nil { + return nil, err + } + return p.getOrFetchArtifactFromURL(ctx, ecosystem, name, version, filename, downloadURL, nil, upstreamHash, declared) +} + +// ErrUnsupportedDigest is returned for a digest whose algorithm or encoding +// the proxy can't verify. +var ErrUnsupportedDigest = errors.New("unsupported digest") + +// digestChecks turns an OCI-style digest into the checks the artifact fetch +// runs: the hex of a sha256 digest, which is also how cached artifacts are +// keyed, or for another algorithm the integrity string verifyIntegrity +// checks. +func digestChecks(expected string) (upstreamHash, declared string, _ error) { + // The sha256 hex is compared as given, ignoring case; a malformed one + // fails as a mismatch once the body has been hashed. + if hash, ok := strings.CutPrefix(expected, "sha256:"); ok { + return hash, "", nil + } + d, err := digest.Parse(expected) + if err != nil { + return "", "", fmt.Errorf("%w %q: %w", ErrUnsupportedDigest, expected, err) + } + var algorithm integrity.Algorithm + switch d.Algorithm() { + case digest.SHA384: + algorithm = integrity.SHA384 + case digest.SHA512: + algorithm = integrity.SHA512 + default: + return "", "", fmt.Errorf("%w %q", ErrUnsupportedDigest, expected) + } + sum, err := integrity.ParseHex(algorithm, d.Encoded()) + if err != nil { + return "", "", fmt.Errorf("%w %q: %w", ErrUnsupportedDigest, expected, err) + } + return "", sum.SRI(), nil +} + +// verifyDigest checks body against expected, an OCI-style digest. A digest +// whose algorithm can't be computed is an ErrUnsupportedDigest, and one that +// doesn't match is an ErrArtifactDigestMismatch. +func verifyDigest(expected string, body []byte) error { + d, err := digest.Parse(expected) + if err != nil { + return fmt.Errorf("%w %q: %w", ErrUnsupportedDigest, expected, err) + } + if actual := d.Algorithm().FromBytes(body); actual != d { + return fmt.Errorf("%w: expected %s, got %s", ErrArtifactDigestMismatch, d, actual) + } + return nil } // GetOrFetchArtifactFromURLWithIntegrity retrieves an artifact and verifies a @@ -1851,14 +2561,19 @@ func (p *Proxy) getOrFetchArtifactFromURL(ctx context.Context, ecosystem, name, } func (p *Proxy) getOrFetchArtifactFromURLWithCachePURLs(ctx context.Context, ecosystem, name, version, filename, pkgPURL, versionPURL, downloadURL string, headers http.Header, upstreamHash, declared string) (*CacheResult, error) { - // Some protocols use qualified cache keys. Check their package identity too. + // Some protocols use qualified cache keys. Check their package identity + // too, and the cache key itself for those, such as Swift, whose name has + // no PURL of its own. if p.versionDenied(ecosystem, name, version) { return nil, fmt.Errorf("%w: %s", ErrVersionDenied, canonicalVersionPURL(ecosystem, name, version)) } + if p.Denylist.Denied(versionPURL) { + return nil, fmt.Errorf("%w: %s", ErrVersionDenied, versionPURL) + } if p.StreamArtifacts { return p.streamFromUpstream(ctx, ecosystem, name, version, filename, versionPURL, downloadURL, upstreamHash, declared, func(fetchCtx context.Context) (*fetch.Artifact, error) { - return p.Fetcher.FetchWithHeaders(fetchCtx, downloadURL, headers) + return p.fetchUpstream(fetchCtx, downloadURL, headers) }) } if cached, err := p.getCachedArtifactWithUpstreamHash(ctx, pkgPURL, versionPURL, filename, upstreamHash); err != nil { @@ -1866,7 +2581,7 @@ func (p *Proxy) getOrFetchArtifactFromURLWithCachePURLs(ctx context.Context, eco } else if cached != nil { return cached, nil } - metrics.RecordCacheMiss(ecosystem) + metrics.RecordArtifactCacheMiss(ecosystem) return p.coalescedFetchFromURL(ctx, ecosystem, name, version, filename, pkgPURL, versionPURL, downloadURL, headers, upstreamHash, declared) } @@ -1884,6 +2599,33 @@ func (p *Proxy) coalescedFetchFromURL(ctx context.Context, ecosystem, name, vers }) } +// cacheStoredCopy caches a copy of the object stored at source under a new +// name, instead of downloading the same bytes again. It shares the coalescing +// key a download from upstreamURL would use, so the two never run at once. +func (p *Proxy) cacheStoredCopy(ctx context.Context, ecosystem, name, version, filename, upstreamURL, upstreamHash string, source *database.StoredContent) (*CacheResult, error) { + pkgPURL, versionPURL, err := packagePURLStrings(ecosystem, name, version) + if err != nil { + return nil, err + } + if p.versionDenied(ecosystem, name, version) || p.Denylist.Denied(versionPURL) { + return nil, fmt.Errorf("%w: %s", ErrVersionDenied, versionPURL) + } + key := artifactCoalesceKey(versionPURL, filename, upstreamURL, upstreamHash, "") + recheck := func() (artifacts.Artifact, string, bool) { + return p.cachedArtifactRecord(pkgPURL, versionPURL, filename, upstreamHash) + } + return p.coalesceFetch(ctx, key, recheck, func(fetchCtx context.Context) (artifacts.Artifact, string, error) { + body, err := p.Storage.Open(fetchCtx, source.StoragePath) + if err != nil { + return artifacts.Artifact{}, "", fmt.Errorf("opening stored copy: %w", err) + } + p.Logger.Info("caching a stored copy", "ecosystem", ecosystem, "name", name, "version", version, + "source", source.StoragePath) + return p.storeArtifact(fetchCtx, ecosystem, name, version, filename, pkgPURL, versionPURL, upstreamURL, upstreamHash, "", + &fetch.Artifact{Body: body, Size: source.Size, ContentType: source.ContentType.String}) + }) +} + // getCachedArtifactWithUpstreamHash returns a cached artifact whose recorded // content hash matches the checksum the upstream currently declares for it. // This detects an upstream re-publishing under the same version, which the @@ -1905,6 +2647,39 @@ func (p *Proxy) getCachedArtifactWithUpstreamHash(ctx context.Context, pkgPURL, return nil, nil } +// refetchArtifactFromURL fetches a file upstream replaces in place, which +// a cached copy can't stand in for while upstream answers. The new copy +// replaces the cached one only once it is stored, and the cached one is +// served when the fetch fails for any reason but the file being missing or +// blocked. Concurrent callers share one fetch. +func (p *Proxy) refetchArtifactFromURL(ctx context.Context, ecosystem, name, version, filename, downloadURL string) (*CacheResult, error) { + pkgPURL, versionPURL, err := packagePURLStrings(ecosystem, name, version) + if err != nil { + return nil, err + } + // Streaming never serves a cached copy, and a denied version is refused + // there. + if p.StreamArtifacts || p.versionDenied(ecosystem, name, version) || p.Denylist.Denied(versionPURL) { + return p.getOrFetchArtifactFromURL(ctx, ecosystem, name, version, filename, downloadURL, nil, "", "") + } + metrics.RecordArtifactCacheMiss(ecosystem) + key := artifactCoalesceKey(versionPURL, filename, downloadURL, "", "") + noRecheck := func() (artifacts.Artifact, string, bool) { return artifacts.Artifact{}, "", false } + result, err := p.coalesceFetch(ctx, key, noRecheck, func(fetchCtx context.Context) (artifacts.Artifact, string, error) { + return p.fetchAndCacheFromURL(fetchCtx, ecosystem, name, version, filename, pkgPURL, versionPURL, downloadURL, nil, "", "") + }) + if err == nil || errors.Is(err, ErrUpstreamNotFound) || errors.Is(err, ErrArtifactBlocked) || ctx.Err() != nil { + return result, err + } + cached, cacheErr := p.checkCache(ctx, pkgPURL, versionPURL, filename) + if cacheErr != nil || cached == nil { + return nil, err + } + p.Logger.Warn("upstream fetch failed, serving cached copy", + "purl", versionPURL, "filename", filename, "error", err) + return cached, nil +} + // discardStaleArtifact clears the cached entry when its digest disagrees with // upstreamHash, queueing its object for deletion. It runs under the coalescing // key, after the recheck, so an entry a previous fetch refreshed is kept. @@ -1926,14 +2701,14 @@ func (p *Proxy) discardStaleArtifact(pkgPURL, versionPURL, filename, upstreamHas } func (p *Proxy) fetchAndCacheFromURL(ctx context.Context, ecosystem, name, version, filename, pkgPURL, versionPURL, downloadURL string, headers http.Header, upstreamHash, declared string) (artifacts.Artifact, string, error) { - if err := p.RateLimits.Held(downloadURL); err != nil { + if err := p.upstreamHeld(downloadURL); err != nil { return artifacts.Artifact{}, "", err } p.Logger.Info("fetching from upstream", "ecosystem", ecosystem, "name", name, "version", version, "url", downloadURL) fetchStart := time.Now() - artifact, err := p.Fetcher.FetchWithHeaders(ctx, downloadURL, headers) + artifact, err := p.fetchUpstream(ctx, downloadURL, headers) metrics.RecordUpstreamFetch(ecosystem, time.Since(fetchStart)) if err != nil { metrics.RecordUpstreamError(ecosystem, "fetch_failed", metrics.FailureDetail{ @@ -1944,7 +2719,131 @@ func (p *Proxy) fetchAndCacheFromURL(ctx context.Context, ecosystem, name, versi return artifacts.Artifact{}, "", fmt.Errorf("fetching from upstream: %w", err) } - return p.storeArtifact(ctx, ecosystem, name, version, filename, pkgPURL, versionPURL, downloadURL, upstreamHash, declared, artifact) + return p.storeFetched(ctx, ecosystem, name, version, filename, pkgPURL, versionPURL, downloadURL, upstreamHash, declared, artifact) +} + +type upstreamLastModifiedKey struct{} + +// WithUpstreamLastModified returns a context under which an artifact fetched +// from upstream reports its Last-Modified to fn, so a handler can learn a +// version's publish time from the download itself rather than with a +// request of its own. fn is not called for a cache hit, or when the +// response has no usable Last-Modified. +func WithUpstreamLastModified(ctx context.Context, fn func(time.Time)) context.Context { + return context.WithValue(ctx, upstreamLastModifiedKey{}, fn) +} + +// observedFetcher is the part of fetch.Fetcher and its circuit breaker that +// reports response headers. +type observedFetcher interface { + FetchObservedWithHeaders(ctx context.Context, url string, headers http.Header) (*fetch.ObservedArtifact, error) +} + +type signedDownloadKey struct{} + +// signedDownload is a download URL carrying a signature, and the URL without +// its query that stands for it everywhere but the request itself. size, when +// not negative, is the exact size the download must have. +type signedDownload struct { + signed, recorded string + size int64 +} + +// errDownloadSize is a download larger or smaller than the size it was +// expected to have. +var errDownloadSize = errors.New("download does not have the expected size") + +// withSignedDownload returns a context under which a fetch of the returned +// URL requests signedURL instead. The returned URL, signedURL without its +// query and fragment, is what is logged, recorded with the artifact and used +// to coalesce fetches, so a signature that grants access to the object +// stays out of logs and the database. A download of other than size bytes +// is cut off with errDownloadSize, unless size is negative. +func withSignedDownload(ctx context.Context, signedURL string, size int64) (context.Context, string) { + u, err := url.Parse(signedURL) + if err != nil { + return ctx, signedURL + } + u.User = nil + u.RawQuery, u.ForceQuery = "", false + u.Fragment, u.RawFragment = "", "" + recorded := u.String() + return context.WithValue(ctx, signedDownloadKey{}, signedDownload{signed: signedURL, recorded: recorded, size: size}), recorded +} + +// redactedFetchError is a fetch error whose text names the recorded URL +// rather than the signed one. +type redactedFetchError struct { + err error + download signedDownload +} + +func (e *redactedFetchError) Error() string { + return strings.ReplaceAll(e.err.Error(), e.download.signed, e.download.recorded) +} + +func (e *redactedFetchError) Unwrap() error { return e.err } + +// fetchUpstream fetches downloadURL, or the signed URL ctx gives for it, +// reporting its Last-Modified when ctx asks for it. +func (p *Proxy) fetchUpstream(ctx context.Context, downloadURL string, headers http.Header) (*fetch.Artifact, error) { + download, ok := ctx.Value(signedDownloadKey{}).(signedDownload) + if !ok || download.recorded != downloadURL { + return p.fetchUpstreamURL(ctx, downloadURL, headers) + } + artifact, err := p.fetchUpstreamURL(ctx, download.signed, headers) + if err != nil { + return nil, &redactedFetchError{err: err, download: download} + } + if download.size < 0 { + return artifact, nil + } + if artifact.Size >= 0 && artifact.Size != download.size { + _ = artifact.Body.Close() + return nil, fmt.Errorf("%w: upstream announced %d bytes, want %d", errDownloadSize, artifact.Size, download.size) + } + artifact.Body = &exactSizeBody{ReadCloser: artifact.Body, left: download.size} + return artifact, nil +} + +// exactSizeBody fails a body that turns out longer or shorter than left +// bytes, without reading more than one byte past it. +type exactSizeBody struct { + io.ReadCloser + left int64 +} + +func (b *exactSizeBody) Read(p []byte) (int, error) { + if int64(len(p)) > b.left+1 { + p = p[:b.left+1] + } + n, err := b.ReadCloser.Read(p) + b.left -= int64(n) + switch { + case b.left < 0: + return n, fmt.Errorf("%w: upstream sent more bytes", errDownloadSize) + case errors.Is(err, io.EOF) && b.left > 0: + return n, fmt.Errorf("%w: upstream sent %d bytes too few", errDownloadSize, b.left) + } + return n, err +} + +func (p *Proxy) fetchUpstreamURL(ctx context.Context, downloadURL string, headers http.Header) (*fetch.Artifact, error) { + report, _ := ctx.Value(upstreamLastModifiedKey{}).(func(time.Time)) + observer, ok := p.Fetcher.(observedFetcher) + if report == nil || !ok { + return p.Fetcher.FetchWithHeaders(ctx, downloadURL, headers) + } + observed, err := observer.FetchObservedWithHeaders(ctx, downloadURL, headers) + if err != nil { + return nil, err + } + if observed.Observation != nil { + if t, err := http.ParseTime(observed.Observation.Headers.Get(headerLastModified)); err == nil { + report(t) + } + } + return observed.Artifact, nil } // streamFromUpstream fetches an artifact when StreamArtifacts is set and hands its @@ -1956,7 +2855,7 @@ func (p *Proxy) fetchAndCacheFromURL(ctx context.Context, ecosystem, name, versi // after the bytes have been sent, and an unterminated chunked response is the // only way left to make the client reject them (see serveArtifact). func (p *Proxy) streamFromUpstream(ctx context.Context, ecosystem, name, version, filename, versionPURL, upstreamURL, upstreamHash, declared string, fetchArtifact func(context.Context) (*fetch.Artifact, error)) (*CacheResult, error) { - if err := p.RateLimits.Held(upstreamURL); err != nil { + if err := p.upstreamHeld(upstreamURL); err != nil { return nil, err } p.Logger.Info("streaming from upstream", diff --git a/internal/handler/handler_bench_test.go b/internal/handler/handler_bench_test.go index cdbb524..fdcc935 100644 --- a/internal/handler/handler_bench_test.go +++ b/internal/handler/handler_bench_test.go @@ -136,6 +136,32 @@ func BenchmarkReadMetadata(b *testing.B) { } } +// BenchmarkReadMetadataSized reads a large document with and without its +// size known, as for a cached document or a response with Content-Length. +func BenchmarkReadMetadataSized(b *testing.B) { + const size = 64 << 20 + payload := bytes.Repeat([]byte("x"), size) + proxy := &Proxy{MetadataMaxSize: 100 << 20} + for _, bench := range []struct { + name string + hint int64 + }{ + {"unknown size", -1}, + {"known size", size}, + } { + b.Run(bench.name, func(b *testing.B) { + b.SetBytes(size) + b.ReportAllocs() + for b.Loop() { + data, err := proxy.ReadMetadataSized(bytes.NewReader(payload), bench.hint) + if err != nil || len(data) != size { + b.Fatalf("read %d bytes, %v", len(data), err) + } + } + }) + } +} + func BenchmarkArtifactPURLConstruction(b *testing.B) { for _, tc := range []struct { name string @@ -186,7 +212,7 @@ func newBenchmarkNPMServer(b *testing.B) *benchmarkNPMServer { b.Cleanup(func() { _ = store.Close() }) content := bytes.Repeat([]byte("x"), benchmarkArtifactSize) - storagePath := storage.ArtifactPath("npm", "", "lodash", "4.17.21", "lodash-4.17.21.tgz") + storagePath := "npm/lodash/4.17.21/lodash-4.17.21.tgz" size, hash, err := store.Store(ctx, storagePath, bytes.NewReader(content)) if err != nil { b.Fatalf("store artifact: %v", err) diff --git a/internal/handler/handler_test.go b/internal/handler/handler_test.go index ffc0d5f..ed56b63 100644 --- a/internal/handler/handler_test.go +++ b/internal/handler/handler_test.go @@ -13,6 +13,7 @@ import ( "slices" "strings" "sync" + "sync/atomic" "testing" "time" @@ -38,6 +39,8 @@ type mockStorage struct { signedURL string signErr error seekable bool + stores int + opens int } func newMockStorage() *mockStorage { @@ -55,12 +58,14 @@ func (s *mockStorage) Store(_ context.Context, path string, r io.Reader) (int64, return 0, "", err } s.files[path] = data + s.stores++ return int64(len(data)), sha256Hex(string(data)), nil } func (s *mockStorage) Open(_ context.Context, path string) (io.ReadCloser, error) { s.mu.Lock() defer s.mu.Unlock() + s.opens++ if s.openErr != nil { return nil, s.openErr } @@ -74,6 +79,9 @@ func (s *mockStorage) Open(_ context.Context, path string) (io.ReadCloser, error return io.NopCloser(bytes.NewReader(data)), nil } +// ReadsSeekable reports what Open returns, as storage.Blob does. +func (s *mockStorage) ReadsSeekable() bool { return s.seekable } + type mockSeekableReadCloser struct { *bytes.Reader } @@ -238,7 +246,7 @@ func seedPackage(t testing.TB, db *database.DB, store *mockStorage, ecosystem, n t.Fatalf("failed to upsert version: %v", err) } - storagePath := storage.ArtifactPath(ecosystem, "", name, version, filename) + storagePath := ecosystem + "/" + name + "/" + version + "/" + filename store.files[storagePath] = []byte(content) sharedArtifact := testArtifact(content, versionPURL, filename, "application/octet-stream") @@ -415,7 +423,7 @@ func assertMalformedCacheRejected(t *testing.T, malformedHash, malformedIntegrit if artifact.StoragePath.Valid { t.Error("unusable cache record retained its storage path") } - assertQueuedForDeletion(t, db, storage.ArtifactPath("npm", "", packageName, version, filename)) + assertQueuedForDeletion(t, db, "npm/"+packageName+"/"+version+"/"+filename) } // TestCorruptCachedArtifactIsQueuedForDeletion streams cached bytes that no @@ -425,7 +433,7 @@ func assertMalformedCacheRejected(t *testing.T, malformedHash, malformedIntegrit func TestCorruptCachedArtifactIsQueuedForDeletion(t *testing.T) { proxy, db, store, _ := setupTestProxy(t) seedPackage(t, db, store, "npm", "corrupt", "1.0.0", "corrupt-1.0.0.tgz", "cached content") - storagePath := storage.ArtifactPath("npm", "", "corrupt", "1.0.0", "corrupt-1.0.0.tgz") + storagePath := "npm/corrupt/1.0.0/corrupt-1.0.0.tgz" store.files[storagePath] = []byte("tampered bytes") result, err := proxy.GetCachedArtifact(context.Background(), "npm", "corrupt", "1.0.0", "corrupt-1.0.0.tgz") @@ -440,6 +448,69 @@ func TestCorruptCachedArtifactIsQueuedForDeletion(t *testing.T) { assertQueuedForDeletion(t, db, storagePath) } +// TestCachedArtifactVerifiedByContentHash checks that a cache hit is verified +// against the recorded content hash only. The version's native integrity is +// one value per version and was checked when the bytes were stored; a stale +// or foreign value there must not discard an artifact whose bytes still +// match their SHA-256. +func TestCachedArtifactVerifiedByContentHash(t *testing.T) { + proxy, db, store, _ := setupTestProxy(t) + seedPackage(t, db, store, "npm", "hashed", "1.0.0", "hashed-1.0.0.tgz", "cached content") + setVersionIntegrity(t, db, "npm", "hashed", "1.0.0", sha512SRI("other bytes")) + + result, err := proxy.GetCachedArtifact(context.Background(), "npm", "hashed", "1.0.0", "hashed-1.0.0.tgz") + if err != nil || result == nil { + t.Fatalf("GetCachedArtifact = %v, %v", result, err) + } + body, err := io.ReadAll(result.Reader) + _ = result.Reader.Close() + if err != nil || string(body) != "cached content" { + t.Fatalf("read %q, %v; want the cached bytes", body, err) + } + artifact, err := db.GetArtifact("pkg:npm/hashed@1.0.0", "hashed-1.0.0.tgz") + if err != nil || artifact == nil || !artifact.StoragePath.Valid { + t.Errorf("record = %+v (err %v), want it kept", artifact, err) + } +} + +// TestCachedArtifactWithoutContentHashChecksNativeIntegrity checks that a +// record without a content hash is still verified against the native +// integrity, which is then the only digest there is. +func TestCachedArtifactWithoutContentHashChecksNativeIntegrity(t *testing.T) { + proxy, db, store, _ := setupTestProxy(t) + seedPackage(t, db, store, "npm", "nohash", "1.0.0", "nohash-1.0.0.tgz", "cached content") + setVersionIntegrity(t, db, "npm", "nohash", "1.0.0", sha512SRI("other bytes")) + artifact, err := db.GetArtifact("pkg:npm/nohash@1.0.0", "nohash-1.0.0.tgz") + if err != nil { + t.Fatal(err) + } + artifact.ContentHash = sql.NullString{} + if err := db.UpsertArtifact(artifact); err != nil { + t.Fatal(err) + } + + result, err := proxy.GetCachedArtifact(context.Background(), "npm", "nohash", "1.0.0", "nohash-1.0.0.tgz") + if err != nil || result == nil { + t.Fatalf("GetCachedArtifact = %v, %v", result, err) + } + _, err = io.ReadAll(result.Reader) + _ = result.Reader.Close() + if !errors.Is(err, ErrArtifactDigestMismatch) { + t.Fatalf("read error = %v, want ErrArtifactDigestMismatch", err) + } +} + +func setVersionIntegrity(t *testing.T, db *database.DB, ecosystem, name, version, integrity string) { + t.Helper() + if err := db.UpsertVersion(&database.Version{ + PURL: purl.MakePURLString(ecosystem, name, version), + PackagePURL: purl.MakePURLString(ecosystem, name, ""), + Integrity: sql.NullString{String: integrity, Valid: true}, + }); err != nil { + t.Fatal(err) + } +} + // assertQueuedForDeletion fails unless path waits in the pending delete queue. func assertQueuedForDeletion(t *testing.T, db *database.DB, path string) { t.Helper() @@ -451,7 +522,7 @@ func assertQueuedForDeletion(t *testing.T, db *database.DB, path string) { func TestGetOrFetchArtifact_CacheMiss_NoPackage(t *testing.T) { proxy, _, _, fetcher := setupTestProxy(t) - missesBefore := testutil.ToFloat64(metrics.CacheMisses.WithLabelValues("npm")) + missesBefore := testutil.ToFloat64(metrics.CacheMisses.WithLabelValues("npm", metrics.CacheKindArtifact)) // The resolver will fail because "nonexistent" isn't a real package, // but we're testing that it tries to fetch (doesn't return from cache). @@ -461,7 +532,7 @@ func TestGetOrFetchArtifact_CacheMiss_NoPackage(t *testing.T) { if err == nil { t.Fatal("expected error for uncached package") } - missesAfter := testutil.ToFloat64(metrics.CacheMisses.WithLabelValues("npm")) + missesAfter := testutil.ToFloat64(metrics.CacheMisses.WithLabelValues("npm", metrics.CacheKindArtifact)) if diff := missesAfter - missesBefore; diff != 1 { t.Errorf("cache misses delta = %.0f, want 1", diff) } @@ -905,7 +976,7 @@ func newRangeTestResult(payload string) *CacheResult { func TestGetOrFetchArtifactFromURL_CacheHit(t *testing.T) { proxy, db, store, fetcher := setupTestProxy(t) seedPackage(t, db, store, "pypi", "requests", "2.28.0", "requests-2.28.0.tar.gz", "pypi content") - missesBefore := testutil.ToFloat64(metrics.CacheMisses.WithLabelValues("pypi")) + missesBefore := testutil.ToFloat64(metrics.CacheMisses.WithLabelValues("pypi", metrics.CacheKindArtifact)) result, err := proxy.GetOrFetchArtifactFromURL(context.Background(), "pypi", "requests", "2.28.0", "requests-2.28.0.tar.gz", "https://pypi.org/files/requests-2.28.0.tar.gz") if err != nil { @@ -919,7 +990,7 @@ func TestGetOrFetchArtifactFromURL_CacheHit(t *testing.T) { if fetcher.fetchCalled { t.Error("fetcher should not be called on cache hit") } - missesAfter := testutil.ToFloat64(metrics.CacheMisses.WithLabelValues("pypi")) + missesAfter := testutil.ToFloat64(metrics.CacheMisses.WithLabelValues("pypi", metrics.CacheKindArtifact)) if diff := missesAfter - missesBefore; diff != 0 { t.Errorf("cache misses delta = %.0f, want 0", diff) } @@ -927,7 +998,7 @@ func TestGetOrFetchArtifactFromURL_CacheHit(t *testing.T) { func TestGetOrFetchArtifactFromURL_CacheMiss(t *testing.T) { proxy, db, store, fetcher := setupTestProxy(t) - missesBefore := testutil.ToFloat64(metrics.CacheMisses.WithLabelValues("pypi")) + missesBefore := testutil.ToFloat64(metrics.CacheMisses.WithLabelValues("pypi", metrics.CacheKindArtifact)) fetchesBefore := histogramSampleCount(t, metrics.UpstreamFetchDuration.WithLabelValues("pypi")) writesBefore := histogramSampleCount(t, metrics.StorageOperationDuration.WithLabelValues("write")) readsBefore := histogramSampleCount(t, metrics.StorageOperationDuration.WithLabelValues("read")) @@ -975,7 +1046,7 @@ func TestGetOrFetchArtifactFromURL_CacheMiss(t *testing.T) { if _, ok := store.files[storagePath]; !ok { t.Error("artifact was not stored in storage") } - missesAfter := testutil.ToFloat64(metrics.CacheMisses.WithLabelValues("pypi")) + missesAfter := testutil.ToFloat64(metrics.CacheMisses.WithLabelValues("pypi", metrics.CacheKindArtifact)) if diff := missesAfter - missesBefore; diff != 1 { t.Errorf("cache misses delta = %.0f, want 1", diff) } @@ -990,17 +1061,7 @@ func TestGetOrFetchArtifactFromURL_CacheMiss(t *testing.T) { } } -// isolateRecentFailures empties the process-wide failure history for the -// test and again when it ends, so neither earlier tests nor repeated runs -// reach its assertions. -func isolateRecentFailures(t *testing.T) { - t.Helper() - metrics.ResetRecentFailures() - t.Cleanup(metrics.ResetRecentFailures) -} - func TestGetOrFetchArtifactFromURL_FetchError(t *testing.T) { - isolateRecentFailures(t) proxy, _, _, fetcher := setupTestProxy(t) fetcher.fetchErr = errors.New("connection refused") errorsBefore := testutil.ToFloat64(metrics.UpstreamErrors.WithLabelValues("pypi", "fetch_failed")) @@ -1016,14 +1077,13 @@ func TestGetOrFetchArtifactFromURL_FetchError(t *testing.T) { t.Errorf("upstream errors delta = %.0f, want 1", diff) } recent := metrics.RecentFailures("proxy_upstream_errors_total", map[string]string{"ecosystem": "pypi", "error_type": "fetch_failed"}) - if len(recent) != 1 || recent[0].PURL != "pkg:pypi/fail@1.0.0" || + if len(recent) == 0 || recent[0].PURL != "pkg:pypi/fail@1.0.0" || recent[0].URL != "https://pypi.org/files/fail-1.0.0.tar.gz" || recent[0].Error != "connection refused" { - t.Errorf("upstream failures = %+v, want one: the failed package, its URL and the error", recent) + t.Errorf("upstream failures = %+v, want the newest failure to contain the failed package, its URL and the error", recent) } } func TestGetOrFetchArtifactFromURL_StoreError(t *testing.T) { - isolateRecentFailures(t) proxy, _, store, fetcher := setupTestProxy(t) store.storeErr = errors.New("disk full") errorsBefore := testutil.ToFloat64(metrics.StorageErrors.WithLabelValues("write")) @@ -1043,9 +1103,9 @@ func TestGetOrFetchArtifactFromURL_StoreError(t *testing.T) { t.Errorf("storage errors delta = %.0f, want 1", diff) } recent := metrics.RecentFailures("proxy_storage_errors_total", map[string]string{"operation": "write"}) - if len(recent) != 1 || recent[0].PURL != "pkg:pypi/fail@1.0.0" || recent[0].Filename != "fail-1.0.0.tar.gz" || + if len(recent) == 0 || recent[0].PURL != "pkg:pypi/fail@1.0.0" || recent[0].Filename != "fail-1.0.0.tar.gz" || recent[0].Path == "" || recent[0].Error != "disk full" { - t.Errorf("storage failures = %+v, want one: the failed package, its storage path and the error", recent) + t.Errorf("storage failures = %+v, want the newest failure to contain the failed package, its storage path and the error", recent) } } @@ -1305,8 +1365,10 @@ func TestProxyCached_NoValidators_OmitsHeaders(t *testing.T) { } func TestFetchOrCacheMetadata_TTL_ServesFreshFromCache(t *testing.T) { - hitsBefore := testutil.ToFloat64(metrics.CacheHits.WithLabelValues("test")) - missesBefore := testutil.ToFloat64(metrics.CacheMisses.WithLabelValues("test")) + hitsBefore := testutil.ToFloat64(metrics.CacheHits.WithLabelValues("test", metrics.CacheKindMetadata)) + missesBefore := testutil.ToFloat64(metrics.CacheMisses.WithLabelValues("test", metrics.CacheKindMetadata)) + artifactHitsBefore := testutil.ToFloat64(metrics.CacheHits.WithLabelValues("test", metrics.CacheKindArtifact)) + servedBefore := testutil.ToFloat64(metrics.MetadataServedBytes.WithLabelValues("test")) upstreamHits := 0 upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { upstreamHits++ @@ -1333,10 +1395,10 @@ func TestFetchOrCacheMetadata_TTL_ServesFreshFromCache(t *testing.T) { if upstreamHits != 1 { t.Fatalf("expected 1 upstream hit, got %d", upstreamHits) } - if diff := testutil.ToFloat64(metrics.CacheMisses.WithLabelValues("test")) - missesBefore; diff != 1 { + if diff := testutil.ToFloat64(metrics.CacheMisses.WithLabelValues("test", metrics.CacheKindMetadata)) - missesBefore; diff != 1 { t.Errorf("cache misses delta after first request = %.0f, want 1", diff) } - if diff := testutil.ToFloat64(metrics.CacheHits.WithLabelValues("test")) - hitsBefore; diff != 0 { + if diff := testutil.ToFloat64(metrics.CacheHits.WithLabelValues("test", metrics.CacheKindMetadata)) - hitsBefore; diff != 0 { t.Errorf("cache hits delta after first request = %.0f, want 0", diff) } @@ -1351,16 +1413,22 @@ func TestFetchOrCacheMetadata_TTL_ServesFreshFromCache(t *testing.T) { if upstreamHits != 1 { t.Errorf("expected upstream to still be hit only once, got %d", upstreamHits) } - if diff := testutil.ToFloat64(metrics.CacheHits.WithLabelValues("test")) - hitsBefore; diff != 1 { + if diff := testutil.ToFloat64(metrics.CacheHits.WithLabelValues("test", metrics.CacheKindMetadata)) - hitsBefore; diff != 1 { t.Errorf("cache hits delta after second request = %.0f, want 1", diff) } - if diff := testutil.ToFloat64(metrics.CacheMisses.WithLabelValues("test")) - missesBefore; diff != 1 { + if diff := testutil.ToFloat64(metrics.CacheMisses.WithLabelValues("test", metrics.CacheKindMetadata)) - missesBefore; diff != 1 { t.Errorf("cache misses delta after second request = %.0f, want 1", diff) } + if diff := testutil.ToFloat64(metrics.MetadataServedBytes.WithLabelValues("test")) - servedBefore; diff != float64(len(body)) { + t.Errorf("metadata served bytes delta = %.0f, want %d (only the cached response)", diff, len(body)) + } + if diff := testutil.ToFloat64(metrics.CacheHits.WithLabelValues("test", metrics.CacheKindArtifact)) - artifactHitsBefore; diff != 0 { + t.Errorf("artifact cache hits delta = %.0f, want 0 for a metadata lookup", diff) + } } func TestFetchOrCacheMetadata_TTL_Zero_AlwaysRevalidates(t *testing.T) { - missesBefore := testutil.ToFloat64(metrics.CacheMisses.WithLabelValues("test")) + missesBefore := testutil.ToFloat64(metrics.CacheMisses.WithLabelValues("test", metrics.CacheKindMetadata)) upstreamHits := 0 upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { upstreamHits++ @@ -1389,7 +1457,7 @@ func TestFetchOrCacheMetadata_TTL_Zero_AlwaysRevalidates(t *testing.T) { if upstreamHits != 2 { t.Errorf("expected 2 upstream hits with TTL=0, got %d", upstreamHits) } - missesAfter := testutil.ToFloat64(metrics.CacheMisses.WithLabelValues("test")) + missesAfter := testutil.ToFloat64(metrics.CacheMisses.WithLabelValues("test", metrics.CacheKindMetadata)) if diff := missesAfter - missesBefore; diff != 2 { t.Errorf("cache misses delta = %.0f, want 2", diff) } @@ -1407,16 +1475,16 @@ func TestFetchOrCacheMetadata_CacheDisabledDoesNotRecordMetrics(t *testing.T) { proxy, _, _, _ := setupTestProxy(t) proxy.HTTPClient = upstream.Client() - hitsBefore := testutil.ToFloat64(metrics.CacheHits.WithLabelValues(ecosystem)) - missesBefore := testutil.ToFloat64(metrics.CacheMisses.WithLabelValues(ecosystem)) + hitsBefore := testutil.ToFloat64(metrics.CacheHits.WithLabelValues(ecosystem, metrics.CacheKindMetadata)) + missesBefore := testutil.ToFloat64(metrics.CacheMisses.WithLabelValues(ecosystem, metrics.CacheKindMetadata)) _, _, err := proxy.FetchOrCacheMetadata(context.Background(), ecosystem, "pkg", upstream.URL+"/pkg") if err != nil { t.Fatalf("fetch metadata: %v", err) } - hitsAfter := testutil.ToFloat64(metrics.CacheHits.WithLabelValues(ecosystem)) - missesAfter := testutil.ToFloat64(metrics.CacheMisses.WithLabelValues(ecosystem)) + hitsAfter := testutil.ToFloat64(metrics.CacheHits.WithLabelValues(ecosystem, metrics.CacheKindMetadata)) + missesAfter := testutil.ToFloat64(metrics.CacheMisses.WithLabelValues(ecosystem, metrics.CacheKindMetadata)) if diff := hitsAfter - hitsBefore; diff != 0 { t.Errorf("cache hits delta = %.0f, want 0", diff) } @@ -1517,3 +1585,54 @@ func TestCanonicalPackagePURLMatchesConfig(t *testing.T) { }) } } + +func TestProxyCachedRecordsUpstreamURL(t *testing.T) { + proxy, upstream := setupCachedProxy(t, `"abc123"`, "") + req := httptest.NewRequest(http.MethodGet, "/test", nil) + proxy.ProxyCached(httptest.NewRecorder(), req, upstream.URL+"/test", "test-eco", "url-key") + + entry, err := proxy.DB.GetMetadataCache("test-eco", "url-key") + if err != nil || entry == nil { + t.Fatalf("GetMetadataCache: %+v, %v", entry, err) + } + if entry.UpstreamURL.String != upstream.URL+"/test" { + t.Errorf("upstream_url = %q, want %q", entry.UpstreamURL.String, upstream.URL+"/test") + } +} + +// A row cached before upstream URLs were recorded gets its URL on the next +// revalidation, even when upstream answers 304. +func TestProxyCachedRecordsUpstreamURLOnNotModified(t *testing.T) { + var notModified atomic.Int32 + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("ETag", `"v1"`) + if r.Header.Get("If-None-Match") == `"v1"` { + notModified.Add(1) + w.WriteHeader(http.StatusNotModified) + return + } + _, _ = w.Write([]byte(`{"ok":true}`)) + })) + t.Cleanup(upstream.Close) + proxy, _, _, _ := setupTestProxy(t) + proxy.CacheMetadata = true + proxy.HTTPClient = upstream.Client() + + proxy.ProxyCached(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/test", nil), upstream.URL+"/test", "test-eco", "url-304-key") + if _, err := proxy.DB.Exec("UPDATE metadata_cache SET upstream_url = NULL"); err != nil { + t.Fatal(err) + } + + w := httptest.NewRecorder() + proxy.ProxyCached(w, httptest.NewRequest(http.MethodGet, "/test", nil), upstream.URL+"/test", "test-eco", "url-304-key") + if w.Code != http.StatusOK || notModified.Load() != 1 { + t.Fatalf("status = %d, upstream 304s = %d; want 200 after one 304", w.Code, notModified.Load()) + } + entry, err := proxy.DB.GetMetadataCache("test-eco", "url-304-key") + if err != nil || entry == nil { + t.Fatalf("GetMetadataCache: %+v, %v", entry, err) + } + if entry.UpstreamURL.String != upstream.URL+"/test" { + t.Errorf("upstream_url after a 304 = %q, want %q", entry.UpstreamURL.String, upstream.URL+"/test") + } +} diff --git a/internal/handler/head_cache_hit_test.go b/internal/handler/head_cache_hit_test.go new file mode 100644 index 0000000..3bcdf6c --- /dev/null +++ b/internal/handler/head_cache_hit_test.go @@ -0,0 +1,88 @@ +package handler + +import ( + "context" + "fmt" + "maps" + "net/http" + "net/http/httptest" + "testing" + + "github.com/git-pkgs/purl" +) + +// A HEAD on a cache hit is answered from the artifact's database record. It +// must not open the stored object (a GET on S3 or GCS), and its headers must +// be the ones the GET sends. +func TestHeadCacheHitSkipsStorageOpen(t *testing.T) { + const digest = "sha256:abc123def456abc123def456abc123def456abc123def456abc123def456abcd" + for _, seekable := range []bool{false, true} { + t.Run(fmt.Sprintf("seekable=%t", seekable), func(t *testing.T) { + proxy, db, store, fetcher := setupTestProxy(t) + store.seekable = seekable + seedPackage(t, db, store, "oci", "library/nginx", digest, digest, "cached blob") + h := &ContainerHandler{ + proxy: proxy, + registryURL: "https://registry.invalid", + proxyURL: "http://localhost:8080", + } + target := "/library/nginx/blobs/" + digest + + get := httptest.NewRecorder() + h.Routes().ServeHTTP(get, httptest.NewRequest(http.MethodGet, target, nil)) + if get.Code != http.StatusOK || get.Body.String() != "cached blob" { + t.Fatalf("GET: status %d, body %q", get.Code, get.Body.String()) + } + opensAfterGet := store.opens + + req := httptest.NewRequest(http.MethodHead, target, nil) + req = req.WithContext(ServingHead(req.Context())) + head := httptest.NewRecorder() + h.Routes().ServeHTTP(head, req) + + if head.Code != http.StatusOK { + t.Fatalf("HEAD: status %d, body %q", head.Code, head.Body.String()) + } + if got := store.opens - opensAfterGet; got != 0 { + t.Errorf("HEAD opened the stored object %d times, want 0", got) + } + if head.Body.Len() != 0 { + t.Errorf("HEAD body length = %d, want 0", head.Body.Len()) + } + if !maps.EqualFunc(get.Header(), head.Header(), func(a, b []string) bool { + return fmt.Sprint(a) == fmt.Sprint(b) + }) { + t.Errorf("HEAD headers differ from GET:\n GET %v\n HEAD %v", get.Header(), head.Header()) + } + if got := get.Header().Get("Accept-Ranges") == "bytes"; got != seekable { + t.Errorf("GET Accept-Ranges set = %t, want %t", got, seekable) + } + if fetcher.fetchCalled { + t.Error("fetcher called on a cache hit") + } + + // A HEAD still counts as a hit, as it did when it opened the object. + art, err := db.GetArtifact(purl.MakePURLString("oci", "library/nginx", digest), digest) + if err != nil || art == nil { + t.Fatalf("artifact record: %v", err) + } + if art.HitCount != 2 { + t.Errorf("hit count = %d, want 2 (GET and HEAD)", art.HitCount) + } + }) + } +} + +// A request that is not marked as HEAD reads the object as before. +func TestCacheHitWithoutHeadMarkOpensObject(t *testing.T) { + proxy, db, store, _ := setupTestProxy(t) + seedPackage(t, db, store, "npm", "demo", "1.0.0", "demo.tgz", "content") + result, err := proxy.GetCachedArtifact(context.Background(), "npm", "demo", "1.0.0", "demo.tgz") + if err != nil || result == nil || result.Reader == nil { + t.Fatalf("result=%+v err=%v; want an open reader", result, err) + } + _ = result.Reader.Close() + if store.opens != 1 { + t.Errorf("opens = %d, want 1", store.opens) + } +} diff --git a/internal/handler/helm.go b/internal/handler/helm.go index 6183d97..661ca98 100644 --- a/internal/handler/helm.go +++ b/internal/handler/helm.go @@ -1,6 +1,7 @@ package handler import ( + "context" "crypto/sha256" "encoding/hex" "errors" @@ -9,6 +10,7 @@ import ( "net/url" "path" "strings" + "sync" "time" "gopkg.in/yaml.v3" @@ -38,6 +40,10 @@ type HelmHandler struct { proxyURL string repositories map[string]string ociRegistries []helmOCIRegistry + + lookupMu sync.Mutex + // lookups holds the charts of each repository's last parsed index. + lookups map[string]*helmChartLookup } // NewHelmHandler creates a Helm chart repository protocol handler. @@ -68,20 +74,36 @@ func (h *HelmHandler) handleIndex(w http.ResponseWriter, r *http.Request) { return } - body, contentType, err := h.fetchIndex(r, repository, upstreamURL) - if err != nil { - h.serveIndexError(w, err) + // Parsing and encoding a large index costs far more than serving it, so + // rewrites go through the rewrite cache like npm packuments. The cache + // key holds the repository and upstream URL, both part of cacheKey. + cacheKey := h.indexCacheKey(repository, upstreamURL) + if stored, contentType, ok := h.proxy.storedRewriteVariant(helmMetadataEcosystem, cacheKey, h.proxyURL, cacheKey, nil); ok { + serveRewrittenMetadataAs(w, r, stored, contentType) return } - rewritten, err := h.rewriteIndex(repository, upstreamURL, body) + index := h.fetchIndex(r.Context(), repository, upstreamURL) + if index.err != nil { + h.serveIndexError(w, index.err) + return + } + + rewritten, err := h.proxy.cachedRewrite(r.Context(), helmMetadataEcosystem, h.proxyURL, cacheKey, index.body, index.digest, + func(body []byte) ([]byte, []string, error) { + return h.rewriteIndex(repository, upstreamURL, body) + }) if err != nil { + if r.Context().Err() != nil { + return // the client left while waiting on a shared rewrite + } h.proxy.Logger.Warn("failed to rewrite Helm index", "repository", repository, "error", err) http.Error(w, "invalid Helm repository index", http.StatusBadGateway) return } - h.proxy.writeMetadataCachedResponse(w, r, helmMetadataEcosystem, h.indexCacheKey(repository, upstreamURL), rewritten, contentType) + markStale(w, index.stale) + serveRewrittenMetadataAs(w, r, rewritten, index.contentType) } func (h *HelmHandler) handleChart(w http.ResponseWriter, r *http.Request) { @@ -98,6 +120,24 @@ func (h *HelmHandler) handleChart(w http.ResponseWriter, r *http.Request) { return } + var charts *helmChartLookup + if h.proxy.cooldownEnabled() { + var err error + charts, err = h.downloadChartLookup(r, repository, upstreamURL) + if err != nil { + cached, cacheErr := h.proxy.GetCachedArtifact(r.Context(), helmMetadataEcosystem, repository, digest, filename) + if cacheErr == nil && cached != nil { + h.serveChart(w, r, repository, digest, filename, cached) + } else { + h.proxy.writeCooldownLookupError(w, helmMetadataEcosystem, repository, err) + } + return + } + if h.withholdChart(w, charts, digest, filename) { + return + } + } + cached, err := h.proxy.GetCachedArtifact(r.Context(), helmMetadataEcosystem, repository, digest, filename) if err != nil { h.proxy.Logger.Error("failed to check Helm chart cache", "error", err) @@ -109,13 +149,17 @@ func (h *HelmHandler) handleChart(w http.ResponseWriter, r *http.Request) { return } - body, _, err := h.fetchIndex(r, repository, upstreamURL) - if err != nil { - h.serveIndexError(w, err) - return + var downloadURL string + if charts == nil { + index := h.fetchIndex(r.Context(), repository, upstreamURL) + if index.err != nil { + h.serveIndexError(w, index.err) + return + } + downloadURL, err = h.findChartDownload(repository, upstreamURL, index, digest, filename) + } else { + downloadURL, err = h.findChartURL(charts, digest, filename) } - - downloadURL, err := h.findChartDownload(upstreamURL, body, digest, filename) if err != nil { if errors.Is(err, errHelmChartNotFound) { http.NotFound(w, r) @@ -126,14 +170,10 @@ func (h *HelmHandler) handleChart(w http.ResponseWriter, r *http.Request) { return } - // A streamed fetch is never stored, so serveChart's digest check has - // nothing to compare against: verify the stream itself instead. - expectedDigest := "" - if h.proxy.StreamArtifacts { - expectedDigest = "sha256:" + digest - } + // Verify the chart against the index digest while it is fetched, so a + // mismatch is never committed to the cache, nor streamed out complete. result, err := h.proxy.GetOrFetchArtifactFromURLWithDigest( - r.Context(), helmMetadataEcosystem, repository, digest, filename, downloadURL, expectedDigest) + r.Context(), helmMetadataEcosystem, repository, digest, filename, downloadURL, "sha256:"+digest) if err != nil { h.proxy.serveArtifactError(w, err, "failed to fetch chart") return @@ -165,13 +205,14 @@ func (h *HelmHandler) repositoryForRequest(r *http.Request) (name, upstreamURL s return name, upstreamURL, ok } -func (h *HelmHandler) fetchIndex(r *http.Request, repository, upstreamURL string) ([]byte, string, error) { - return h.proxy.FetchOrCacheMetadata( - r.Context(), +func (h *HelmHandler) fetchIndex(ctx context.Context, repository, upstreamURL string) metadataResult { + return h.proxy.fetchMetadataDocument( + ctx, helmMetadataEcosystem, h.indexCacheKey(repository, upstreamURL), upstreamURL+"/"+helmIndexFilename, "application/x-yaml, text/yaml;q=0.9, */*;q=0.1", + nil, ) } @@ -193,17 +234,21 @@ func (h *HelmHandler) serveIndexError(w http.ResponseWriter, err error) { http.Error(w, "failed to fetch Helm repository index", http.StatusBadGateway) } -func (h *HelmHandler) rewriteIndex(repository, upstreamURL string, body []byte) ([]byte, error) { +// rewriteIndex points the index's chart URLs at the proxy and drops releases +// in cooldown. It also returns the releases it kept, by chart name and +// digest, which together with the index fix its output. +func (h *HelmHandler) rewriteIndex(repository, upstreamURL string, body []byte) ([]byte, []string, error) { document, entries, err := parseHelmIndex(body) if err != nil { - return nil, err + return nil, nil, err } + var kept []string for i := 0; i < len(entries.Content); i += 2 { chartName := entries.Content[i].Value releases := entries.Content[i+1] if releases.Kind != yaml.SequenceNode { - return nil, fmt.Errorf("chart %q releases must be a sequence", chartName) + return nil, nil, fmt.Errorf("chart %q releases must be a sequence", chartName) } filtered := make([]*yaml.Node, 0, len(releases.Content)) @@ -225,47 +270,172 @@ func (h *HelmHandler) rewriteIndex(repository, upstreamURL string, body []byte) } } filtered = append(filtered, release) + kept = append(kept, chartName+"@"+chart.digest) } releases.Content = filtered } - return yaml.Marshal(document) + out, err := yaml.Marshal(document) + return out, kept, err } -func (h *HelmHandler) findChartDownload(upstreamURL string, body []byte, digest, filename string) (string, error) { - _, entries, err := parseHelmIndex(body) +// findChartDownload returns the upstream URL of a chart in the index. Parsing +// a large index takes a while, so the charts it lists are kept per +// repository for as long as the stored index stays the same. +func (h *HelmHandler) findChartDownload(repository, upstreamURL string, index metadataResult, digest, filename string) (string, error) { + charts, err := h.chartLookup(repository, upstreamURL, index) if err != nil { return "", err } + return h.findChartURL(charts, digest, filename) +} +func (h *HelmHandler) findChartURL(charts *helmChartLookup, digest, filename string) (string, error) { + for _, chart := range charts.byDigest[digest] { + if h.chartOnCooldown(chart.name, chart.created) { + continue + } + for _, download := range chart.downloads { + if download.filename == filename { + return download.url, nil + } + } + } + return "", errHelmChartNotFound +} + +// helmChartLookup holds the HTTP chart downloads an index lists, by chart +// digest, in index order, and each release by chart name and version. +type helmChartLookup struct { + indexDigest string + byDigest map[string][]helmChartEntry + byRelease map[helmRelease]helmReleaseDownload +} + +type helmChartEntry struct { + name string + created time.Time + downloads []helmChartDownload +} + +type helmRelease struct{ chart, version string } + +// helmReleaseDownload is what helm downloads for a release: the first URL +// the index lists for it, checked against its digest. +type helmReleaseDownload struct { + digest string + created time.Time + first helmChartDownload +} + +// chartLookup returns the charts the index lists, parsing it only when the +// last lookup built for the repository came from other bytes. An index +// without a digest, read with the metadata cache off, is parsed every time. +func (h *HelmHandler) chartLookup(repository, upstreamURL string, index metadataResult) (*helmChartLookup, error) { + key := repository + "\x00" + upstreamURL + if index.digest != "" { + h.lookupMu.Lock() + cached := h.lookups[key] + h.lookupMu.Unlock() + if cached != nil && cached.indexDigest == index.digest { + return cached, nil + } + } + + lookup, err := h.buildChartLookup(upstreamURL, index.body) + if err != nil { + return nil, err + } + if index.digest != "" { + lookup.indexDigest = index.digest + h.lookupMu.Lock() + if h.lookups == nil { + h.lookups = make(map[string]*helmChartLookup) + } + h.lookups[key] = lookup + h.lookupMu.Unlock() + } + return lookup, nil +} + +func (h *HelmHandler) buildChartLookup(upstreamURL string, body []byte) (*helmChartLookup, error) { + _, entries, err := parseHelmIndex(body) + if err != nil { + return nil, err + } + + lookup := &helmChartLookup{byDigest: make(map[string][]helmChartEntry), byRelease: make(map[helmRelease]helmReleaseDownload)} for i := 0; i < len(entries.Content); i += 2 { chartName := entries.Content[i].Value releases := entries.Content[i+1] if releases.Kind != yaml.SequenceNode { - return "", fmt.Errorf("chart %q releases must be a sequence", chartName) + return nil, fmt.Errorf("chart %q releases must be a sequence", chartName) } for _, release := range releases.Content { chart, err := h.parseChartRelease(chartName, upstreamURL, release) if err != nil { continue } - if chart.digest != digest || h.chartOnCooldown(chartName, chart.created) { - continue - } - for _, download := range chart.downloads { - if !download.oci && download.filename == filename { - return download.url, nil + entry := helmChartEntry{name: chartName, created: chart.created} + if version := helmMappingValue(release, "version"); version != nil && version.Value != "" { + // helm takes the first release listed for a version. + key := helmRelease{chartName, version.Value} + if _, listed := lookup.byRelease[key]; !listed { + first := chart.downloads[0] + lookup.byRelease[key] = helmReleaseDownload{ + digest: chart.digest, + created: chart.created, + first: helmChartDownload{url: first.url, filename: first.filename, oci: first.oci}, + } } } + for _, download := range chart.downloads { + if !download.oci { + // Drop the YAML node, so the lookup doesn't keep the + // parsed index alive. + entry.downloads = append(entry.downloads, helmChartDownload{url: download.url, filename: download.filename}) + } + } + lookup.byDigest[chart.digest] = append(lookup.byDigest[chart.digest], entry) } } + return lookup, nil +} - return "", errHelmChartNotFound +func (h *HelmHandler) downloadChartLookup(r *http.Request, repository, upstreamURL string) (*helmChartLookup, error) { + key := "helm\x00" + h.indexCacheKey(repository, upstreamURL) + return publishIndex(h.proxy, key, func() metadataResult { + return h.fetchIndex(r.Context(), repository, upstreamURL) + }, func(res metadataResult) (*helmChartLookup, error) { + if res.err != nil { + return nil, res.err + } + return h.chartLookup(repository, upstreamURL, res) + }) +} + +func (h *HelmHandler) withholdChart(w http.ResponseWriter, charts *helmChartLookup, digest, filename string) bool { + withheld := false + for _, chart := range charts.byDigest[digest] { + for _, download := range chart.downloads { + if download.filename != filename { + continue + } + if !h.chartOnCooldown(chart.name, chart.created) { + return false + } + withheld = true + } + } + if withheld { + http.Error(w, ErrVersionNotFound.Error(), http.StatusNotFound) + } + return withheld } func (h *HelmHandler) chartOnCooldown(chartName string, created time.Time) bool { return !created.IsZero() && h.proxy.Cooldown != nil && h.proxy.Cooldown.Enabled() && - !h.proxy.Cooldown.IsAllowed(helmMetadataEcosystem, canonicalPackagePURL(helmMetadataEcosystem, chartName), created) + !h.proxy.cooldown().IsAllowed(helmMetadataEcosystem, canonicalPackagePURL(helmMetadataEcosystem, chartName), created) } type helmChartDownload struct { diff --git a/internal/handler/helm_mirror.go b/internal/handler/helm_mirror.go new file mode 100644 index 0000000..fe2199d --- /dev/null +++ b/internal/handler/helm_mirror.go @@ -0,0 +1,67 @@ +package handler + +import ( + "context" + "fmt" + "path" + "slices" + "strings" +) + +// MirrorChart caches a chart release of a configured repository under the +// key handleChart serves it from, checked against the digest the index +// lists. The index is read through the metadata cache, as handleIndex reads +// it, so with metadata caching on helm finds the chart there as well while +// the repository is down. +func (h *HelmHandler) MirrorChart(ctx context.Context, repository, chart, version string) (*CacheResult, error) { + upstreamURL, ok := h.repositories[repository] + if !ok { + return nil, h.unknownRepositoryError(repository) + } + index := h.fetchIndex(ctx, repository, upstreamURL) + if index.err != nil { + return nil, fmt.Errorf("fetching the %s index: %w", repository, index.err) + } + charts, err := h.chartLookup(repository, upstreamURL, index) + if err != nil { + return nil, err + } + + release, ok := charts.byRelease[helmRelease{chart, version}] + switch { + case !ok: + return nil, fmt.Errorf("%w: %s %s is not in the %s index", ErrUpstreamNotFound, chart, version, repository) + case release.first.oci: + return nil, fmt.Errorf("%s %s is published as %s, which helm pulls through the container registry routes; mirror it as an image: %s", + chart, version, release.first.url, ociChartPURL(release.first.url, version)) + case h.chartOnCooldown(chart, release.created): + return nil, fmt.Errorf("%s %s is in cooldown, so the index doesn't list it", chart, version) + } + return h.proxy.GetOrFetchArtifactFromURLWithDigest(ctx, helmMetadataEcosystem, repository, release.digest, + release.first.filename, release.first.url, "sha256:"+release.digest) +} + +func (h *HelmHandler) unknownRepositoryError(repository string) error { + names := make([]string, 0, len(h.repositories)) + for name := range h.repositories { + names = append(names, name) + } + if len(names) == 0 { + return fmt.Errorf("unknown Helm repository %q: upstream.helm configures none", repository) + } + slices.Sort(names) + return fmt.Errorf("unknown Helm repository %q: upstream.helm configures %s", repository, strings.Join(names, ", ")) +} + +// ociChartPURL returns the image PURL that mirrors an OCI chart reference, +// tagged with the chart version when the reference has no tag or digest, as +// helm pulls it. +func ociChartPURL(reference, version string) string { + repository := strings.TrimPrefix(reference, "oci://") + if at := strings.LastIndex(repository, "@"); at >= 0 { + repository, version = repository[:at], repository[at+1:] + } else if colon := strings.LastIndex(repository, ":"); colon > strings.LastIndex(repository, "/") { + repository, version = repository[:colon], repository[colon+1:] + } + return "pkg:oci/" + path.Base(repository) + "@" + version + "?repository_url=" + repository +} diff --git a/internal/handler/helm_mirror_test.go b/internal/handler/helm_mirror_test.go new file mode 100644 index 0000000..617d35d --- /dev/null +++ b/internal/handler/helm_mirror_test.go @@ -0,0 +1,17 @@ +package handler + +import "testing" + +func TestOCIChartPURL(t *testing.T) { + tests := []struct{ reference, want string }{ + {"oci://ghcr.io/owner/demo:2.0.0", "pkg:oci/demo@2.0.0?repository_url=ghcr.io/owner/demo"}, + {"oci://ghcr.io/owner/demo", "pkg:oci/demo@1.0.0?repository_url=ghcr.io/owner/demo"}, + {"oci://localhost:5000/demo", "pkg:oci/demo@1.0.0?repository_url=localhost:5000/demo"}, + {"oci://ghcr.io/owner/demo@sha256:abc", "pkg:oci/demo@sha256:abc?repository_url=ghcr.io/owner/demo"}, + } + for _, tt := range tests { + if got := ociChartPURL(tt.reference, "1.0.0"); got != tt.want { + t.Errorf("ociChartPURL(%q) = %q, want %q", tt.reference, got, tt.want) + } + } +} diff --git a/internal/handler/helm_oci_test.go b/internal/handler/helm_oci_test.go index c5163bd..e421e3f 100644 --- a/internal/handler/helm_oci_test.go +++ b/internal/handler/helm_oci_test.go @@ -57,7 +57,7 @@ entries: if !strings.Contains(response.Body.String(), ociURL) || !strings.Contains(response.Body.String(), h.chartProxyURL("mixed", digest, "demo-1.0.0.tgz")) { t.Fatalf("incorrectly rewritten index: %s", response.Body.String()) } - download, err := h.findChartDownload(upstream.URL, []byte(index), digest, "demo-1.0.0.tgz") + download, err := h.findChartDownload("mixed", upstream.URL, metadataResult{body: []byte(index)}, digest, "demo-1.0.0.tgz") if err != nil || download != upstream.URL+"/demo-1.0.0.tgz" { t.Fatalf("HTTP chart lookup = %q, %v", download, err) } @@ -103,7 +103,7 @@ func TestHelmOCIReferenceRewriting(t *testing.T) { } h := NewHelmHandlerWithOCIRegistries(&Proxy{}, tt.proxyURL, nil, tt.defaultRegistry, tt.registries) index := fmt.Sprintf("apiVersion: v1\nentries:\n demo:\n - digest: %s\n urls: [%q]\n", strings.Repeat("a", 64), tt.reference) - rewritten, err := h.rewriteIndex("mixed", "https://charts.example", []byte(index)) + rewritten, _, err := h.rewriteIndex("mixed", "https://charts.example", []byte(index)) if err != nil { t.Fatal(err) } @@ -125,7 +125,7 @@ func TestHelmIndexOmitsMalformedChartReleases(t *testing.T) { t.Run(reference, func(t *testing.T) { h := NewHelmHandler(&Proxy{Logger: slog.New(slog.NewTextHandler(io.Discard, nil))}, "https://proxy.example", nil) index := fmt.Sprintf("apiVersion: v1\nentries:\n demo:\n - digest: %s\n urls: [%q]\n - digest: %s\n urls: [demo-1.0.0.tgz]\n", strings.Repeat("b", 64), reference, goodDigest) - rewritten, err := h.rewriteIndex("mixed", "https://charts.example", []byte(index)) + rewritten, _, err := h.rewriteIndex("mixed", "https://charts.example", []byte(index)) if err != nil { t.Fatal(err) } @@ -135,11 +135,11 @@ func TestHelmIndexOmitsMalformedChartReleases(t *testing.T) { if !strings.Contains(string(rewritten), h.chartProxyURL("mixed", goodDigest, "demo-1.0.0.tgz")) { t.Fatalf("valid release missing from rewritten index: %s", rewritten) } - download, err := h.findChartDownload("https://charts.example", []byte(index), goodDigest, "demo-1.0.0.tgz") + download, err := h.findChartDownload("mixed", "https://charts.example", metadataResult{body: []byte(index)}, goodDigest, "demo-1.0.0.tgz") if err != nil || download != "https://charts.example/demo-1.0.0.tgz" { t.Fatalf("chart lookup = %q, %v", download, err) } - if _, err := h.findChartDownload("https://charts.example", []byte(index), strings.Repeat("b", 64), "demo-1.0.0.tgz"); !errors.Is(err, errHelmChartNotFound) { + if _, err := h.findChartDownload("mixed", "https://charts.example", metadataResult{body: []byte(index)}, strings.Repeat("b", 64), "demo-1.0.0.tgz"); !errors.Is(err, errHelmChartNotFound) { t.Fatalf("omitted release lookup error = %v, want errHelmChartNotFound", err) } }) @@ -160,7 +160,7 @@ entries: urls: [oci://ghcr.io/owner/demo:2.0.0] `, strings.Repeat("a", 64), time.Now().Add(-7*24*time.Hour).Format(time.RFC3339), strings.Repeat("b", 64), time.Now().Add(-time.Hour).Format(time.RFC3339)) - rewritten, err := h.rewriteIndex("mixed", "https://charts.example", []byte(index)) + rewritten, _, err := h.rewriteIndex("mixed", "https://charts.example", []byte(index)) if err != nil { t.Fatal(err) } diff --git a/internal/handler/helm_pypi_bench_test.go b/internal/handler/helm_pypi_bench_test.go new file mode 100644 index 0000000..afda74f --- /dev/null +++ b/internal/handler/helm_pypi_bench_test.go @@ -0,0 +1,184 @@ +package handler + +import ( + "fmt" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" +) + +// benchHelmIndex builds an index.yaml shaped like a large public chart +// repository: many charts, each with many releases. +func benchHelmIndex(charts, releases int) string { + var b strings.Builder + b.WriteString("apiVersion: v1\nentries:\n") + for c := range charts { + fmt.Fprintf(&b, " chart-%d:\n", c) + for r := range releases { + fmt.Fprintf(&b, ` - apiVersion: v2 + appVersion: 1.%d.0 + created: "2021-01-02T03:04:05.123456789Z" + dependencies: + - name: common + repository: oci://registry.example/charts + version: 2.x.x + description: A chart for benchmarking the index rewrite with a realistic amount of text. + digest: %064x + home: https://example.com/chart-%d + keywords: [web, server, benchmark] + maintainers: + - name: Maintainer + url: https://example.com + name: chart-%d + sources: + - https://github.com/example/chart-%d + urls: + - https://charts.example/chart-%d-1.%d.0.tgz + version: 1.%d.0 +`, r, c*releases+r, c, c, c, c, r, r) + } + } + b.WriteString("generated: \"2021-01-02T03:04:05Z\"\n") + return b.String() +} + +func benchServe(b *testing.B, h http.Handler, target, accept string) { + b.Helper() + b.ReportAllocs() + for b.Loop() { + rec := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodGet, target, nil) + if accept != "" { + req.Header.Set("Accept", accept) + } + h.ServeHTTP(rec, req) + if rec.Code != http.StatusOK { + b.Fatalf("status %d: %s", rec.Code, rec.Body.String()) + } + } +} + +// BenchmarkHelmIndexRequest serves a cached 2.5 MB index repeatedly. +func BenchmarkHelmIndexRequest(b *testing.B) { + index := benchHelmIndex(250, 20) + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/x-yaml") + _, _ = w.Write([]byte(index)) + })) + defer upstream.Close() + proxy, _, _, _ := setupTestProxy(b) + proxy.HTTPClient = upstream.Client() + proxy.CacheMetadata = true + proxy.MetadataTTL = time.Hour + proxy.SetMetadataRewriteCacheSize(256 << 20) + h := NewHelmHandler(proxy, "http://proxy.example", map[string]string{"stable": upstream.URL}).Routes() + b.SetBytes(int64(len(index))) + benchServe(b, h, "/stable/index.yaml", "") +} + +// benchPyPIProject builds simple HTML, simple JSON and JSON API documents +// for a project with many files, like botocore. +func benchPyPIProject(versions, filesPerVersion int) (simpleHTML, simpleJSON, jsonAPI string) { + var hb, sb, jb strings.Builder + hb.WriteString("\n\n \n \n Links for big\n \n \n

Links for big

\n") + sb.WriteString(`{"meta":{"api-version":"1.1"},"name":"big","files":[`) + jb.WriteString(`{"info":{"name":"big","version":"1.0.0"},"releases":{`) + n := 0 + for v := range versions { + version := fmt.Sprintf("1.%d.0", v) + if v > 0 { + jb.WriteByte(',') + } + fmt.Fprintf(&jb, "%q:[", version) + for f := range filesPerVersion { + filename := fmt.Sprintf("big-%s-py3-none-any%d.whl", version, f) + if f == 1 { + filename = fmt.Sprintf("big-%s.tar.gz", version) + } + url := fmt.Sprintf("https://files.pythonhosted.org/packages/%02x/%02x/%060x/%s", v%256, f, v*filesPerVersion+f, filename) + fmt.Fprintf(&hb, " %s
\n", url, n, n, n, filename) + if n > 0 { + sb.WriteByte(',') + } + fmt.Fprintf(&sb, `{"filename":%q,"url":%q,"hashes":{"sha256":"%064x"},"requires-python":">=3.8","core-metadata":{"sha256":"%064x"},"size":12345,"upload-time":"2021-01-02T03:04:05.123456Z","yanked":false}`, filename, url, n, n) + if f > 0 { + jb.WriteByte(',') + } + fmt.Fprintf(&jb, `{"filename":%q,"url":%q,"digests":{"sha256":"%064x","md5":"%032x"},"packagetype":"bdist_wheel","python_version":"py3","size":12345,"upload_time_iso_8601":"2021-01-02T03:04:05.123456Z","yanked":false}`, filename, url, n, n) + n++ + } + jb.WriteByte(']') + } + hb.WriteString(" \n\n\n") + sb.WriteString("]}") + jb.WriteString(`},"urls":[]}`) + return hb.String(), sb.String(), jb.String() +} + +func benchPyPIHandler(b *testing.B, deny ...string) http.Handler { + b.Helper() + simpleHTML, simpleJSON, jsonAPI := benchPyPIProject(2000, 2) + h, proxy := setupPyPIHandler(b, func(r *http.Request) (*http.Response, error) { + switch { + case r.URL.Path == "/pypi/big/json": + return pypiHTTPResponse(r, "application/json", jsonAPI), nil + case r.Header.Get("Accept") == pypiSimpleJSON: + return pypiHTTPResponse(r, pypiSimpleJSON, simpleJSON), nil + default: + return pypiHTTPResponse(r, "text/html", simpleHTML), nil + } + }) + proxy.CacheMetadata = true + proxy.MetadataTTL = time.Hour + proxy.SetMetadataRewriteCacheSize(256 << 20) + if len(deny) > 0 { + setTestDenylist(b, proxy, deny...) + } + return h.Routes() +} + +func BenchmarkPyPISimpleHTMLRequest(b *testing.B) { + benchServe(b, benchPyPIHandler(b), "/simple/big/", "") +} + +// BenchmarkPyPISimpleHTMLFilteredRequest has a version denied, so the page +// is filtered as well as rewritten. +func BenchmarkPyPISimpleHTMLFilteredRequest(b *testing.B) { + benchServe(b, benchPyPIHandler(b, "pkg:pypi/big@1.5.0"), "/simple/big/", "") +} + +func BenchmarkPyPISimpleJSONRequest(b *testing.B) { + benchServe(b, benchPyPIHandler(b), "/simple/big/", pypiSimpleJSON) +} + +func BenchmarkPyPIJSONAPIRequest(b *testing.B) { + benchServe(b, benchPyPIHandler(b), "/pypi/big/json", "") +} + +// BenchmarkPyPIRewriteSimpleHTML is the rewrite a cache miss pays. +func BenchmarkPyPIRewriteSimpleHTML(b *testing.B) { + simpleHTML, _, _ := benchPyPIProject(2000, 2) + body := []byte(simpleHTML) + h := NewPyPIHandlerWithUpstreams(testProxy(), "http://proxy.example", "", "") + b.SetBytes(int64(len(body))) + b.ReportAllocs() + for b.Loop() { + _ = h.rewriteSimpleHTML(body, nil) + } +} + +// BenchmarkPyPIRewriteSimpleHTMLFiltered is the same with a version filtered +// out. +func BenchmarkPyPIRewriteSimpleHTMLFiltered(b *testing.B) { + simpleHTML, _, _ := benchPyPIProject(2000, 2) + body := []byte(simpleHTML) + h := NewPyPIHandlerWithUpstreams(testProxy(), "http://proxy.example", "", "") + filtered := map[string]bool{"1.5.0": true} + b.SetBytes(int64(len(body))) + b.ReportAllocs() + for b.Loop() { + _ = h.rewriteSimpleHTML(h.filterSimpleHTMLLinks(body, filtered), filtered) + } +} diff --git a/internal/handler/helm_pypi_rewrite_test.go b/internal/handler/helm_pypi_rewrite_test.go new file mode 100644 index 0000000..3500f8e --- /dev/null +++ b/internal/handler/helm_pypi_rewrite_test.go @@ -0,0 +1,308 @@ +package handler + +import ( + "context" + "errors" + "fmt" + "net/http" + "net/http/httptest" + "regexp" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/git-pkgs/cooldown" +) + +// getRewritten requests target and checks the response status. +func getRewritten(t *testing.T, h http.Handler, target string, header http.Header, want int) *httptest.ResponseRecorder { + t.Helper() + req := httptest.NewRequest(http.MethodGet, target, nil) + for k, v := range header { + req.Header[k] = v + } + rec := httptest.NewRecorder() + h.ServeHTTP(rec, req) + if rec.Code != want { + t.Fatalf("GET %s: status %d, want %d: %s", target, rec.Code, want, rec.Body.String()) + } + return rec +} + +// checkServedFromRewriteCache requests target twice more after a first +// request, with storage failing, and checks the repeat is the cached rewrite: +// same body and ETag, 304 for the ETag, gzip for a client accepting it. +func checkServedFromRewriteCache(t *testing.T, h http.Handler, store *mockStorage, target string, header http.Header) string { + t.Helper() + first := getRewritten(t, h, target, header, http.StatusOK) + etag := first.Header().Get(headerETag) + if etag == "" { + t.Fatalf("no ETag on rewritten metadata; headers %v", first.Header()) + } + + // The repeat must not read the stored document back. + store.mu.Lock() + store.openErr = errors.New("storage must not be read") + store.mu.Unlock() + t.Cleanup(func() { + store.mu.Lock() + store.openErr = nil + store.mu.Unlock() + }) + + second := getRewritten(t, h, target, header, http.StatusOK) + if second.Body.String() != first.Body.String() || second.Header().Get(headerETag) != etag { + t.Errorf("repeat differs: ETag %q vs %q", second.Header().Get(headerETag), etag) + } + if got, want := second.Header().Get(headerContentType), first.Header().Get(headerContentType); got != want { + t.Errorf("repeat Content-Type = %q, want %q", got, want) + } + + conditional := header.Clone() + if conditional == nil { + conditional = http.Header{} + } + conditional.Set("If-None-Match", etag) + getRewritten(t, h, target, conditional, http.StatusNotModified) + + gzipped := header.Clone() + if gzipped == nil { + gzipped = http.Header{} + } + gzipped.Set(headerAcceptEncoding, "gzip") + compressed := getRewritten(t, h, target, gzipped, http.StatusOK) + if got := compressed.Header().Get(headerContentEncoding); got != "gzip" { + t.Errorf("Content-Encoding = %q, want gzip", got) + } + return first.Body.String() +} + +func TestHelmIndexServedFromRewriteCache(t *testing.T) { + digest := strings.Repeat("a", 64) + var indexRequests atomic.Int32 + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + indexRequests.Add(1) + w.Header().Set("Content-Type", "application/x-yaml") + _, _ = fmt.Fprintf(w, "apiVersion: v1\nentries:\n demo:\n%s", strings.Repeat(fmt.Sprintf( + " - digest: %s\n name: demo\n urls: [demo-1.0.0.tgz]\n version: 1.0.0\n", digest), 20)) + })) + defer upstream.Close() + + proxy, _, store, _ := setupTestProxy(t) + proxy.HTTPClient = upstream.Client() + proxy.CacheMetadata = true + proxy.MetadataTTL = time.Hour + proxy.SetMetadataRewriteCacheSize(1 << 20) + h := NewHelmHandler(proxy, "http://proxy.example", map[string]string{"stable": upstream.URL}).Routes() + + body := checkServedFromRewriteCache(t, h, store, "/stable/index.yaml", nil) + if !strings.Contains(body, "http://proxy.example/helm/stable/charts/"+digest+"/demo-1.0.0.tgz") { + t.Errorf("index not rewritten: %s", body) + } + if got := indexRequests.Load(); got != 1 { + t.Errorf("upstream requests = %d, want 1", got) + } + if got := proxy.rewrites.len(); got != 1 { + t.Errorf("cached rewrites = %d, want 1", got) + } +} + +// TestHelmChartLookupFollowsIndex checks that chart downloads are looked up +// in charts kept from the last parse of the same index, and that a changed +// index is parsed again. +func TestHelmChartLookupFollowsIndex(t *testing.T) { + chartA, chartB := []byte("chart a"), []byte("chart b") + digestA, digestB := helmSHA256Hex(chartA), helmSHA256Hex(chartB) + var withB atomic.Bool + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/index.yaml": + w.Header().Set("Content-Type", "application/x-yaml") + _, _ = fmt.Fprintf(w, "apiVersion: v1\nentries:\n a:\n - digest: %s\n urls: [a-1.0.0.tgz]\n", digestA) + if withB.Load() { + _, _ = fmt.Fprintf(w, " b:\n - digest: %s\n urls: [b-1.0.0.tgz]\n", digestB) + } + case "/a-1.0.0.tgz": + _, _ = w.Write(chartA) + case "/b-1.0.0.tgz": + _, _ = w.Write(chartB) + default: + http.NotFound(w, r) + } + })) + defer upstream.Close() + + proxy, _, _, _ := setupTestProxy(t) + proxy.HTTPClient = upstream.Client() + proxy.CacheMetadata = true + proxy.MetadataTTL = time.Hour + h := NewHelmHandler(proxy, "http://proxy.example", map[string]string{"stable": upstream.URL}) + index := func() metadataResult { + return h.fetchIndex(context.Background(), "stable", upstream.URL) + } + + first, err := h.findChartDownload("stable", upstream.URL, index(), digestA, "a-1.0.0.tgz") + if err != nil || first != upstream.URL+"/a-1.0.0.tgz" { + t.Fatalf("lookup = %q, %v", first, err) + } + lookup := h.lookups["stable\x00"+upstream.URL] + if lookup == nil { + t.Fatal("chart lookup was not kept") + } + if _, err := h.findChartDownload("stable", upstream.URL, index(), digestB, "b-1.0.0.tgz"); !errors.Is(err, errHelmChartNotFound) { + t.Fatalf("lookup of unlisted chart: %v", err) + } + if h.lookups["stable\x00"+upstream.URL] != lookup { + t.Error("same index was parsed again") + } + + // A new index from upstream lists a new chart. + withB.Store(true) + proxy.MetadataTTL = 0 + got, err := h.findChartDownload("stable", upstream.URL, index(), digestB, "b-1.0.0.tgz") + if err != nil || got != upstream.URL+"/b-1.0.0.tgz" { + t.Fatalf("lookup in new index = %q, %v", got, err) + } +} + +func TestPyPIMetadataServedFromRewriteCache(t *testing.T) { + const files = "https://files.pythonhosted.org/packages/ab/cd/" + simpleHTML := `demo-1.0.0.tar.gz
` + + `demo-2.0.0.tar.gz
` + + strings.Repeat("\n", 20) + simpleJSON := `{"meta":{"api-version":"1.1"},"name":"demo","files":[` + + `{"filename":"demo-1.0.0.tar.gz","url":"` + files + `demo-1.0.0.tar.gz"},` + + `{"filename":"demo-2.0.0.tar.gz","url":"` + files + `demo-2.0.0.tar.gz"}],` + + `"padding":"` + strings.Repeat("x", 1000) + `"}` + jsonAPI := `{"info":{"name":"demo","version":"1.0.0","description":"` + strings.Repeat("x", 1000) + `"},` + + `"releases":{"1.0.0":[{"url":"` + files + `demo-1.0.0.tar.gz"}],"2.0.0":[{"url":"` + files + `demo-2.0.0.tar.gz"}]},` + + `"urls":[{"url":"` + files + `demo-1.0.0.tar.gz"}]}` + + cases := []struct { + name, target, accept string + }{ + {"simple html", "/simple/demo/", ""}, + {"simple json", "/simple/demo/", pypiSimpleJSON}, + {"json api", "/pypi/demo/json", ""}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + var upstreamCalls atomic.Int32 + proxy, _, store, _ := setupTestProxy(t) + proxy.HTTPClient = &http.Client{Transport: pypiRoundTripFunc(func(r *http.Request) (*http.Response, error) { + upstreamCalls.Add(1) + switch { + case r.URL.Path == "/pypi/demo/json": + return pypiHTTPResponse(r, "application/json", jsonAPI), nil + case r.Header.Get("Accept") == pypiSimpleJSON: + return pypiHTTPResponse(r, pypiSimpleJSON, simpleJSON), nil + default: + return pypiHTTPResponse(r, "text/html", simpleHTML), nil + } + })} + proxy.CacheMetadata = true + proxy.MetadataTTL = time.Hour + proxy.SetMetadataRewriteCacheSize(1 << 20) + setTestDenylist(t, proxy, "pkg:pypi/demo@2.0.0") + h := NewPyPIHandlerWithUpstreams(proxy, "http://proxy.test", "https://pypi.test", "") + + var header http.Header + if c.accept != "" { + header = http.Header{"Accept": {c.accept}} + } + body := checkServedFromRewriteCache(t, h.Routes(), store, c.target, header) + if !strings.Contains(body, "http://proxy.test/pypi/packages/packages/ab/cd/demo-1.0.0.tar.gz") { + t.Errorf("download URL not rewritten: %s", body) + } + if strings.Contains(body, "demo-2.0.0") { + t.Errorf("denied version served: %s", body) + } + if got := upstreamCalls.Load(); got != 1 { + t.Errorf("upstream calls = %d, want 1", got) + } + + if c.target == "/simple/demo/" { + rec := getRewritten(t, h.Routes(), c.target, header, http.StatusOK) + vary := strings.Join(rec.Header().Values("Vary"), ", ") + if !strings.Contains(vary, "Accept-Encoding") || !strings.Contains(strings.ReplaceAll(vary, "Accept-Encoding", ""), "Accept") { + t.Errorf("Vary = %q, want Accept and Accept-Encoding", vary) + } + } + }) + } +} + +// TestPyPISimpleRewriteFollowsCooldown checks that a cached rewrite of a +// simple page is not served once the versions cooldown filters out change, +// though the page itself is the same. +func TestPyPISimpleRewriteFollowsCooldown(t *testing.T) { + now := time.Now() + old := now.Add(-30 * 24 * time.Hour).Format(time.RFC3339) + var released atomic.Value + released.Store(now.Add(-time.Hour).Format(time.RFC3339)) + + h, proxy := setupPyPIHandler(t, func(r *http.Request) (*http.Response, error) { + switch r.URL.Path { + case "/simple/ruff/": + return pypiHTTPResponse(r, "text/html", + `ruff-1.0.0.tar.gz`+ + `ruff-2.0.0.tar.gz`), nil + case "/pypi/ruff/json": + return pypiHTTPResponse(r, "application/json", `{"releases":{`+ + `"1.0.0":[{"upload_time_iso_8601":"`+old+`"}],`+ + `"2.0.0":[{"upload_time_iso_8601":"`+released.Load().(string)+`"}]}}`), nil + default: + t.Fatalf("unexpected upstream path: %s", r.URL.Path) + return nil, nil + } + }) + proxy.Cooldown = &cooldown.Config{Default: "7d"} + proxy.SetMetadataRewriteCacheSize(1 << 20) + + first := getRewritten(t, h.Routes(), "/simple/ruff/", nil, http.StatusOK).Body.String() + if strings.Contains(first, "ruff-2.0.0") || !strings.Contains(first, "ruff-1.0.0") { + t.Fatalf("first page = %s, want only ruff-1.0.0", first) + } + + released.Store(old) + second := getRewritten(t, h.Routes(), "/simple/ruff/", nil, http.StatusOK).Body.String() + if !strings.Contains(second, "ruff-2.0.0") { + t.Errorf("version out of cooldown still filtered: %s", second) + } +} + +// rewriteDownloadHrefsRegexp is the regular expression rewrite that +// rewriteDownloadHrefs replaces. +func rewriteDownloadHrefsRegexp(h *PyPIHandler, body []byte) []byte { + re := regexp.MustCompile(`href="(` + regexp.QuoteMeta(h.downloadURL) + `/packages/[^"]+)"`) + return re.ReplaceAllFunc(body, func(match []byte) []byte { + submatch := re.FindSubmatch(match) + return []byte(`href="` + h.proxyURL + "/pypi/packages" + strings.TrimPrefix(string(submatch[1]), h.downloadURL) + `"`) + }) +} + +func FuzzPyPIRewriteDownloadHrefs(f *testing.F) { + const dl = "https://files.pythonhosted.org" + for _, seed := range []string{ + `x`, + `empty`, + ``, + ``, + `x`, + `x`, + `x`, + `href="` + dl + `/packages/` + "\n" + `multi line"`, + `href="href="` + dl + `/packages/x"`, + } { + f.Add(seed) + } + h := NewPyPIHandlerWithUpstreams(testProxy(), "http://proxy.test", "", dl) + f.Fuzz(func(t *testing.T, body string) { + want := rewriteDownloadHrefsRegexp(h, []byte(body)) + if got := h.rewriteDownloadHrefs([]byte(body)); string(got) != string(want) { + t.Errorf("rewriteDownloadHrefs(%q)\n = %q\nwant %q", body, got, want) + } + }) +} diff --git a/internal/handler/helm_test.go b/internal/handler/helm_test.go index c4a60fe..837934a 100644 --- a/internal/handler/helm_test.go +++ b/internal/handler/helm_test.go @@ -14,7 +14,6 @@ import ( "github.com/git-pkgs/cooldown" upstreamhttp "github.com/git-pkgs/proxy/internal/httpclient" - "github.com/git-pkgs/proxy/internal/storage" "github.com/git-pkgs/registries/fetch" "gopkg.in/yaml.v3" ) @@ -169,7 +168,7 @@ func TestHelmHandler_RejectsChartDigestMismatch(t *testing.T) { if err != nil { t.Fatalf("listing queued deletes: %v", err) } - chartDir := storage.ArtifactPath(helmMetadataEcosystem, "", "test", digest, "") + chartDir := helmMetadataEcosystem + "/test/" + digest + "/" stored := 0 for path := range store.files { if !strings.HasPrefix(path, chartDir) { @@ -180,8 +179,8 @@ func TestHelmHandler_RejectsChartDigestMismatch(t *testing.T) { t.Errorf("rejected chart at %q is not queued for deletion", path) } } - if stored != requests { - t.Errorf("found %d stored charts, want one per request (%d)", stored, requests) + if stored != 0 { + t.Errorf("found %d stored charts, want none: a mismatch is discarded before it is committed", stored) } } @@ -291,7 +290,7 @@ entries: `, time.Now().Add(-10*24*time.Hour).Format(time.RFC3339), oldDigest, time.Now().Add(-time.Hour).Format(time.RFC3339), newDigest) - rewritten, err := h.rewriteIndex("test", "https://charts.example", []byte(body)) + rewritten, _, err := h.rewriteIndex("test", "https://charts.example", []byte(body)) if err != nil { t.Fatalf("rewriteIndex() error = %v", err) } diff --git a/internal/handler/hex.go b/internal/handler/hex.go index 847f955..d394c4d 100644 --- a/internal/handler/hex.go +++ b/internal/handler/hex.go @@ -5,7 +5,6 @@ import ( "compress/gzip" "encoding/json" "fmt" - "io" "net/http" "strings" "time" @@ -79,6 +78,7 @@ func (h *HexHandler) handleDownload(w http.ResponseWriter, r *http.Request) { parseErr: "could not parse tarball filename", fetchErr: "failed to fetch package", parse: h.parseTarballFilename, + publishTime: h.publishTime, }) } @@ -102,102 +102,116 @@ const hexAPIURL = "https://hex.pm" // handlePackages proxies the /packages/{name} endpoint, applying cooldown filtering // when enabled. Since the protobuf format has no timestamps, we fetch them from the // Hex HTTP API concurrently. +// +// Both are read through the metadata cache, so within metadata_ttl a package +// costs no request to repo.hex.pm or to the rate limited Hex API, and after +// it both are revalidated with their ETags. The filtered package is kept in +// the rewrite cache and served with an ETag of its own. func (h *HexHandler) handlePackages(w http.ResponseWriter, r *http.Request) { - if h.proxy.Cooldown == nil || !h.proxy.Cooldown.Enabled() { - h.proxyCached(w, r) - return - } - name := r.PathValue("name") - if name == "" { + if name == "" || !h.proxy.cooldownApplies("hex", name) { h.proxyCached(w, r) return } h.proxy.Logger.Info("hex package request with cooldown", "name", name) - protoResp, filteredVersions, err := h.fetchPackageAndVersions(r, name) + docs, err := h.proxy.fetchTimedMetadata(r.Context(), h.timedPackage(name), h.packageVersions) + switch { + case docs.doc.err != nil: + h.proxy.writeMetadataFetchError(w, docs.doc.err) + return + case docs.times.err != nil: + h.proxy.writeCooldownLookupError(w, "hex", name, docs.times.err) + return + case err != nil: + h.proxy.Logger.Error("failed to read hex package", "name", name, "error", err) + http.Error(w, "failed to filter package metadata", http.StatusBadGateway) + return + } + + packagePURL := canonicalPackagePURL("hex", name) + m, err := h.proxy.cachedRewrite(r.Context(), "hex", h.proxyURL, "packages/"+name, docs.doc.body, docs.rewriteDigest(), + func([]byte) ([]byte, []string, error) { + body, err := h.proxy.decodedMetadataBody(docs.doc) + if err != nil { + return nil, nil, err + } + versions, err := h.packageVersions(docs.doc) + if err != nil { + return nil, nil, err + } + filtered := make(map[string]bool) + var kept []string + for _, version := range versions { + if docs.withheld(h.proxy, "hex", packagePURL, version) { + filtered[version] = true + h.proxy.Logger.Info("cooldown: filtering hex version", "package", name, "version", version) + continue + } + kept = append(kept, version) + } + if len(filtered) == 0 { + // Nothing in cooldown: upstream's bytes, signature included. + return body, kept, nil + } + out, err := h.filterSignedPackage(body, filtered) + return out, kept, err + }) if err != nil { - if writeUpstreamHeld(w, err) { - return - } - h.proxy.Logger.Error("upstream request failed", "error", err) - http.Error(w, "upstream request failed", http.StatusBadGateway) - return - } - defer func() { _ = protoResp.Body.Close() }() - - if protoResp.StatusCode != http.StatusOK { - h.proxy.relayResponse(w, r, protoResp, nil) + h.proxy.Logger.Error("failed to filter hex package", "name", name, "error", err) + http.Error(w, "failed to filter package metadata", http.StatusBadGateway) return } - body, err := io.ReadAll(protoResp.Body) - if err != nil { - http.Error(w, "failed to read response", http.StatusInternalServerError) + markStale(w, docs.doc.stale || docs.times.stale) + serveHexPackage(w, r, m) +} + +// serveHexPackage writes a package with its validators, or 304 when they +// show the client's copy is current. The registry file is gzip itself, and +// Hex clients gunzip it however it is labelled, so it is never compressed +// again. +func serveHexPackage(w http.ResponseWriter, r *http.Request, m rewrittenMetadata) { + w.Header().Set(headerETag, m.etag) + if !m.lastModified.IsZero() { + w.Header().Set(headerLastModified, m.lastModified.UTC().Format(http.TimeFormat)) + } + if notModified(r, m.etag, m.lastModified) { + w.WriteHeader(http.StatusNotModified) return } - - if len(filteredVersions) == 0 { - // No versions to filter or couldn't get timestamps, pass through - w.Header().Set(headerContentType, protoResp.Header.Get(headerContentType)) - w.Header().Set("Content-Encoding", "gzip") - _, _ = w.Write(body) - return - } - - filtered, err := h.filterSignedPackage(body, filteredVersions) - if err != nil { - h.proxy.Logger.Warn("failed to filter hex package, proxying original", "error", err) - w.Header().Set(headerContentType, protoResp.Header.Get(headerContentType)) - w.Header().Set("Content-Encoding", "gzip") - _, _ = w.Write(body) - return - } - w.Header().Set(headerContentType, "application/octet-stream") - w.Header().Set("Content-Encoding", "gzip") - _, _ = w.Write(filtered) + w.Header().Set(headerContentEncoding, "gzip") + w.WriteHeader(http.StatusOK) + _, _ = w.Write(m.content()) } -// fetchPackageAndVersions fetches the protobuf package and version timestamps concurrently. -func (h *HexHandler) fetchPackageAndVersions(r *http.Request, name string) (*http.Response, map[string]bool, error) { - type versionsResult struct { - filtered map[string]bool - err error +// timedPackage describes a package's registry file and the Hex API entry +// it takes publish times from. +func (h *HexHandler) timedPackage(name string) timedMetadata { + return timedMetadata{ + ecosystem: "hex", + docKey: "packages/" + name, + docURL: h.upstreamURL + "/packages/" + name, + timesKey: hashedCacheKey(h.apiURL, "api/packages/"+name), + timesURL: fmt.Sprintf("%s/api/packages/%s", h.apiURL, name), + timesAccept: contentTypeJSON, + parseTimes: parseHexReleases, } - - versionsCh := make(chan versionsResult, 1) - go func() { - filtered, err := h.fetchFilteredVersions(r, name) - versionsCh <- versionsResult{filtered: filtered, err: err} - }() - - protoResp, err := h.fetchUpstreamPackage(r, name) - - versionsRes := <-versionsCh - - if err != nil { - return nil, nil, err - } - - if versionsRes.err != nil { - h.proxy.Logger.Warn("failed to fetch hex version timestamps, proxying unfiltered", - "name", name, "error", versionsRes.err) - return protoResp, nil, nil - } - - return protoResp, versionsRes.filtered, nil } -// fetchUpstreamPackage fetches the protobuf package from upstream. -func (h *HexHandler) fetchUpstreamPackage(r *http.Request, name string) (*http.Response, error) { - upstreamURL := h.upstreamURL + "/packages/" + name - req, err := http.NewRequestWithContext(r.Context(), http.MethodGet, upstreamURL, nil) +// packageVersions lists the releases in a gzipped Signed package. +func (h *HexHandler) packageVersions(doc metadataResult) ([]string, error) { + body, err := h.proxy.decodedMetadataBody(doc) if err != nil { return nil, err } - return h.proxy.HTTPClient.Do(req) + payload, err := h.signedPayload(body) + if err != nil { + return nil, err + } + return packageReleaseVersions(payload) } // hexRelease represents a version entry from the Hex API. @@ -211,61 +225,35 @@ type hexPackageAPI struct { Releases []hexRelease `json:"releases"` } -// fetchFilteredVersions fetches the Hex API and returns a set of version -// strings that should be filtered out by cooldown. -func (h *HexHandler) fetchFilteredVersions(r *http.Request, name string) (map[string]bool, error) { - apiURL := fmt.Sprintf("%s/api/packages/%s", h.apiURL, name) - req, err := http.NewRequestWithContext(r.Context(), http.MethodGet, apiURL, nil) - if err != nil { - return nil, err - } - req.Header.Set("Accept", "application/json") - - resp, err := h.proxy.HTTPClient.Do(req) - if err != nil { - return nil, err - } - defer func() { _ = resp.Body.Close() }() - - if resp.StatusCode != http.StatusOK { - return nil, fmt.Errorf("hex API returned %d", resp.StatusCode) - } - +// parseHexReleases reads the publish times from a Hex API package response. +func parseHexReleases(body []byte) (publishTimes, error) { var pkg hexPackageAPI - if err := json.NewDecoder(resp.Body).Decode(&pkg); err != nil { + if err := json.Unmarshal(body, &pkg); err != nil { return nil, err } - - packagePURL := canonicalPackagePURL("hex", name) - filtered := make(map[string]bool) - + times := make(publishTimes, len(pkg.Releases)) for _, release := range pkg.Releases { insertedAt, err := time.Parse(time.RFC3339Nano, release.InsertedAt) if err != nil { - continue - } - - if !h.proxy.Cooldown.IsAllowed("hex", packagePURL, insertedAt) { - filtered[release.Version] = true - h.proxy.Logger.Info("cooldown: filtering hex version", - "package", name, "version", release.Version, - "published", release.InsertedAt) + insertedAt = time.Time{} } + times[release.Version] = insertedAt } - - return filtered, nil + return times, nil } -// filterSignedPackage decompresses gzipped data, decodes the Signed protobuf wrapper, -// filters releases from the Package payload, and re-encodes as gzipped protobuf -// (without the original signature since the payload has changed). -func (h *HexHandler) filterSignedPackage(gzippedData []byte, filteredVersions map[string]bool) ([]byte, error) { - // Decompress gzip +func (h *HexHandler) publishTime(r *http.Request, name, version string) (time.Time, bool, bool, error) { + return h.proxy.lookupPublishTime(r.Context(), h.timedPackage(name), version, h.packageVersions) +} + +// signedPayload decompresses a gzipped Signed message, with the metadata +// limit applied to the decompressed size, and returns its payload. +func (h *HexHandler) signedPayload(gzippedData []byte) ([]byte, error) { gr, err := gzip.NewReader(bytes.NewReader(gzippedData)) if err != nil { return nil, err } - signed, err := io.ReadAll(gr) + signed, err := h.proxy.ReadMetadata(gr) if err != nil { return nil, err } @@ -276,9 +264,30 @@ func (h *HexHandler) filterSignedPackage(gzippedData []byte, filteredVersions ma if err != nil { return nil, fmt.Errorf("extracting payload: %w", err) } + return payload, nil +} + +// packageReleaseVersions lists the versions of the releases in a Package +// message. +func packageReleaseVersions(payload []byte) ([]string, error) { + var versions []string + _, err := filterPackageReleases(payload, nil, func(version string) { + versions = append(versions, version) + }) + return versions, err +} + +// filterSignedPackage decompresses gzipped data, decodes the Signed protobuf wrapper, +// filters releases from the Package payload, and re-encodes as gzipped protobuf +// (without the original signature since the payload has changed). +func (h *HexHandler) filterSignedPackage(gzippedData []byte, filteredVersions map[string]bool) ([]byte, error) { + payload, err := h.signedPayload(gzippedData) + if err != nil { + return nil, err + } // Filter releases from the Package message - filteredPayload, err := filterPackageReleases(payload, filteredVersions) + filteredPayload, err := filterPackageReleases(payload, filteredVersions, nil) if err != nil { return nil, fmt.Errorf("filtering releases: %w", err) } @@ -301,9 +310,10 @@ func (h *HexHandler) filterSignedPackage(gzippedData []byte, filteredVersions ma return buf.Bytes(), nil } -// filterPackageReleases filters releases from a Package protobuf message. +// filterPackageReleases filters releases from a Package protobuf message, +// calling seen, when not nil, with the version of each release. // Package: field 1 = releases (repeated), field 2 = name, field 3 = repository -func filterPackageReleases(payload []byte, filteredVersions map[string]bool) ([]byte, error) { +func filterPackageReleases(payload []byte, filteredVersions map[string]bool, seen func(string)) ([]byte, error) { var result []byte data := payload @@ -328,6 +338,9 @@ func filterPackageReleases(payload []byte, filteredVersions map[string]bool) ([] if num == 1 { // releases field version := extractReleaseVersion(v) + if seen != nil { + seen(version) + } if filteredVersions[version] { continue // skip this release } diff --git a/internal/handler/hex_test.go b/internal/handler/hex_test.go index 92120bd..a0b0448 100644 --- a/internal/handler/hex_test.go +++ b/internal/handler/hex_test.go @@ -3,6 +3,7 @@ package handler import ( "bytes" "compress/gzip" + cryptorand "crypto/rand" "encoding/json" "io" "log/slog" @@ -94,7 +95,7 @@ func buildHexSigned(payload []byte) []byte { func TestHexFilterPackageReleases(t *testing.T) { pkg := buildHexPackage("phoenix", []string{testVersion100, "2.0.0", "3.0.0"}) - filtered, err := filterPackageReleases(pkg, map[string]bool{"2.0.0": true}) + filtered, err := filterPackageReleases(pkg, map[string]bool{"2.0.0": true}, nil) if err != nil { t.Fatal(err) } @@ -329,3 +330,67 @@ func TestHexHandlePackagesWithoutCooldown(t *testing.T) { t.Fatalf("status = %d, want %d", w.Code, http.StatusOK) } } + +func TestHexCooldownMetadataSizeLimit(t *testing.T) { + const limit = 1024 + now := time.Now() + releases := []hexRelease{ + {Version: testVersion100, InsertedAt: now.Add(-7 * 24 * time.Hour).Format(time.RFC3339Nano)}, + {Version: "2.0.0", InsertedAt: now.Add(-time.Hour).Format(time.RFC3339Nano)}, + } + apiJSON, _ := json.Marshal(hexPackageAPI{Releases: releases}) + pkg := buildHexPackage("testpkg", []string{testVersion100, "2.0.0"}) + proto := buildHexSigned(pkg) + + // An unknown bytes field pads the payload: it compresses to a few bytes + // but decompresses past the limit. + padded := protowire.AppendTag(append([]byte(nil), pkg...), 4, protowire.BytesType) + padded = protowire.AppendBytes(padded, make([]byte, 64*limit)) + bomb := buildHexSigned(padded) + if len(bomb) >= limit { + t.Fatalf("compressed package is %d bytes, want under %d", len(bomb), limit) + } + // Padding that doesn't compress makes the response itself too large. + noise := make([]byte, 2*limit) + _, _ = cryptorand.Read(noise) + large := protowire.AppendTag(append([]byte(nil), pkg...), 4, protowire.BytesType) + large = buildHexSigned(protowire.AppendBytes(large, noise)) + if len(large) <= limit { + t.Fatalf("compressed package is %d bytes, want over %d", len(large), limit) + } + + tests := []struct { + name string + pkg, api []byte + }{ + {"package over limit", large, apiJSON}, + {"package decompresses past limit", bomb, apiJSON}, + {"API response over limit", proto, append(append([]byte(nil), apiJSON...), bytes.Repeat([]byte(" "), 2*limit)...)}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/packages/testpkg": + _, _ = w.Write(tt.pkg) + case "/api/packages/testpkg": + _, _ = w.Write(tt.api) + default: + w.WriteHeader(http.StatusNotFound) + } + })) + defer upstream.Close() + + proxy, _, _, _ := setupTestProxy(t) + proxy.Cooldown = &cooldown.Config{Default: "3d"} + proxy.MetadataMaxSize = limit + h := NewHexHandlerWithUpstreams(proxy, "http://proxy.test", upstream.URL, upstream.URL) + + w := httptest.NewRecorder() + h.Routes().ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/packages/testpkg", nil)) + if w.Code != http.StatusBadGateway { + t.Errorf("status = %d, want %d", w.Code, http.StatusBadGateway) + } + }) + } +} diff --git a/internal/handler/homebrew.go b/internal/handler/homebrew.go index 0af67af..4e40d02 100644 --- a/internal/handler/homebrew.go +++ b/internal/handler/homebrew.go @@ -64,7 +64,7 @@ func (h *HomebrewHandler) Routes() http.Handler { if strings.HasPrefix(requestPath, "analytics/") { acceptEncoding = "identity" } - h.proxy.proxyCachedWithEncoding(w, r, upstreamURL, homebrewMetadataEcosystem, homebrewMetadataCacheKey(requestPath, r.URL.RawQuery), acceptEncoding, "*/*") + h.proxy.proxyCachedWithEncoding(w, r, upstreamURL, homebrewMetadataEcosystem, homebrewMetadataCacheKey(requestPath, r.URL.RawQuery), acceptEncoding, nil, "*/*") }) } diff --git a/internal/handler/homebrew_bottles.go b/internal/handler/homebrew_bottles.go new file mode 100644 index 0000000..169ed61 --- /dev/null +++ b/internal/handler/homebrew_bottles.go @@ -0,0 +1,92 @@ +package handler + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "regexp" + "strconv" + "strings" +) + +var ( + homebrewFormulaPattern = regexp.MustCompile(`^[a-z0-9][a-z0-9@+._-]*$`) + homebrewVersionPattern = regexp.MustCompile(`^[0-9A-Za-z][0-9A-Za-z._+-]*$`) +) + +// homebrewMaxFormulaJSON bounds one formula's JSON API document, a few KB. +const homebrewMaxFormulaJSON = 1 << 20 + +// homebrewFormula is the part of a formula's JSON API document that names +// its bottles' image tag. +type homebrewFormula struct { + Versions struct { + Stable string `json:"stable"` + } `json:"versions"` + Revision int `json:"revision"` + Bottle struct { + Stable struct { + Rebuild int `json:"rebuild"` + Files map[string]any `json:"files"` + } `json:"stable"` + } `json:"bottle"` +} + +// BottleImage returns the homebrew/core image and tag for a formula version. +// Only the current version gets its revision and rebuild from the JSON API; +// any other version is used as the tag as given. +func (h *HomebrewHandler) BottleImage(ctx context.Context, formula, version string) (ImageRef, error) { + if !homebrewFormulaPattern.MatchString(formula) { + return ImageRef{}, fmt.Errorf("invalid Homebrew formula name %q", formula) + } + if !homebrewVersionPattern.MatchString(version) { + return ImageRef{}, fmt.Errorf("invalid Homebrew version %q", version) + } + f, err := h.fetchFormula(ctx, formula) + if err != nil { + return ImageRef{}, err + } + tag := version + if version == f.Versions.Stable { + if len(f.Bottle.Stable.Files) == 0 { + return ImageRef{}, fmt.Errorf("homebrew formula %s %s has no bottles", formula, version) + } + if f.Revision > 0 { + tag += "_" + strconv.Itoa(f.Revision) + } + if f.Bottle.Stable.Rebuild > 0 { + tag += "-" + strconv.Itoa(f.Bottle.Stable.Rebuild) + } + } + name := strings.NewReplacer("@", "/", "+", "x").Replace(formula) + return ImageRef{Name: homebrewArtifactRepository + "/" + name, References: []string{tag}}, nil +} + +func (h *HomebrewHandler) fetchFormula(ctx context.Context, formula string) (*homebrewFormula, error) { + req, err := http.NewRequestWithContext(ctx, http.MethodGet, h.apiUpstream+"/formula/"+formula+".json", nil) + if err != nil { + return nil, err + } + resp, err := h.proxy.HTTPClient.Do(req) + if err != nil { + return nil, fmt.Errorf("reading the Homebrew formula: %w", err) + } + defer func() { _ = resp.Body.Close() }() + switch { + case resp.StatusCode == http.StatusNotFound: + return nil, fmt.Errorf("homebrew/core has no formula %q", formula) + case resp.StatusCode != http.StatusOK: + return nil, fmt.Errorf("reading the Homebrew formula: upstream answered %d", resp.StatusCode) + } + var f homebrewFormula + if err := json.NewDecoder(io.LimitReader(resp.Body, homebrewMaxFormulaJSON)).Decode(&f); err != nil { + return nil, fmt.Errorf("reading the Homebrew formula: %w", err) + } + if f.Versions.Stable == "" { + return nil, errors.New("reading the Homebrew formula: it has no stable version") + } + return &f, nil +} diff --git a/internal/handler/homebrew_bottles_test.go b/internal/handler/homebrew_bottles_test.go new file mode 100644 index 0000000..a2ddb64 --- /dev/null +++ b/internal/handler/homebrew_bottles_test.go @@ -0,0 +1,72 @@ +package handler + +import ( + "context" + "net/http" + "net/http/httptest" + "strings" + "sync/atomic" + "testing" +) + +func TestHomebrewBottleImage(t *testing.T) { + formulas := map[string]string{ + "/formula/hello.json": `{"versions":{"stable":"2.12.3"},"revision":0, + "bottle":{"stable":{"rebuild":1,"files":{"arm64_linux":{}}}}}`, + "/formula/openssl@3.json": `{"versions":{"stable":"3.5.0"},"revision":2, + "bottle":{"stable":{"rebuild":0,"files":{"arm64_sequoia":{}}}}}`, + "/formula/libsigc++.json": `{"versions":{"stable":"3.6.0"},"revision":0, + "bottle":{"stable":{"rebuild":0,"files":{"x86_64_linux":{}}}}}`, + "/formula/nobottle.json": `{"versions":{"stable":"1.0"},"bottle":{}}`, + } + var requests atomic.Int32 + api := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + requests.Add(1) + body, ok := formulas[r.URL.Path] + if !ok { + http.NotFound(w, r) + return + } + _, _ = w.Write([]byte(body)) + })) + defer api.Close() + proxy, _, _, _ := setupTestProxy(t) + proxy.HTTPClient = api.Client() + h := NewHomebrewHandler(proxy, api.URL) + + tests := []struct { + formula, version string + image, tag, err string + }{ + {formula: "hello", version: "2.12.3", image: "homebrew/core/hello", tag: "2.12.3-1"}, + {formula: "openssl@3", version: "3.5.0", image: "homebrew/core/openssl/3", tag: "3.5.0_2"}, + {formula: "libsigc++", version: "3.6.0", image: "homebrew/core/libsigcxx", tag: "3.6.0"}, + // Only the current version is described; another is the tag as given. + {formula: "hello", version: "2.12.2", image: "homebrew/core/hello", tag: "2.12.2"}, + {formula: "hello", version: "2.12.3-1", image: "homebrew/core/hello", tag: "2.12.3-1"}, + {formula: "nobottle", version: "1.0", err: "has no bottles"}, + {formula: "missing", version: "1.0", err: `no formula "missing"`}, + } + for _, tt := range tests { + ref, err := h.BottleImage(context.Background(), tt.formula, tt.version) + if tt.err != "" { + if err == nil || !strings.Contains(err.Error(), tt.err) { + t.Errorf("%s@%s: err = %v, want %q", tt.formula, tt.version, err, tt.err) + } + continue + } + if err != nil || ref.Name != tt.image || len(ref.References) != 1 || ref.References[0] != tt.tag { + t.Errorf("%s@%s = %+v, %v; want %s:%s", tt.formula, tt.version, ref, err, tt.image, tt.tag) + } + } + + before := requests.Load() + for _, bad := range [][2]string{{"../hello", "1.0"}, {"Hello", "1.0"}, {"hello", "1.0/../x"}, {"hello", ""}} { + if _, err := h.BottleImage(context.Background(), bad[0], bad[1]); err == nil { + t.Errorf("%q@%q accepted", bad[0], bad[1]) + } + } + if requests.Load() != before { + t.Error("an invalid name or version reached the API") + } +} diff --git a/internal/handler/hosted.go b/internal/handler/hosted.go index 41ccb93..33f2191 100644 --- a/internal/handler/hosted.go +++ b/internal/handler/hosted.go @@ -23,6 +23,16 @@ var ( ErrHostedUnsupported = errors.New("pushing packages is not supported for this ecosystem") ErrHostedInvalidName = errors.New("invalid package name or version") ErrHostedVersionNotFound = errors.New("no pushed artifacts for this version") + ErrHostedFileNotFound = errors.New("no pushed file of this name for this version") + + // ErrHostedExists refuses a second push of the same file. Clients pin + // pushed files by version and often by hash, so a published file is never + // silently replaced; delete it first to push it again. + ErrHostedExists = errors.New("this file was already pushed; delete it first to push it again") + + // ErrHostedChecksumMismatch reports a push whose bytes don't match the + // sha256 the client sent along. + ErrHostedChecksumMismatch = errors.New("pushed bytes don't match the expected sha256") // ErrHostedArtifactUnavailable and ErrHostedArtifactMissing report a // pushed artifact the cache can't serve. They stop the caller from @@ -50,53 +60,127 @@ type HostedArtifact struct { PushedAt time.Time `json:"pushed_at"` } -// hostedNaming describes how an ecosystem names pushed archives: which -// package names it has, split on "/", and the filename its clients request. -type hostedNaming struct { +// hostedEcosystem is what an ecosystem defines for pushed packages. Storing, +// listing, deleting and the push rules are shared; adding an ecosystem means +// adding an entry here and, if its clients read version lists, listing pushed +// versions in its metadata. +type hostedEcosystem struct { + // validName reports whether a package name, split on "/", is one of the + // ecosystem's. validName func(segments []string) bool - filename func(name, version string) string + + // filename is the name clients request the archive by, derived from the + // package name and version. When nil, the filename is the last segment of + // the push path, the package name must be a single segment so the path is + // unambiguous, and a version can hold several files (see multiFile). + filename func(name, version string) string + + // readManifest reads the package manifest out of a pushed archive and + // checks that it describes target. When nil, pushes carry no manifest. + readManifest func(archive io.Reader, target HostedTarget) (json.RawMessage, error) + + // hostedOnly reports whether a namespace (an npm scope, a Composer + // vendor) is served from pushed packages alone. When nil, the ecosystem + // has no such namespaces. + hostedOnly func(p *Proxy, namespace string) bool } -var hostedNamings = map[string]hostedNaming{ +var hostedEcosystems = map[string]hostedEcosystem{ "npm": { validName: func(segments []string) bool { return len(segments) == 1 || (len(segments) == 2 && strings.HasPrefix(segments[0], "@")) }, - filename: func(name, version string) string { return lastSegment(name) + "-" + version + ".tgz" }, + filename: func(name, version string) string { return lastSegment(name) + "-" + version + ".tgz" }, + readManifest: readNPMManifest, + hostedOnly: func(p *Proxy, scope string) bool { + return slices.Contains(p.HostedNPMScopes, scope) + }, }, "composer": { - validName: func(segments []string) bool { return len(segments) == vendorPackageParts }, - filename: func(name, version string) string { return lastSegment(name) + "-" + version + ".zip" }, + validName: func(segments []string) bool { return len(segments) == vendorPackageParts }, + filename: func(name, version string) string { return lastSegment(name) + "-" + version + ".zip" }, + readManifest: readComposerManifest, + hostedOnly: func(p *Proxy, vendor string) bool { + return slices.ContainsFunc(p.HostedComposerVendors, func(v string) bool { + return strings.EqualFold(v, vendor) + }) + }, }, + // generic holds files that aren't packages, such as prebuilt binaries. + // They are served at /generic/hosted/{name}/{version}/{file} and never + // come from an upstream. + genericEcosystem: { + validName: func(segments []string) bool { return len(segments) == 1 }, + }, +} + +// multiFile reports whether a version can hold several files: those named in +// the push path. Such versions get no version-level integrity, which could +// only describe one of them. +func (e hostedEcosystem) multiFile() bool { + return e.filename == nil } // HostedSupported reports whether packages can be pushed for ecosystem. func HostedSupported(ecosystem string) bool { - _, ok := hostedNamings[ecosystem] + _, ok := hostedEcosystems[ecosystem] return ok } +// HostedFileInPath reports whether pushes for ecosystem name the file in the +// path, {name}/{version}/{file}, rather than deriving it from the name and +// version. +func HostedFileInPath(ecosystem string) bool { + eco, ok := hostedEcosystems[ecosystem] + return ok && eco.multiFile() +} + func lastSegment(name string) string { return name[strings.LastIndex(name, "/")+1:] } // HostedTargetFor validates a push of name@version to ecosystem and returns -// where it is stored. -func HostedTargetFor(ecosystem, name, version string) (HostedTarget, error) { - naming, ok := hostedNamings[ecosystem] - if !ok { - return HostedTarget{}, fmt.Errorf("%w: %s", ErrHostedUnsupported, ecosystem) +// where it is stored. filename is required for ecosystems whose pushes name +// the file (see HostedFileInPath) and must be empty for the others. +func HostedTargetFor(ecosystem, name, version, filename string) (HostedTarget, error) { + if err := ValidateHostedPath(ecosystem, name, version, filename); err != nil { + return HostedTarget{}, err } - segments := strings.Split(name, "/") - if !naming.validName(segments) { + eco := hostedEcosystems[ecosystem] + if eco.filename != nil { + filename = eco.filename(name, version) + } else if filename == "" { return HostedTarget{}, ErrHostedInvalidName } - for _, segment := range append(segments, version) { + return HostedTarget{Name: name, Version: version, Filename: filename}, nil +} + +// ValidateHostedPath checks the parts of a hosted API path: a supported +// ecosystem, one of its package names, and path segments that are safe to +// store. filename may be empty, as in a delete of a whole version, but is +// only allowed for ecosystems whose pushes name the file. +func ValidateHostedPath(ecosystem, name, version, filename string) error { + eco, ok := hostedEcosystems[ecosystem] + if !ok { + return fmt.Errorf("%w: %s", ErrHostedUnsupported, ecosystem) + } + segments := strings.Split(name, "/") + if !eco.validName(segments) { + return ErrHostedInvalidName + } + checked := append(slices.Clone(segments), version) + if filename != "" { + if !eco.multiFile() { + return ErrHostedInvalidName + } + checked = append(checked, filename) + } + for _, segment := range checked { if !validHostedSegment(segment) { - return HostedTarget{}, ErrHostedInvalidName + return ErrHostedInvalidName } } - return HostedTarget{Name: name, Version: version, Filename: naming.filename(name, version)}, nil + return nil } func validHostedSegment(s string) bool { @@ -114,16 +198,18 @@ func validHostedSegment(s string) bool { // PushLocalArtifact stores body as the artifact for target and records it as // local, replacing any cached upstream copy. Download handlers serve it from // the cache without contacting the upstream, and eviction never removes it. -// The archive's manifest must name target; it is kept so the ecosystem's -// metadata can list the version with its dependencies. -func (p *Proxy) PushLocalArtifact(ctx context.Context, ecosystem string, target HostedTarget, body io.Reader, contentType string) (HostedArtifact, error) { +// A file that was already pushed is refused with ErrHostedExists. When +// wantSHA256 is set, the pushed bytes must hash to it. If the ecosystem has +// manifests, the archive's manifest must name target; it is kept so the +// ecosystem's metadata can list the version with its dependencies. +func (p *Proxy) PushLocalArtifact(ctx context.Context, ecosystem string, target HostedTarget, body io.Reader, contentType, wantSHA256 string) (HostedArtifact, error) { + if err := p.CheckPush(ecosystem, target); err != nil { + return HostedArtifact{}, err + } pkgPURL, versionPURL, err := packagePURLStrings(ecosystem, target.Name, target.Version) if err != nil { return HostedArtifact{}, err } - if p.versionDenied(ecosystem, target.Name, target.Version) { - return HostedArtifact{}, fmt.Errorf("%w: %s", ErrVersionDenied, versionPURL) - } push := storedPush{ storagePath: storage.FetchPath(ecosystem, target.Name, target.Version, storage.NewFetchID(), target.Filename), @@ -140,6 +226,11 @@ func (p *Proxy) PushLocalArtifact(ctx context.Context, ecosystem string, target } push.integrity = "sha512-" + base64.StdEncoding.EncodeToString(sha512Hash.Sum(nil)) + if wantSHA256 != "" && !strings.EqualFold(wantSHA256, push.sha256) { + p.discardStored(ctx, push.storagePath) + return HostedArtifact{}, fmt.Errorf("%w: got %s", ErrHostedChecksumMismatch, push.sha256) + } + if err := p.checkPush(ctx, ecosystem, target, versionPURL, &push); err != nil { p.discardStored(ctx, push.storagePath) return HostedArtifact{}, err @@ -160,6 +251,40 @@ func (p *Proxy) PushLocalArtifact(ctx context.Context, ecosystem string, target }, nil } +// CheckPush refuses a push of a denied version or of a file that was already +// pushed, before any bytes are read, so a client can be told without +// uploading the file. For ecosystems with one file per version, any pushed +// file of the version counts, so a differently cased alias of the name is +// refused too. A cached upstream copy is fine to replace. Recording the push +// checks again atomically, for concurrent pushes. +func (p *Proxy) CheckPush(ecosystem string, target HostedTarget) error { + _, versionPURL, err := packagePURLStrings(ecosystem, target.Name, target.Version) + if err != nil { + return err + } + if p.versionDenied(ecosystem, target.Name, target.Version) { + return fmt.Errorf("%w: %s", ErrVersionDenied, versionPURL) + } + var existing []database.Artifact + if hostedEcosystems[ecosystem].multiFile() { + record, err := p.DB.GetArtifact(versionPURL, target.Filename) + if err != nil { + return fmt.Errorf("checking existing artifact: %w", err) + } + if record != nil { + existing = append(existing, *record) + } + } else if existing, err = p.DB.GetArtifactsByVersionPURL(versionPURL); err != nil { + return fmt.Errorf("checking existing artifacts: %w", err) + } + for _, a := range existing { + if a.Source == database.SourceLocal { + return ErrHostedExists + } + } + return nil +} + // storedPush is a pushed archive once it is in storage. type storedPush struct { storagePath string @@ -173,14 +298,16 @@ type storedPush struct { // checkPush reads the manifest of a stored push and runs the scanners on it. func (p *Proxy) checkPush(ctx context.Context, ecosystem string, target HostedTarget, versionPURL string, push *storedPush) error { - stored, err := p.Storage.Open(ctx, push.storagePath) - if err != nil { - return fmt.Errorf("reading pushed archive: %w", err) - } - push.manifest, err = readHostedManifest(ecosystem, stored, target) - _ = stored.Close() - if err != nil { - return err + if hostedEcosystems[ecosystem].readManifest != nil { + stored, err := p.Storage.Open(ctx, push.storagePath) + if err != nil { + return fmt.Errorf("reading pushed archive: %w", err) + } + push.manifest, err = readHostedManifest(ecosystem, stored, target) + _ = stored.Close() + if err != nil { + return err + } } if p.Scanners != nil && p.Scanners.Enabled() { @@ -195,41 +322,38 @@ func (p *Proxy) discardStored(ctx context.Context, storagePath string) { } } -// recordLocalArtifact writes the package, version and artifact records. The -// version's integrity is set to the pushed bytes, so the cache's integrity -// check verifies them rather than an upstream archive's digest. An existing -// package record is kept as it is, since it may describe the upstream package. +// recordLocalArtifact writes the package, version and artifact records in +// one transaction. An existing package record is kept as it is, since it may +// describe the upstream package. For ecosystems with one file per version, +// the version's integrity is set to the pushed bytes, so the cache's +// integrity check verifies them rather than an upstream archive's digest. +// Multi-file versions can't have one integrity, so an existing version record +// is left alone and each file is checked against its own sha256. func (p *Proxy) recordLocalArtifact(ecosystem string, target HostedTarget, pkgPURL, versionPURL string, push storedPush) error { - existing, err := p.DB.GetPackageByPURL(pkgPURL) + oneFilePerVersion := !hostedEcosystems[ecosystem].multiFile() + err := p.DB.RecordLocalArtifact( + &database.Package{PURL: pkgPURL, Ecosystem: ecosystem, Name: target.Name}, + &database.Version{ + PURL: versionPURL, + PackagePURL: pkgPURL, + Integrity: sql.NullString{String: push.integrity, Valid: oneFilePerVersion}, + }, + oneFilePerVersion, + &database.Artifact{ + VersionPURL: versionPURL, + Filename: target.Filename, + StoragePath: sql.NullString{String: push.storagePath, Valid: true}, + ContentHash: sql.NullString{String: push.sha256, Valid: true}, + Size: sql.NullInt64{Int64: push.size, Valid: true}, + ContentType: sql.NullString{String: push.contentType, Valid: push.contentType != ""}, + FetchedAt: sql.NullTime{Time: push.pushedAt, Valid: true}, + Manifest: sql.NullString{String: string(push.manifest), Valid: push.manifest != nil}, + }) + if errors.Is(err, database.ErrLocalArtifactExists) { + return ErrHostedExists + } if err != nil { - return fmt.Errorf("reading package: %w", err) - } - if existing == nil { - if err := p.DB.UpsertPackage(&database.Package{PURL: pkgPURL, Ecosystem: ecosystem, Name: target.Name}); err != nil { - return fmt.Errorf("upserting package: %w", err) - } - } - - if err := p.DB.UpsertVersion(&database.Version{ - PURL: versionPURL, - PackagePURL: pkgPURL, - Integrity: sql.NullString{String: push.integrity, Valid: true}, - }); err != nil { - return fmt.Errorf("upserting version: %w", err) - } - - if err := p.DB.UpsertArtifact(&database.Artifact{ - VersionPURL: versionPURL, - Filename: target.Filename, - StoragePath: sql.NullString{String: push.storagePath, Valid: true}, - ContentHash: sql.NullString{String: push.sha256, Valid: true}, - Size: sql.NullInt64{Int64: push.size, Valid: true}, - ContentType: sql.NullString{String: push.contentType, Valid: push.contentType != ""}, - FetchedAt: sql.NullTime{Time: push.pushedAt, Valid: true}, - Source: database.SourceLocal, - Manifest: sql.NullString{String: string(push.manifest), Valid: true}, - }); err != nil { - return fmt.Errorf("upserting artifact: %w", err) + return fmt.Errorf("recording pushed artifact: %w", err) } return nil } @@ -266,19 +390,8 @@ func (p *Proxy) hostedOnly(ecosystem, name string) bool { return false } namespace, _, namespaced := strings.Cut(name, "/") - if !namespaced { - return false - } - switch ecosystem { - case "npm": - return slices.Contains(p.HostedNPMScopes, namespace) - case "composer": - return slices.ContainsFunc(p.HostedComposerVendors, func(vendor string) bool { - return strings.EqualFold(vendor, namespace) - }) - default: - return false - } + eco := hostedEcosystems[ecosystem] + return namespaced && eco.hostedOnly != nil && eco.hostedOnly(p, namespace) } // localVersion is a pushed version as ecosystem metadata lists it. @@ -328,16 +441,25 @@ func (p *Proxy) localVersions(ecosystem, name string) ([]localVersion, error) { // DeleteLocalVersion removes the archives pushed for name@version. If the // upstream has the version, clients get the upstream archive again. func (p *Proxy) DeleteLocalVersion(ecosystem, name, version string) error { + return p.deleteLocal(ecosystem, name, version, "", ErrHostedVersionNotFound) +} + +// DeleteLocalFile removes one pushed file of name@version. +func (p *Proxy) DeleteLocalFile(ecosystem, name, version, filename string) error { + return p.deleteLocal(ecosystem, name, version, filename, ErrHostedFileNotFound) +} + +func (p *Proxy) deleteLocal(ecosystem, name, version, filename string, notFound error) error { _, versionPURL, err := packagePURLStrings(ecosystem, name, version) if err != nil { return err } - deleted, err := p.DB.DeleteLocalArtifacts(versionPURL) + deleted, err := p.DB.DeleteLocalArtifacts(versionPURL, filename) if err != nil { return fmt.Errorf("deleting local artifacts: %w", err) } if deleted == 0 { - return ErrHostedVersionNotFound + return notFound } return nil } @@ -347,7 +469,14 @@ func (p *Proxy) DeleteLocalVersion(ecosystem, name, version string) error { // before serving a cached copy call it first, so pushed versions the upstream // does not list are still served. Pushed artifacts are not a cache, so they // are served even when StreamArtifacts is set. +// +// With hosted packages disabled it returns nil without a lookup, as +// localVersions does: pushes are then left out of metadata, so they are not +// served ahead of the upstream either. func (p *Proxy) GetLocalArtifact(ctx context.Context, ecosystem, name, version, filename string) (*CacheResult, error) { + if !p.HostedEnabled { + return nil, nil + } pkgPURL, versionPURL, err := packagePURLStrings(ecosystem, name, version) if err != nil { return nil, err diff --git a/internal/handler/hosted_manifest.go b/internal/handler/hosted_manifest.go index 3bd9b38..cf90dcb 100644 --- a/internal/handler/hosted_manifest.go +++ b/internal/handler/hosted_manifest.go @@ -26,15 +26,16 @@ const maxManifestSize = 1 << 20 // readHostedManifest reads the package manifest out of a pushed archive and // checks that it describes target. The manifest is what the ecosystem's // metadata lists the version with, so its dependencies reach the client. +// Ecosystems without manifests return nil. func readHostedManifest(ecosystem string, archive io.Reader, target HostedTarget) (json.RawMessage, error) { - switch ecosystem { - case "npm": - return readNPMManifest(archive, target) - case "composer": - return readComposerManifest(archive, target) - default: + eco, ok := hostedEcosystems[ecosystem] + if !ok { return nil, fmt.Errorf("%w: %s", ErrHostedUnsupported, ecosystem) } + if eco.readManifest == nil { + return nil, nil + } + return eco.readManifest(archive, target) } // readNPMManifest reads package.json from the top directory of an npm diff --git a/internal/handler/hosted_test.go b/internal/handler/hosted_test.go index a4e7145..b0640be 100644 --- a/internal/handler/hosted_test.go +++ b/internal/handler/hosted_test.go @@ -7,14 +7,37 @@ import ( "compress/gzip" "context" "errors" + "fmt" "io" "strings" + "sync" "testing" "github.com/git-pkgs/proxy/internal/database" "github.com/git-pkgs/registries/fetch" ) +func TestHostedTargetForFileInPath(t *testing.T) { + got, err := HostedTargetFor("generic", "tools", "1.2.0", "tool.tar.gz") + if err != nil || got != (HostedTarget{Name: "tools", Version: "1.2.0", Filename: "tool.tar.gz"}) { + t.Errorf("generic target = %+v, %v", got, err) + } + for _, tt := range []struct{ ecosystem, name, version, file string }{ + {"generic", "tools", "1.2.0", ""}, + {"generic", "tools", "1.2.0", ".."}, + {"generic", "acme/tools", "1.2.0", "tool.tar.gz"}, + {"npm", "request", "2.88.3", "request-2.88.3.tgz"}, + } { + if _, err := HostedTargetFor(tt.ecosystem, tt.name, tt.version, tt.file); !errors.Is(err, ErrHostedInvalidName) { + t.Errorf("HostedTargetFor(%q, %q, %q, %q) error = %v, want ErrHostedInvalidName", + tt.ecosystem, tt.name, tt.version, tt.file, err) + } + } + if !HostedFileInPath("generic") || HostedFileInPath("npm") || HostedFileInPath("cargo") { + t.Error("HostedFileInPath should hold for generic only") + } +} + func TestHostedTargetFor(t *testing.T) { tests := []struct { name string @@ -49,7 +72,7 @@ func TestHostedTargetFor(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - got, err := HostedTargetFor(tt.ecosystem, tt.pkg, tt.version) + got, err := HostedTargetFor(tt.ecosystem, tt.pkg, tt.version, "") if tt.wantErr != nil { if !errors.Is(err, tt.wantErr) { t.Fatalf("HostedTargetFor() error = %v, want %v", err, tt.wantErr) @@ -114,11 +137,11 @@ var pushedTarball = string(npmTarball(requestManifest)) func pushRequest(t *testing.T, proxy *Proxy) HostedArtifact { t.Helper() - target, err := HostedTargetFor("npm", "request", "2.88.3") + target, err := HostedTargetFor("npm", "request", "2.88.3", "") if err != nil { t.Fatalf("HostedTargetFor: %v", err) } - pushed, err := proxy.PushLocalArtifact(context.Background(), "npm", target, strings.NewReader(pushedTarball), "application/gzip") + pushed, err := proxy.PushLocalArtifact(context.Background(), "npm", target, strings.NewReader(pushedTarball), "application/gzip", "") if err != nil { t.Fatalf("PushLocalArtifact: %v", err) } @@ -205,6 +228,7 @@ func TestLocalArtifactsAndDeleteLocalVersion(t *testing.T) { func TestGetLocalArtifactIgnoresUpstreamCopies(t *testing.T) { proxy, _, _, fetcher := setupTestProxy(t) + proxy.HostedEnabled = true fetcher.artifact = &fetch.Artifact{Body: io.NopCloser(strings.NewReader("upstream tarball")), ContentType: "application/gzip"} cached, err := proxy.GetOrFetchArtifactFromURL(context.Background(), "npm", "request", "2.88.3", "request-2.88.3.tgz", "https://registry.npmjs.org/request/-/request-2.88.3.tgz") @@ -228,6 +252,34 @@ func TestGetLocalArtifactIgnoresUpstreamCopies(t *testing.T) { } } +// With hosted packages disabled, downloads don't look for a pushed artifact, +// as metadata requests don't. +func TestGetLocalArtifactNeedsHostedEnabled(t *testing.T) { + proxy, db, _, _ := setupTestProxy(t) + proxy.HostedEnabled = true + pushRequest(t, proxy) + if local, err := proxy.GetLocalArtifact(context.Background(), "npm", "request", "2.88.3", "request-2.88.3.tgz"); err != nil || local == nil { + t.Fatalf("GetLocalArtifact with hosted enabled = %+v, %v, want the pushed artifact", local, err) + } else { + _ = local.Reader.Close() + } + + proxy.HostedEnabled = false + if local, err := proxy.GetLocalArtifact(context.Background(), "npm", "request", "2.88.3", "request-2.88.3.tgz"); err != nil || local != nil { + t.Fatalf("GetLocalArtifact with hosted disabled = %+v, %v, want nil, nil", local, err) + } + + // A closed database fails every query, so a nil error shows no lookup ran. + _ = db.Close() + if local, err := proxy.GetLocalArtifact(context.Background(), "npm", "request", "2.88.3", "request-2.88.3.tgz"); err != nil || local != nil { + t.Errorf("GetLocalArtifact with hosted disabled = %+v, %v, want nil, nil without a database lookup", local, err) + } + proxy.HostedEnabled = true + if _, err := proxy.GetLocalArtifact(context.Background(), "npm", "request", "2.88.3", "request-2.88.3.tgz"); err == nil { + t.Error("GetLocalArtifact with hosted enabled did not query the closed database") + } +} + func TestPushLocalArtifactRecordsManifest(t *testing.T) { proxy, _, _, _ := setupTestProxy(t) proxy.HostedEnabled = true @@ -290,11 +342,11 @@ func TestPushLocalArtifactChecksManifest(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { proxy, _, store, _ := setupTestProxy(t) - target, err := HostedTargetFor(tt.ecosystem, tt.pkg, tt.version) + target, err := HostedTargetFor(tt.ecosystem, tt.pkg, tt.version, "") if err != nil { t.Fatalf("HostedTargetFor: %v", err) } - _, err = proxy.PushLocalArtifact(context.Background(), tt.ecosystem, target, bytes.NewReader(tt.archive), "") + _, err = proxy.PushLocalArtifact(context.Background(), tt.ecosystem, target, bytes.NewReader(tt.archive), "", "") if tt.wantErr == nil { if err != nil { t.Fatalf("PushLocalArtifact: %v", err) @@ -401,7 +453,7 @@ func TestComposerManifestLookup(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - target, err := HostedTargetFor("composer", "monolog/monolog", "3.5.0") + target, err := HostedTargetFor("composer", "monolog/monolog", "3.5.0", "") if err != nil { t.Fatalf("HostedTargetFor: %v", err) } @@ -415,3 +467,96 @@ func TestComposerManifestLookup(t *testing.T) { }) } } + +func TestConcurrentPushesOfTheSameFileHaveOneWinner(t *testing.T) { + proxy, _, _, _ := setupTestProxy(t) + proxy.HostedEnabled = true + target, err := HostedTargetFor("generic", "tools", "1.2.0", "tool.tar.gz") + if err != nil { + t.Fatalf("HostedTargetFor: %v", err) + } + + const pushes = 8 + start := make(chan struct{}) + results := make([]error, pushes) + pushed := make([]HostedArtifact, pushes) + var wg sync.WaitGroup + for i := range pushes { + wg.Add(1) + go func() { + defer wg.Done() + <-start + body := strings.NewReader(fmt.Sprintf("build %d", i)) + pushed[i], results[i] = proxy.PushLocalArtifact(context.Background(), "generic", target, body, "", "") + }() + } + close(start) + wg.Wait() + + winner := -1 + for i, err := range results { + switch { + case err == nil && winner >= 0: + t.Fatalf("pushes %d and %d both succeeded", winner, i) + case err == nil: + winner = i + case !errors.Is(err, ErrHostedExists): + t.Fatalf("push %d error = %v, want ErrHostedExists", i, err) + } + } + if winner < 0 { + t.Fatal("no push succeeded") + } + + result, err := proxy.GetLocalArtifact(context.Background(), "generic", "tools", "1.2.0", "tool.tar.gz") + if err != nil || result == nil { + t.Fatalf("GetLocalArtifact = %v, %v", result, err) + } + served, _ := io.ReadAll(result.Reader) + _ = result.Reader.Close() + if string(served) != fmt.Sprintf("build %d", winner) { + t.Errorf("served %q, want the winning push %q", served, fmt.Sprintf("build %d", winner)) + } +} + +// A fetch that started before a push and records after it must not replace +// the pushed artifact or its version's integrity. +func TestCacheFillAfterPushKeepsThePush(t *testing.T) { + proxy, _, store, _ := setupTestProxy(t) + proxy.HostedEnabled = true + pushRequest(t, proxy) + + const fetchedPath = "npm/request/2.88.3/fetched/request-2.88.3.tgz" + if _, _, err := store.Store(context.Background(), fetchedPath, strings.NewReader("upstream bytes")); err != nil { + t.Fatalf("storing fetched copy: %v", err) + } + fetched := testArtifact("upstream bytes", "pkg:npm/request@2.88.3", "request-2.88.3.tgz", "application/gzip") + err := proxy.updateCacheDB("npm", "request", "pkg:npm/request", "https://registry.npmjs.org/request/-/request-2.88.3.tgz", + fetchedPath, fetched, "sha512-upstream") + if !errors.Is(err, database.ErrLocalArtifactExists) { + t.Fatalf("updateCacheDB over a push error = %v, want ErrLocalArtifactExists", err) + } + + result, err := proxy.GetLocalArtifact(context.Background(), "npm", "request", "2.88.3", "request-2.88.3.tgz") + if err != nil || result == nil { + t.Fatalf("GetLocalArtifact = %v, %v, want the pushed copy", result, err) + } + served, err := io.ReadAll(result.Reader) + _ = result.Reader.Close() + if err != nil || string(served) != pushedTarball { + t.Errorf("served %d bytes, %v, want the pushed tarball, integrity intact", len(served), err) + } +} + +func TestGenericPushDoesNotReadTheStoredFile(t *testing.T) { + proxy, _, store, _ := setupTestProxy(t) + proxy.HostedEnabled = true + target, err := HostedTargetFor("generic", "tools", "1.2.0", "tool.tar.gz") + if err != nil { + t.Fatalf("HostedTargetFor: %v", err) + } + store.openErr = errors.New("storage opened") + if _, err := proxy.PushLocalArtifact(context.Background(), "generic", target, strings.NewReader("bytes"), "", ""); err != nil { + t.Fatalf("PushLocalArtifact: %v", err) + } +} diff --git a/internal/handler/integrity.go b/internal/handler/integrity.go index 7e800b8..1bbd406 100644 --- a/internal/handler/integrity.go +++ b/internal/handler/integrity.go @@ -49,6 +49,19 @@ func newIntegrityChecks(contentHash, native string) (integrityChecks, error) { return checks, nil } +// forStoredObject returns the checks to run when serving a stored object. +// When the content hash is recorded it alone is checked. It was computed +// from the bytes that were verified against the native integrity before +// they were stored, so a match binds the bytes just as well, and serving a +// cache hit costs one hash instead of two (SHA-256 plus SHA-512 for npm). +// Without a content hash the native digests are all there is to check. +func (c integrityChecks) forStoredObject() integrityChecks { + if len(c.contentHash) == 0 { + return c + } + return integrityChecks{contentHash: c.contentHash, algorithms: []integrity.Algorithm{integrity.SHA256}} +} + // verifyIntegrity wraps body to check it against the declared integrity as // it is read. verified, called once body has been read, reports a mismatch as // ErrArtifactDigestMismatch, and also a body that was not read to its end, @@ -79,10 +92,22 @@ func verifyIntegrity(body io.ReadCloser, declared string) (_ io.Reader, verified } func (c integrityChecks) wrap(source io.ReadCloser, onMismatch func(string)) (io.ReadCloser, error) { + return c.wrapSeekable(source, onMismatch, false) +} + +// wrapFailOnMismatch is wrap for bytes that are served to a client: the +// final chunk is held back until the digest is checked, and a mismatch drops +// it and is returned from Read as ErrArtifactDigestMismatch in place of +// io.EOF, so the caller can abort rather than complete the response. +func (c integrityChecks) wrapFailOnMismatch(source io.ReadCloser, onMismatch func(string)) (io.ReadCloser, error) { + return c.wrapSeekable(source, onMismatch, true) +} + +func (c integrityChecks) wrapSeekable(source io.ReadCloser, onMismatch func(string), failOnMismatch bool) (io.ReadCloser, error) { if len(c.algorithms) == 0 { return source, nil } - verified, err := c.newVerifyingReader(source, onMismatch, false) + verified, err := c.newVerifyingReader(source, onMismatch, failOnMismatch) if err != nil { return nil, err } @@ -97,13 +122,6 @@ func (c integrityChecks) wrap(source io.ReadCloser, onMismatch func(string)) (io }, nil } -// wrapFailOnMismatch is wrap for bytes that have not been checked anywhere -// else: a mismatch is also returned from Read as ErrArtifactDigestMismatch in -// place of io.EOF, so the caller can abort rather than complete the response. -func (c integrityChecks) wrapFailOnMismatch(source io.ReadCloser, onMismatch func(string)) (io.ReadCloser, error) { - return c.newVerifyingReader(source, onMismatch, true) -} - func (c integrityChecks) newVerifyingReader(source io.ReadCloser, onMismatch func(string), failOnMismatch bool) (io.ReadCloser, error) { if len(c.algorithms) == 0 { return source, nil @@ -132,6 +150,14 @@ type verifyingReader struct { failOnMismatch bool mismatched bool + + // With failOnMismatch, held (backed by buf) is read but not yet + // returned, and only its first releasable bytes are known not to end the + // body. The rest is the latest chunk, returned once the digest matches. + buf []byte + held []byte + releasable int + eof bool } // seekableVerifyingReader verifies ordinary reads until a successful seek, @@ -163,16 +189,65 @@ func (r *seekableVerifyingReader) Close() error { } func (r *verifyingReader) Read(p []byte) (int, error) { + if r.failOnMismatch { + return r.readHoldingBack(p) + } n, err := r.reader.Read(p) if err == io.EOF { r.verify() - if r.failOnMismatch && r.mismatched { - return n, ErrArtifactDigestMismatch - } } return n, err } +// readHoldingBack returns bytes one chunk behind the source, so the final +// chunk is released only after the digest over the whole body has matched. +func (r *verifyingReader) readHoldingBack(p []byte) (int, error) { + if len(p) == 0 { + return 0, nil + } + for r.releasable == 0 && !r.eof { + // Move the held chunk to the front of the buffer and read the next + // chunk after it; once that arrives, the held chunk is not the last. + var pending int + if cap(r.buf) < len(r.held)+len(p) { + buf := make([]byte, len(r.held)+len(p)) + pending = copy(buf, r.held) + r.buf = buf + } else { + pending = copy(r.buf[:cap(r.buf)], r.held) + } + n, err := r.reader.Read(r.buf[pending : pending+len(p)]) + r.held = r.buf[:pending+n] + if n > 0 { + r.releasable = pending + } + switch { + case err == io.EOF: + r.verify() + r.eof = true + case err != nil: + r.held, r.releasable = nil, 0 + return 0, err + case n == 0: + return 0, nil + } + } + if r.eof { + if r.mismatched { + r.held, r.releasable = nil, 0 + return 0, ErrArtifactDigestMismatch + } + r.releasable = len(r.held) + if r.releasable == 0 { + return 0, io.EOF + } + } + n := copy(p, r.held[:r.releasable]) + r.held = r.held[n:] + r.releasable -= n + return n, nil +} + func (r *verifyingReader) Close() error { return r.source.Close() } diff --git a/internal/handler/integrity_test.go b/internal/handler/integrity_test.go index 16f47b1..84ce34d 100644 --- a/internal/handler/integrity_test.go +++ b/internal/handler/integrity_test.go @@ -7,10 +7,16 @@ import ( "encoding/base64" "encoding/hex" "errors" + "fmt" "io" + "net/http" + "net/http/httptest" "slices" "strings" "testing" + "testing/iotest" + + "github.com/git-pkgs/registries/fetch" ) func sha256Hex(data string) string { @@ -348,3 +354,197 @@ func TestVerifyingReaderVerifyOnce(t *testing.T) { t.Errorf("onMismatch called %d times, want 1", calls) } } + +// TestCorruptCachedArtifactAbortsResponse serves a cached artifact whose +// stored bytes no longer match its digest through a real server and client. +// The client must see a failed, short body rather than a complete response. +func TestCorruptCachedArtifactAbortsResponse(t *testing.T) { + proxy, db, store, _ := setupTestProxy(t) + content := strings.Repeat("cached content ", 10000) + seedPackage(t, db, store, "npm", "corrupt", "1.0.0", "corrupt-1.0.0.tgz", content) + seeded, err := db.GetArtifact("pkg:npm/corrupt@1.0.0", "corrupt-1.0.0.tgz") + if err != nil || seeded == nil || !seeded.StoragePath.Valid { + t.Fatalf("seeded record = %+v (err %v), want a storage path", seeded, err) + } + tampered := []byte(content) + tampered[len(tampered)-1] = '!' + store.files[seeded.StoragePath.String] = tampered + + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + result, err := proxy.GetCachedArtifact(r.Context(), "npm", "corrupt", "1.0.0", "corrupt-1.0.0.tgz") + if err != nil || result == nil { + http.Error(w, "not cached", http.StatusInternalServerError) + return + } + ServeArtifactRequest(w, r, result) + })) + t.Cleanup(server.Close) + + resp, err := server.Client().Get(server.URL) + if err != nil { + t.Fatalf("GET: %v", err) + } + defer func() { _ = resp.Body.Close() }() + if resp.StatusCode != http.StatusOK { + t.Fatalf("status = %d, want %d", resp.StatusCode, http.StatusOK) + } + if resp.ContentLength != int64(len(content)) { + t.Fatalf("Content-Length = %d, want %d", resp.ContentLength, len(content)) + } + body, err := io.ReadAll(resp.Body) + if err == nil { + t.Error("reading a corrupted cached artifact succeeded, want an error") + } + if int64(len(body)) >= resp.ContentLength { + t.Errorf("read %d bytes, want fewer than Content-Length %d", len(body), resp.ContentLength) + } + if !bytes.HasPrefix(tampered, body) { + t.Error("body is not a prefix of the stored bytes") + } + + artifact, err := db.GetArtifact("pkg:npm/corrupt@1.0.0", "corrupt-1.0.0.tgz") + if err != nil || artifact == nil || artifact.StoragePath.Valid { + t.Errorf("record = %+v (err %v), want it cleared", artifact, err) + } +} + +func TestFailOnMismatchHoldsBackFinalChunk(t *testing.T) { + data := strings.Repeat("0123456789", 1000) + for _, tt := range []struct { + name string + source func(string) io.Reader + }{ + {"single reads", func(s string) io.Reader { return strings.NewReader(s) }}, + {"one byte reads", func(s string) io.Reader { return iotest.OneByteReader(strings.NewReader(s)) }}, + {"data with EOF", func(s string) io.Reader { return iotest.DataErrReader(strings.NewReader(s)) }}, + } { + t.Run(tt.name, func(t *testing.T) { + checks, err := newIntegrityChecks(sha256Hex(data), "") + if err != nil { + t.Fatal(err) + } + + reader, err := checks.wrapFailOnMismatch(io.NopCloser(tt.source(data)), func(string) { + t.Error("onMismatch called for matching bytes") + }) + if err != nil { + t.Fatal(err) + } + got, err := io.ReadAll(reader) + if err != nil || string(got) != data { + t.Errorf("matching read = %d bytes, %v; want %d bytes, nil", len(got), err, len(data)) + } + + var calls int + tampered := data[:len(data)-1] + "!" + reader, err = checks.wrapFailOnMismatch(io.NopCloser(tt.source(tampered)), func(string) { calls++ }) + if err != nil { + t.Fatal(err) + } + got, err = io.ReadAll(reader) + if !errors.Is(err, ErrArtifactDigestMismatch) { + t.Errorf("mismatched read error = %v, want ErrArtifactDigestMismatch", err) + } + if len(got) >= len(tampered) || !strings.HasPrefix(tampered, string(got)) { + t.Errorf("mismatched read returned %d of %d bytes, want a strict prefix", len(got), len(tampered)) + } + if calls != 1 { + t.Errorf("onMismatch called %d times, want 1", calls) + } + }) + } +} + +// TestFetchWithDigestVerifiesEveryAlgorithm checks that a sha512 digest is +// verified before the artifact is cached, like a sha256 one, and that a digest +// whose algorithm can't be verified is refused without fetching. +func TestFetchWithDigestVerifiesEveryAlgorithm(t *testing.T) { + const content = "blob content" + sum512 := sha512.Sum512([]byte(content)) + tests := []struct { + name, digest string + wantErr error + }{ + {"sha256", "sha256:" + sha256Hex(content), nil}, + {"sha512", "sha512:" + hex.EncodeToString(sum512[:]), nil}, + {"mismatched sha256", "sha256:" + sha256Hex("other"), ErrArtifactDigestMismatch}, + {"mismatched sha512", "sha512:" + strings.Repeat("a", 128), ErrArtifactDigestMismatch}, + {"unsupported algorithm", "sha1:" + strings.Repeat("a", 40), ErrUnsupportedDigest}, + {"malformed sha512", "sha512:abc", ErrUnsupportedDigest}, + } + for _, stream := range []bool{false, true} { + for _, tt := range tests { + t.Run(fmt.Sprintf("%s/stream=%t", tt.name, stream), func(t *testing.T) { + checkFetchWithDigest(t, stream, content, tt.digest, tt.wantErr) + }) + } + } +} + +func checkFetchWithDigest(t *testing.T, stream bool, content, digest string, wantErr error) { + t.Helper() + proxy, _, _, fetcher := setupTestProxy(t) + proxy.StreamArtifacts = stream + fetcher.artifact = &fetch.Artifact{Body: io.NopCloser(strings.NewReader(content))} + + result, err := proxy.GetOrFetchArtifactFromURLWithDigest(t.Context(), "oci", "library/demo", digest, digest, + "https://registry.example/v2/library/demo/blobs/"+digest, digest) + if err == nil { + var body []byte + body, err = io.ReadAll(result.Reader) + _ = result.Reader.Close() + if err == nil && string(body) != content { + t.Errorf("body = %q, want %q", body, content) + } + } + if !errors.Is(err, wantErr) { + t.Fatalf("error = %v, want %v", err, wantErr) + } + if errors.Is(wantErr, ErrUnsupportedDigest) && fetcher.fetchCalled { + t.Error("fetched an artifact whose digest can't be verified") + } + cached, err := proxy.GetCachedArtifact(t.Context(), "oci", "library/demo", digest, digest) + if err != nil { + t.Fatal(err) + } + if cached != nil { + _ = cached.Reader.Close() + } + if wantCached := wantErr == nil && !stream; (cached != nil) != wantCached { + t.Errorf("cached = %v, want %v", cached != nil, wantCached) + } +} + +// BenchmarkStoredObjectVerification compares verifying a cache hit with +// every recorded digest (SHA-256 content hash plus npm's SHA-512) against +// the content hash alone. +func BenchmarkStoredObjectVerification(b *testing.B) { + data := strings.Repeat("x", 8<<20) + checks, err := newIntegrityChecks(sha256Hex(data), sha512SRI(data)) + if err != nil { + b.Fatal(err) + } + for _, bench := range []struct { + name string + checks integrityChecks + }{ + {"all digests", checks}, + {"content hash", checks.forStoredObject()}, + } { + b.Run(bench.name, func(b *testing.B) { + b.SetBytes(int64(len(data))) + buf := make([]byte, 32<<10) + for b.Loop() { + reader, err := bench.checks.wrapFailOnMismatch(io.NopCloser(strings.NewReader(data)), func(reason string) { + b.Fatal(reason) + }) + if err != nil { + b.Fatal(err) + } + if _, err := io.CopyBuffer(io.Discard, reader, buf); err != nil { + b.Fatal(err) + } + } + }) + } +} diff --git a/internal/handler/julia.go b/internal/handler/julia.go index 749335b..dbac313 100644 --- a/internal/handler/julia.go +++ b/internal/handler/julia.go @@ -12,6 +12,7 @@ import ( "regexp" "strings" "sync" + "time" "github.com/BurntSushi/toml" "github.com/git-pkgs/proxy/internal/retention" @@ -22,6 +23,11 @@ const ( juliaGeneralRegistryUUID = "23338594-aafe-5451-b93e-139f81909106" juliaArtifactName = "_artifact" juliaRegistryName = "_registry" + + // juliaRefreshTimeout bounds a background reload of the name map. + juliaRefreshTimeout = 5 * time.Minute + // maxJuliaRegistryTomlSize bounds Registry.toml. General's is a few MB. + maxJuliaRegistryTomlSize = 64 << 20 ) var ( @@ -101,16 +107,16 @@ func (h *JuliaHandler) handleRegistry(w http.ResponseWriter, r *http.Request) { return } - h.proxy.Logger.Info("julia registry request", "uuid", uuid, "hash", hash) + h.proxy.Logger.Debug("julia registry request", "uuid", uuid, "hash", hash) upstreamURL := h.upstreamURL + r.URL.Path - result, err := h.proxy.GetOrFetchArtifactFromURL(r.Context(), "julia", juliaRegistryName, hash, hash+".tar.gz", upstreamURL) + result, err := h.proxy.GetOrFetchArtifactFromURL(r.Context(), "julia", juliaRegistryName, hash, juliaTarball(hash), upstreamURL) if err != nil { h.proxy.serveArtifactError(w, err, "failed to fetch registry") return } - go h.refreshNamesFromRegistry(uuid, hash) + go h.refreshNamesFromRegistry(context.WithoutCancel(r.Context()), uuid, hash) ServeArtifactRequest(w, r, result) } @@ -131,8 +137,15 @@ func (h *JuliaHandler) handlePackage(w http.ResponseWriter, r *http.Request) { h.proxy.Logger.Info("julia package request", "name", name, "uuid", uuid, "hash", hash) + if name == uuid { + if result := h.cachedPackage(r.Context(), hash); result != nil { + ServeArtifactRequest(w, r, result) + return + } + } + upstreamURL := h.upstreamURL + r.URL.Path - result, err := h.proxy.GetOrFetchArtifactFromURL(r.Context(), "julia", name, hash, hash+".tar.gz", upstreamURL) + result, err := h.proxy.GetOrFetchArtifactFromURL(r.Context(), "julia", name, hash, juliaTarball(hash), upstreamURL) if err != nil { h.proxy.serveArtifactError(w, err, "failed to fetch package") return @@ -141,6 +154,54 @@ func (h *JuliaHandler) handlePackage(w http.ResponseWriter, r *http.Request) { ServeArtifactRequest(w, r, result) } +// cachedPackage returns the package tarball with tree hash hash from the +// cache, under whatever name it was cached as, or nil. Without the name map, +// which needs the registry from upstream, a request can't be matched to the +// name its package was cached under, but the tarball is identified by its +// tree hash alone. The registry and artifact tarballs cached under the same +// file name are skipped. +func (h *JuliaHandler) cachedPackage(ctx context.Context, hash string) *CacheResult { + if h.proxy.DB == nil { + return nil + } + filename := juliaTarball(hash) + names, err := h.proxy.DB.CachedArtifactNames("julia", filename) + if err != nil { + h.proxy.Logger.Warn("looking up cached julia package", "hash", hash, "error", err) + return nil + } + for _, name := range names { + if name == juliaRegistryName || name == juliaArtifactName { + continue + } + result, err := h.proxy.GetCachedArtifact(ctx, "julia", name, hash, filename) + if err == nil && result != nil { + return result + } + } + return nil +} + +// JuliaPackageDownload returns the URL of a package's tarball on the Pkg +// server at upstreamURL, or the default one when empty, and the file name the +// Julia handler caches it under. +func JuliaPackageDownload(upstreamURL, uuid, treeHash string) (url, filename string, err error) { + if !validJuliaUUID(uuid) { + return "", "", fmt.Errorf("invalid julia package uuid %q", uuid) + } + if !juliaHexPattern.MatchString(treeHash) { + return "", "", fmt.Errorf("invalid julia tree hash %q", treeHash) + } + base := configuredUpstreamURL(upstreamURL, juliaUpstream) + return base + "/package/" + uuid + "/" + treeHash, juliaTarball(treeHash), nil +} + +// juliaTarball is the file name a registry, package or artifact tarball is +// cached under. +func juliaTarball(hash string) string { + return hash + ".tar.gz" +} + // handleArtifact serves an immutable binary artifact tarball. Artifacts are // anonymous content-addressed blobs with no associated package name. func (h *JuliaHandler) handleArtifact(w http.ResponseWriter, r *http.Request) { @@ -150,10 +211,10 @@ func (h *JuliaHandler) handleArtifact(w http.ResponseWriter, r *http.Request) { return } - h.proxy.Logger.Info("julia artifact request", "hash", hash) + h.proxy.Logger.Debug("julia artifact request", "hash", hash) upstreamURL := h.upstreamURL + r.URL.Path - result, err := h.proxy.GetOrFetchArtifactFromURL(r.Context(), "julia", juliaArtifactName, hash, hash+".tar.gz", upstreamURL) + result, err := h.proxy.GetOrFetchArtifactFromURL(r.Context(), "julia", juliaArtifactName, hash, juliaTarball(hash), upstreamURL) if err != nil { h.proxy.serveArtifactError(w, err, "failed to fetch artifact") return @@ -211,24 +272,16 @@ func (h *JuliaHandler) loadNamesFromUpstream(ctx context.Context) error { return h.loadRegistryTarball(ctx, juliaGeneralRegistryUUID, hash) } -// fetchGeneralRegistryHash reads /registries and returns the current tree hash -// for the General registry. +// fetchGeneralRegistryHash reads /registries, through the metadata cache that +// also serves it to clients, and returns the current tree hash for the +// General registry. func (h *JuliaHandler) fetchGeneralRegistryHash(ctx context.Context) (string, error) { - req, err := http.NewRequestWithContext(ctx, http.MethodGet, h.upstreamURL+"/registries", nil) + body, _, err := h.proxy.FetchOrCacheMetadata(ctx, "julia", "registries", h.upstreamURL+"/registries", "*/*") if err != nil { - return "", err - } - resp, err := h.proxy.HTTPClient.Do(req) - if err != nil { - return "", err - } - defer func() { _ = resp.Body.Close() }() - - if resp.StatusCode != http.StatusOK { - return "", fmt.Errorf("upstream /registries returned %d", resp.StatusCode) + return "", fmt.Errorf("reading /registries: %w", err) } - scanner := bufio.NewScanner(resp.Body) + scanner := bufio.NewScanner(bytes.NewReader(body)) for scanner.Scan() { uuid, hash, ok := parseRegistryLine(scanner.Text()) if ok && uuid == juliaGeneralRegistryUUID { @@ -241,23 +294,41 @@ func (h *JuliaHandler) fetchGeneralRegistryHash(ctx context.Context) (string, er return "", fmt.Errorf("general registry not listed in /registries") } -// refreshNamesFromRegistry reloads the UUID→name map from a registry tarball -// that has just been cached. Errors are logged but do not affect the response. -func (h *JuliaHandler) refreshNamesFromRegistry(uuid, hash string) { - if uuid != juliaGeneralRegistryUUID { +// refreshNamesFromRegistry reloads the UUID→name map after a General registry +// tarball has been served. Only the hash /registries currently lists replaces +// the map, so requests for older snapshots neither roll it back nor trigger a +// download each. One reload runs at a time; a request that finds one running +// skips its own. Errors are logged but do not affect the response. +func (h *JuliaHandler) refreshNamesFromRegistry(ctx context.Context, uuid, hash string) { + if uuid != juliaGeneralRegistryUUID || h.currentNamesHash() == hash { return } - h.mu.RLock() - current := h.namesHash - h.mu.RUnlock() - if current == hash { + if !h.loadMu.TryLock() { return } - if err := h.loadRegistryTarball(context.Background(), uuid, hash); err != nil { + defer h.loadMu.Unlock() + + ctx, cancel := context.WithTimeout(ctx, juliaRefreshTimeout) + defer cancel() + advertised, err := h.fetchGeneralRegistryHash(ctx) + if err != nil { + h.proxy.Logger.Warn("failed to refresh julia name map", "error", err) + return + } + if advertised != hash || h.currentNamesHash() == hash { + return + } + if err := h.loadRegistryTarball(ctx, uuid, hash); err != nil { h.proxy.Logger.Warn("failed to refresh julia name map", "error", err) } } +func (h *JuliaHandler) currentNamesHash() string { + h.mu.RLock() + defer h.mu.RUnlock() + return h.namesHash +} + // loadRegistryTarball downloads a registry tarball and replaces the name map // with the contents of its Registry.toml. func (h *JuliaHandler) loadRegistryTarball(ctx context.Context, uuid, hash string) error { @@ -312,10 +383,13 @@ func extractRegistryNames(r io.Reader) (map[string]string, error) { continue } - data, err := io.ReadAll(tr) + data, err := io.ReadAll(io.LimitReader(tr, maxJuliaRegistryTomlSize+1)) if err != nil { return nil, err } + if len(data) > maxJuliaRegistryTomlSize { + return nil, fmt.Errorf("registry file Registry.toml exceeds %d bytes", maxJuliaRegistryTomlSize) + } return parseRegistryToml(data) } } diff --git a/internal/handler/julia_refresh_test.go b/internal/handler/julia_refresh_test.go new file mode 100644 index 0000000..4ee080b --- /dev/null +++ b/internal/handler/julia_refresh_test.go @@ -0,0 +1,135 @@ +package handler + +import ( + "archive/tar" + "bytes" + "compress/gzip" + "context" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + "time" +) + +func juliaRegistryTarball(t *testing.T, packageName string) []byte { + t.Helper() + body := "name = \"General\"\n[packages]\n295af30f-e4ad-537b-8983-00126c2a3abe = { name = \"" + packageName + "\", path = \"R/X\" }\n" + var buf bytes.Buffer + gw := gzip.NewWriter(&buf) + tw := tar.NewWriter(gw) + if err := tw.WriteHeader(&tar.Header{Name: "Registry.toml", Mode: 0o644, Size: int64(len(body))}); err != nil { + t.Fatal(err) + } + _, _ = tw.Write([]byte(body)) + _ = tw.Close() + _ = gw.Close() + return buf.Bytes() +} + +type fakeJuliaUpstream struct { + mu sync.Mutex + advertised string + tarballs map[string][]byte + downloads map[string]int +} + +func (u *fakeJuliaUpstream) ServeHTTP(w http.ResponseWriter, r *http.Request) { + u.mu.Lock() + defer u.mu.Unlock() + if r.URL.Path == "/registries" { + _, _ = w.Write([]byte("/registry/" + juliaGeneralRegistryUUID + "/" + u.advertised + "\n")) + return + } + hash := r.URL.Path[strings.LastIndex(r.URL.Path, "/")+1:] + body, ok := u.tarballs[hash] + if !ok { + http.NotFound(w, r) + return + } + u.downloads[hash]++ + _, _ = w.Write(body) +} + +func (u *fakeJuliaUpstream) count(hash string) int { + u.mu.Lock() + defer u.mu.Unlock() + return u.downloads[hash] +} + +func TestJuliaRefreshOnlyLoadsAdvertisedRegistry(t *testing.T) { + oldHash, newHash := strings.Repeat("a", 40), strings.Repeat("b", 40) + up := &fakeJuliaUpstream{ + advertised: newHash, + tarballs: map[string][]byte{ + oldHash: juliaRegistryTarball(t, "OldName"), + newHash: juliaRegistryTarball(t, "NewName"), + }, + downloads: map[string]int{}, + } + server := httptest.NewServer(up) + defer server.Close() + + proxy, _, _, _ := setupTestProxy(t) + h := NewJuliaHandlerWithUpstream(proxy, server.URL) + ctx := context.Background() + + // An older snapshot neither replaces the map nor is downloaded for it. + for range 5 { + h.refreshNamesFromRegistry(ctx, juliaGeneralRegistryUUID, oldHash) + } + if n := up.count(oldHash); n != 0 { + t.Fatalf("old registry downloaded %d times for the name map", n) + } + + h.refreshNamesFromRegistry(ctx, juliaGeneralRegistryUUID, newHash) + if got := h.resolveName("295af30f-e4ad-537b-8983-00126c2a3abe"); got != "NewName" { + t.Fatalf("name = %q, want NewName", got) + } + + // The loaded hash is not fetched again, and an old one doesn't roll back. + h.refreshNamesFromRegistry(ctx, juliaGeneralRegistryUUID, newHash) + h.refreshNamesFromRegistry(ctx, juliaGeneralRegistryUUID, oldHash) + if n := up.count(newHash); n != 1 { + t.Errorf("current registry downloaded %d times, want 1", n) + } + if got := h.resolveName("295af30f-e4ad-537b-8983-00126c2a3abe"); got != "NewName" { + t.Errorf("name rolled back to %q", got) + } +} + +func TestJuliaRefreshSkipsWhileLoading(t *testing.T) { + proxy, _, _, _ := setupTestProxy(t) + h := NewJuliaHandlerWithUpstream(proxy, "http://127.0.0.1:1") + h.loadMu.Lock() + done := make(chan struct{}) + go func() { + h.refreshNamesFromRegistry(context.Background(), juliaGeneralRegistryUUID, strings.Repeat("c", 40)) + close(done) + }() + select { + case <-done: + case <-time.After(5 * time.Second): + t.Fatal("refresh waited for a running load instead of skipping") + } + h.loadMu.Unlock() +} + +func TestJuliaExtractRegistryNamesLimitsRegistryToml(t *testing.T) { + var buf bytes.Buffer + gw := gzip.NewWriter(&buf) + tw := tar.NewWriter(gw) + size := int64(maxJuliaRegistryTomlSize + 1) + if err := tw.WriteHeader(&tar.Header{Name: "Registry.toml", Mode: 0o644, Size: size}); err != nil { + t.Fatal(err) + } + if _, err := tw.Write(bytes.Repeat([]byte("#"), int(size))); err != nil { + t.Fatal(err) + } + _ = tw.Close() + _ = gw.Close() + if _, err := extractRegistryNames(&buf); err == nil { + t.Fatal("oversized Registry.toml was accepted") + } +} diff --git a/internal/handler/maven.go b/internal/handler/maven.go index 1e4e2eb..50d3046 100644 --- a/internal/handler/maven.go +++ b/internal/handler/maven.go @@ -1,8 +1,12 @@ package handler import ( + "context" + "crypto/sha256" + "encoding/hex" "errors" "fmt" + "io" "net/http" "path" "strings" @@ -35,12 +39,44 @@ func mavenRetentionKey(p *purl.PURL) (string, bool) { return retention.DefaultCanonical("maven")(p) } -// MavenHandler handles Maven repository protocol requests. +// MavenHandler handles Maven repository protocol requests. The default +// repository is served at /maven/ and falls back to the Gradle Plugin Portal; +// each named repository is served at /maven/{name}/ from its own upstream +// alone. type MavenHandler struct { proxy *Proxy upstreamURL string pluginPortalUpstreamURL string proxyURL string + repositories map[string]mavenSource +} + +// mavenSource is the repository a request is served from. +type mavenSource struct { + // name is the repository name, or "" for the default repository. + name string + upstreamURL string + // fallbackURL is tried when upstreamURL doesn't have a file. Only the + // default repository has one, the Gradle Plugin Portal. + fallbackURL string + // cachePrefix is prepended to cached filenames: empty for the default + // repository, {name}/{hash of upstreamURL}/ for a named one. + cachePrefix string +} + +// WithRepositories adds named repositories, served at /maven/{name}/. +func (h *MavenHandler) WithRepositories(repositories map[string]string) *MavenHandler { + h.repositories = make(map[string]mavenSource, len(repositories)) + for name, upstreamURL := range repositories { + upstreamURL = strings.TrimSuffix(upstreamURL, "/") + digest := sha256.Sum256([]byte(upstreamURL)) + h.repositories[name] = mavenSource{ + name: name, + upstreamURL: upstreamURL, + cachePrefix: name + "/" + hex.EncodeToString(digest[:mavenUpstreamHashBytes]) + "/", + } + } + return h } // NewMavenHandler creates a new Maven repository handler. @@ -68,7 +104,7 @@ func (h *MavenHandler) Routes() http.Handler { // e.g., /com/google/guava/guava/32.1.3-jre/guava-32.1.3-jre.jar mux.HandleFunc("GET /", h.handleRequest) - return mux + return rejectQueryChars(mux) } // handleRequest routes Maven requests based on the path. @@ -79,82 +115,185 @@ func (h *MavenHandler) handleRequest(w http.ResponseWriter, r *http.Request) { return } + source := mavenSource{upstreamURL: h.upstreamURL, fallbackURL: h.pluginPortalUpstreamURL} + if name, rest, ok := strings.Cut(urlPath, "/"); ok { + if named, found := h.repositories[name]; found { + source = named + urlPath = rest + } + } else if _, found := h.repositories[urlPath]; found { + http.NotFound(w, r) + return + } + if urlPath == "" { + http.NotFound(w, r) + return + } + filename := path.Base(urlPath) if h.isVersionListingFile(filename) { - h.handleMetadata(w, r, urlPath) + h.handleMetadata(w, r, source, urlPath) return } - if h.isArtifactFile(filename) || h.isChecksumFile(filename) { - h.handleDownload(w, r, urlPath) + if h.isArtifactFile(filename) || h.isChecksumFile(filename) || h.isCoordinateFile(urlPath) { + h.handleDownload(w, r, source, urlPath) return } - // Proxy everything else (directory listings etc.) - h.proxyUpstream(w, r) + // Proxy everything else (directory listings, catalogs etc.) + h.proxyUpstream(w, r, source, urlPath) } -func (h *MavenHandler) handleMetadata(w http.ResponseWriter, r *http.Request, urlPath string) { - cacheKey := strings.ReplaceAll(urlPath, "/", "_") - upstreamURL := fmt.Sprintf("%s/%s", h.upstreamURL, urlPath) - - body, contentType, err := h.proxy.FetchOrCacheMetadata(r.Context(), "maven", cacheKey, upstreamURL, "*/*") - if err != nil { - if errors.Is(err, ErrUpstreamNotFound) { - pluginPortalURL := fmt.Sprintf("%s/%s", h.pluginPortalUpstreamURL, urlPath) - h.proxy.Logger.Info("maven metadata unavailable in primary upstream, trying Gradle Plugin Portal", - "path", urlPath) - body, contentType, err = h.proxy.FetchOrCacheMetadata(r.Context(), "maven", cacheKey, pluginPortalURL, "*/*") - } +// metadataCacheKey is the metadata cache key of urlPath. The default +// repository's keys are hashed from its upstream URLs and the path. A named +// repository's keys are hashed from its name, upstream URL and the path, so +// repositories never share entries and repointing one drops what it cached. +func (s mavenSource) metadataCacheKey(urlPath string) string { + if s.name == "" { + return hashedCacheKey(s.upstreamURL, s.fallbackURL, urlPath) } - if err != nil { - if errors.Is(err, ErrUpstreamNotFound) { - http.Error(w, "not found", http.StatusNotFound) - return - } - if writeUpstreamHeld(w, err) { - return - } - h.proxy.Logger.Error("metadata fetch failed", "error", err) - http.Error(w, "failed to fetch from upstream", http.StatusBadGateway) + digest := sha256.Sum256([]byte(s.name + "\x00" + s.upstreamURL + "\x00" + urlPath)) + return "repo_" + hex.EncodeToString(digest[:]) +} + +// cacheFilename is the name a file is cached under. A named repository's +// files are prefixed with its name and a hash of its upstream URL, so the +// same coordinates in two repositories, which may hold different bytes, are +// cached apart, and repointing a repository stops serving what the old +// upstream sent. +func (s mavenSource) cacheFilename(filename string) string { + return s.cachePrefix + filename +} + +// mavenUpstreamHashBytes is how much of the upstream URL's hash a named +// repository's cache filenames carry: enough to tell its upstreams apart. +const mavenUpstreamHashBytes = 8 + +func (h *MavenHandler) handleMetadata(w http.ResponseWriter, r *http.Request, source mavenSource, urlPath string) { + if h.cooldownEnabled() && h.serveCooldownMetadata(w, r, source, urlPath) { return } - h.proxy.writeMetadataCachedResponse(w, r, "maven", cacheKey, body, contentType) + // The checksums of maven-metadata.xml are computed from the cached + // metadata, as with cooldown, so they never describe another deploy. + if suffix, ok := strings.CutPrefix(path.Base(urlPath), mavenMetadataFile); ok && mavenChecksums[suffix] != nil { + res, _ := h.fetchMetadata(r.Context(), source, path.Join(path.Dir(urlPath), mavenMetadataFile)) + var body []byte + if res.err == nil { + body, res.err = h.proxy.decodedMetadataBody(res) + } + if res.err != nil { + h.writeMetadataError(w, res.err) + return + } + sum := mavenChecksums[suffix]() + _, _ = sum.Write(body) + w.Header().Set(headerContentType, "text/plain") + markStale(w, res.stale) + _, _ = io.WriteString(w, hex.EncodeToString(sum.Sum(nil))) + return + } + + res, _ := h.fetchMetadata(r.Context(), source, urlPath) + if res.err != nil { + h.writeMetadataError(w, res.err) + return + } + writeMetadataResult(w, r, res) +} + +// fetchMetadata fetches a metadata file from the source's upstream, or from +// its fallback when the upstream doesn't have it, and returns it with the +// key it is cached under. +func (h *MavenHandler) fetchMetadata(ctx context.Context, source mavenSource, urlPath string) (metadataResult, string) { + cacheKey := source.metadataCacheKey(urlPath) + upstreamURL := fmt.Sprintf("%s/%s", source.upstreamURL, urlPath) + + res := h.proxy.lookupMetadata(ctx, "maven", cacheKey, upstreamURL, "*/*", "", nil) + if res.err != nil && source.fallbackURL != "" { + if errors.Is(res.err, ErrUpstreamNotFound) { + pluginPortalURL := fmt.Sprintf("%s/%s", source.fallbackURL, urlPath) + h.proxy.Logger.Info("maven metadata unavailable in primary upstream, trying Gradle Plugin Portal", + "path", urlPath) + res = h.proxy.lookupMetadata(ctx, "maven", cacheKey, pluginPortalURL, "*/*", "", nil) + } + } + return res, cacheKey +} + +func (h *MavenHandler) writeMetadataError(w http.ResponseWriter, err error) { + if errors.Is(err, ErrUpstreamNotFound) { + http.Error(w, "not found", http.StatusNotFound) + return + } + if writeUpstreamHeld(w, err) { + return + } + h.proxy.Logger.Error("metadata fetch failed", "error", err) + http.Error(w, "failed to fetch from upstream", http.StatusBadGateway) } // handleDownload serves an artifact file, fetching and caching from upstream if needed. -func (h *MavenHandler) handleDownload(w http.ResponseWriter, r *http.Request, urlPath string) { +func (h *MavenHandler) handleDownload(w http.ResponseWriter, r *http.Request, source mavenSource, urlPath string) { // Parse Maven path: group/artifact/version/filename // e.g., com/google/guava/guava/32.1.3-jre/guava-32.1.3-jre.jar group, artifact, version, filename := h.parsePath(urlPath) if artifact == "" { - h.proxyUpstream(w, r) + if strings.Count(urlPath, "/") >= minMavenParts-1 { + // A dot or colon in a group directory, or a colon in the + // artifact, which the Maven layout never has. Proxied, the + // file would skip the denylist, scan and cooldown. + http.NotFound(w, r) + return + } + h.proxyUpstream(w, r, source, urlPath) + return + } + + // The .pom of a version whose time isn't known yet carries it in its + // own Last-Modified, so it is checked once fetched, without a request + // of its own. Maven fetches the .pom before a version's other files. + ctx, checkAfter := h.cooldownFromDownload(r.Context(), source, urlPath, version) + if !checkAfter && h.checkCooldown(w, r, source, urlPath, version) { return } // Maven uses group:artifact as the package name name := fmt.Sprintf("%s:%s", group, artifact) - h.proxy.Logger.Info("maven download request", + h.proxy.Logger.Debug("maven download request", "repository", source.name, "group", group, "artifact", artifact, "version", version, "filename", filename) - upstreamURL := fmt.Sprintf("%s/%s", h.upstreamURL, urlPath) + upstreamURL := fmt.Sprintf("%s/%s", source.upstreamURL, urlPath) + cacheFilename := source.cacheFilename(filename) - result, err := h.proxy.GetOrFetchArtifactFromURL(r.Context(), "maven", name, version, filename, upstreamURL) - if err != nil { + // Each build replaces a SNAPSHOT file named without a timestamp, so a + // GET fetches it again rather than serving the cached copy. HEAD is + // answered from cache. + get := h.proxy.GetOrFetchArtifactFromURL + if h.isMutableSnapshotFile(urlPath) && r.Method != http.MethodHead { + get = h.proxy.refetchArtifactFromURL + } + + result, err := get(ctx, "maven", name, version, cacheFilename, upstreamURL) + if err != nil && source.fallbackURL != "" { if errors.Is(err, ErrUpstreamNotFound) { - pluginPortalURL := fmt.Sprintf("%s/%s", h.pluginPortalUpstreamURL, urlPath) + pluginPortalURL := fmt.Sprintf("%s/%s", source.fallbackURL, urlPath) h.proxy.Logger.Info("maven artifact not found in primary upstream, trying Gradle Plugin Portal", "group", group, "artifact", artifact, "version", version, "filename", filename) - result, err = h.proxy.GetOrFetchArtifactFromURL(r.Context(), "maven", name, version, filename, pluginPortalURL) + result, err = get(ctx, "maven", name, version, cacheFilename, pluginPortalURL) } } if err != nil { h.proxy.serveArtifactError(w, err, "failed to fetch artifact") return } + if checkAfter && h.checkCooldown(w, r, source, urlPath, version) { + _ = result.Reader.Close() + return + } ServeArtifactRequest(w, r, result) } @@ -162,6 +301,7 @@ func (h *MavenHandler) handleDownload(w http.ResponseWriter, r *http.Request, ur // parsePath extracts Maven coordinates from a URL path. // e.g., "com/google/guava/guava/32.1.3-jre/guava-32.1.3-jre.jar" // -> ("com.google.guava", "guava", "32.1.3-jre", "guava-32.1.3-jre.jar") +// A path that isn't in the Maven layout returns empty strings. func (h *MavenHandler) parsePath(urlPath string) (group, artifact, version, filename string) { parts := strings.Split(urlPath, "/") if len(parts) < minMavenParts { @@ -172,6 +312,18 @@ func (h *MavenHandler) parsePath(urlPath string) (group, artifact, version, file version = parts[len(parts)-2] artifact = parts[len(parts)-3] groupParts := parts[:len(parts)-3] + // The Maven layout splits a group at its dots, so a group directory + // never holds a dot or is empty. Such a path would spell the same group + // as another and share its cache entries, so it is not parsed. Nor is a + // colon in the group or artifact, which are cached as group:artifact. + for _, part := range groupParts { + if part == "" || strings.ContainsAny(part, ".:") { + return "", "", "", "" + } + } + if strings.Contains(artifact, ":") { + return "", "", "", "" + } group = strings.Join(groupParts, ".") return group, artifact, version, filename @@ -193,6 +345,34 @@ func (h *MavenHandler) isArtifactFile(filename string) bool { return false } +// isCoordinateFile reports whether urlPath is a file named after the +// artifact and version of its directory, {artifact}-{version}..., as Maven +// names every file it publishes, whatever the extension. A SNAPSHOT's +// files carry a timestamp in place of "SNAPSHOT". +// +// The group isn't checked, so a file under a group directory outside the +// Maven layout still goes to handleDownload, which answers 404. +func (h *MavenHandler) isCoordinateFile(urlPath string) bool { + parts := strings.Split(urlPath, "/") + if len(parts) < minMavenParts { + return false + } + filename, version, artifact := parts[len(parts)-1], parts[len(parts)-2], parts[len(parts)-3] + if artifact == "" || version == "" { + return false + } + return strings.HasPrefix(filename, artifact+"-"+strings.TrimSuffix(version, "SNAPSHOT")) +} + +// isMutableSnapshotFile reports whether urlPath is a SNAPSHOT file named +// with "SNAPSHOT" rather than a build timestamp (lib-1.0-SNAPSHOT.jar), which +// each new build replaces. Timestamped SNAPSHOT files never change. +func (h *MavenHandler) isMutableSnapshotFile(urlPath string) bool { + _, artifact, version, filename := h.parsePath(urlPath) + return artifact != "" && strings.HasSuffix(version, mavenSnapshot) && + strings.HasPrefix(filename, artifact+"-"+version) +} + // isVersionListingFile matches maven-metadata.xml and its checksums. The // listing changes with every release, so it is cached for the metadata TTL // rather than kept like an artifact. @@ -212,7 +392,21 @@ func (h *MavenHandler) isChecksumFile(filename string) bool { return false } -// proxyUpstream forwards a request to Maven Central without caching. -func (h *MavenHandler) proxyUpstream(w http.ResponseWriter, r *http.Request) { - h.proxy.ProxyUpstream(w, r, h.upstreamURL+r.URL.Path, nil) +// mavenForwardHeaders lets clients resume artifacts proxied without caching. +var mavenForwardHeaders = []string{"Range", "If-Range"} + +// proxyUpstream forwards a request to the source's upstream without caching. +func (h *MavenHandler) proxyUpstream(w http.ResponseWriter, r *http.Request, source mavenSource, urlPath string) { + if source.fallbackURL == "" { + h.proxy.ProxyUpstream(w, r, source.upstreamURL+"/"+urlPath, mavenForwardHeaders) + return + } + // As for cached files, a file the primary upstream lacks is looked for + // on the Gradle Plugin Portal. + resp, err := h.proxy.upstreamRequest(r, source.upstreamURL+"/"+urlPath, mavenForwardHeaders) + if err == nil && resp.StatusCode == http.StatusNotFound { + _ = resp.Body.Close() + resp, err = h.proxy.upstreamRequest(r, source.fallbackURL+"/"+urlPath, mavenForwardHeaders) + } + h.proxy.relayUpstream(w, r, resp, err) } diff --git a/internal/handler/maven_consistency_test.go b/internal/handler/maven_consistency_test.go new file mode 100644 index 0000000..e548447 --- /dev/null +++ b/internal/handler/maven_consistency_test.go @@ -0,0 +1,157 @@ +package handler + +import ( + "crypto/sha1" //nolint:gosec // Maven publishes SHA-1 checksums. + "encoding/hex" + "io" + "net/http" + "net/http/httptest" + "sync/atomic" + "testing" + "time" + + "github.com/git-pkgs/registries/fetch" +) + +// mavenGenerations serves every path with the current generation's bytes, +// and a matching .sha1 for maven-metadata.xml, counting requests per path. +type mavenGenerations struct { + gen atomic.Int32 + requests map[string]*atomic.Int32 + // down makes every request fail with 502. + down atomic.Bool +} + +func (m *mavenGenerations) body(path string) string { + return path + " generation " + string(rune('0'+m.gen.Load())) +} + +func newMavenGenerations(t *testing.T, paths ...string) (*mavenGenerations, http.Handler) { + t.Helper() + m := &mavenGenerations{requests: map[string]*atomic.Int32{}} + for _, p := range paths { + m.requests[p] = &atomic.Int32{} + } + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if n := m.requests[r.URL.Path]; n != nil { + n.Add(1) + } + if m.down.Load() { + http.Error(w, "unavailable", http.StatusBadGateway) + return + } + const metadata = "/com/example/lib/maven-metadata.xml" + if r.URL.Path == metadata+".sha1" { + sum := sha1.Sum([]byte(m.body(metadata))) //nolint:gosec // as above + _, _ = io.WriteString(w, hex.EncodeToString(sum[:])) + return + } + _, _ = io.WriteString(w, m.body(r.URL.Path)) + })) + t.Cleanup(srv.Close) + + proxy, _, store, _ := setupTestProxy(t) + store.seekable = true + proxy.CacheMetadata = true + proxy.MetadataTTL = time.Hour + proxy.HTTPClient = srv.Client() + fetcher := fetch.NewFetcher(fetch.WithHTTPClient(srv.Client()), fetch.WithMaxRetries(0)) + proxy.Fetcher = fetcher + t.Cleanup(func() { _ = fetcher.Close() }) + return m, NewMavenHandler(proxy, "http://localhost", srv.URL, srv.URL).Routes() +} + +// TestMavenMetadataChecksumMatchesServedMetadata checks that the checksum +// files of maven-metadata.xml describe the metadata the proxy serves, even +// when upstream has deployed since it was cached. +func TestMavenMetadataChecksumMatchesServedMetadata(t *testing.T) { + m, h := newMavenGenerations(t) + const metadata = "/com/example/lib/maven-metadata.xml" + + served := getMaven(h, metadata).Body.String() + m.gen.Store(1) + w := getMaven(h, metadata+".sha1") + sum := sha1.Sum([]byte(served)) //nolint:gosec // as above + if w.Code != http.StatusOK || w.Body.String() != hex.EncodeToString(sum[:]) { + t.Errorf(".sha1 = %d %q, want the sha1 of the served metadata %x", w.Code, w.Body, sum) + } +} + +// TestMavenNonUniqueSnapshotNotKept checks that a SNAPSHOT file without a +// timestamp, which each build replaces, is not served from cache for good, +// while a timestamped one is. +func TestMavenNonUniqueSnapshotNotKept(t *testing.T) { + const ( + snapshot = "/com/example/lib/1.0-SNAPSHOT/lib-1.0-SNAPSHOT.jar" + timestamped = "/com/example/lib/1.0-SNAPSHOT/lib-1.0-20240101.120000-1.jar" + ) + m, h := newMavenGenerations(t, timestamped) + + getMaven(h, snapshot) + getMaven(h, snapshot+".sha1") + getMaven(h, timestamped) + m.gen.Store(1) + if w := getMaven(h, snapshot); w.Body.String() != m.body(snapshot) { + t.Errorf("SNAPSHOT jar = %q, want the new build %q", w.Body, m.body(snapshot)) + } + if w := getMaven(h, snapshot+".sha1"); w.Body.String() != m.body(snapshot+".sha1") { + t.Errorf("SNAPSHOT jar checksum = %q, want the new build's", w.Body) + } + if w := getMaven(h, timestamped); w.Code != http.StatusOK || m.requests[timestamped].Load() != 1 { + t.Errorf("timestamped SNAPSHOT jar fetched %d times, want once", m.requests[timestamped].Load()) + } +} + +// TestMavenMutableSnapshotKeepsPolicyAndFallback checks that a SNAPSHOT file +// fetched again for each request still goes through the denylist, and falls +// back to the Gradle Plugin Portal when the primary upstream lacks it. +func TestMavenMutableSnapshotKeepsPolicyAndFallback(t *testing.T) { + const snapshot = "/com/example/lib/1.0-SNAPSHOT/lib-1.0-SNAPSHOT.jar" + primary := httptest.NewServer(http.NotFoundHandler()) + t.Cleanup(primary.Close) + portal := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _, _ = io.WriteString(w, "portal build") + })) + t.Cleanup(portal.Close) + + proxy, _, store, _ := setupTestProxy(t) + store.seekable = true + proxy.HTTPClient = primary.Client() + fetcher := fetch.NewFetcher(fetch.WithHTTPClient(primary.Client()), fetch.WithMaxRetries(0)) + proxy.Fetcher = fetcher + t.Cleanup(func() { _ = fetcher.Close() }) + h := NewMavenHandler(proxy, "http://localhost", primary.URL, portal.URL).Routes() + + if w := getMaven(h, snapshot); w.Code != http.StatusOK || w.Body.String() != "portal build" { + t.Errorf("SNAPSHOT from the fallback = %d %q, want 200 portal build", w.Code, w.Body) + } + setTestDenylist(t, proxy, "pkg:maven/com.example/lib@1.0-SNAPSHOT") + if w := getMaven(h, snapshot); w.Code != http.StatusForbidden { + t.Errorf("denied SNAPSHOT = %d, want 403", w.Code) + } +} + +// TestMavenMutableSnapshotServesCacheWhenUpstreamFails checks that a +// SNAPSHOT file fetched again for each request is still served from cache +// while upstream is down, and that HEAD does not download it again. +func TestMavenMutableSnapshotServesCacheWhenUpstreamFails(t *testing.T) { + const snapshot = "/com/example/lib/1.0-SNAPSHOT/lib-1.0-SNAPSHOT.jar" + m, h := newMavenGenerations(t, snapshot) + + built := getMaven(h, snapshot).Body.String() + w := httptest.NewRecorder() + h.ServeHTTP(w, httptest.NewRequest(http.MethodHead, snapshot, nil)) + if w.Code != http.StatusOK || m.requests[snapshot].Load() != 1 { + t.Errorf("HEAD = %d after %d upstream requests, want 200 from cache", w.Code, m.requests[snapshot].Load()) + } + + m.down.Store(true) + if w := getMaven(h, snapshot); w.Code != http.StatusOK || w.Body.String() != built { + t.Errorf("SNAPSHOT while upstream is down = %d %q, want the cached build %q", w.Code, w.Body, built) + } + m.down.Store(false) + m.gen.Store(1) + if w := getMaven(h, snapshot); w.Body.String() != m.body(snapshot) { + t.Errorf("SNAPSHOT once upstream is back = %q, want the new build", w.Body) + } +} diff --git a/internal/handler/maven_cooldown.go b/internal/handler/maven_cooldown.go new file mode 100644 index 0000000..6155e0d --- /dev/null +++ b/internal/handler/maven_cooldown.go @@ -0,0 +1,476 @@ +package handler + +import ( + "bytes" + "context" + "crypto/md5" + "crypto/sha1" + "crypto/sha256" + "crypto/sha512" + "encoding/hex" + "encoding/xml" + "errors" + "fmt" + "hash" + "io" + "net/http" + "net/url" + "path" + "slices" + "strings" + "time" +) + +// Maven cooldown measures a version by the Last-Modified header of its .pom. +// On Maven Central that is the time the version was deployed. The header is +// read once per version and stored in the versions table, since release +// files don't change. +// +// maven-metadata.xml has a single for the whole artifact, so +// the proxy only looks at versions that can still be in cooldown: none when +// is older than the window, and otherwise the versions from +// the end of the list back to the first one that is old enough. Maven +// Central blocks clients that send bursts of requests, so the proxy doesn't +// read every version's time. +// +// SNAPSHOT versions are left alone: their files change after publishing. + +const errMavenCooldown = "version is in cooldown" + +// mavenTimeUserAgent is the User-Agent of publish-time requests, the one +// the artifact fetcher sends. +const mavenTimeUserAgent = "git-pkgs-proxy/1.0" + +const ( + mavenMetadataFile = "maven-metadata.xml" + mavenSnapshot = "-SNAPSHOT" + // mavenLastUpdatedLayout is the UTC timestamp format of . + mavenLastUpdatedLayout = "20060102150405" +) + +// mavenChecksums are the checksum files served beside maven-metadata.xml. +// With cooldown on they are computed from the metadata as served. +var mavenChecksums = map[string]func() hash.Hash{ + ".md5": md5.New, + ".sha1": sha1.New, + ".sha256": sha256.New, + ".sha512": sha512.New, +} + +func (h *MavenHandler) cooldownEnabled() bool { + return h.proxy.Cooldown != nil && h.proxy.Cooldown.Enabled() +} + +func mavenPackagePURL(group, artifact string) string { + return canonicalPackagePURL("maven", group+":"+artifact) +} + +// mavenCoordinates returns the group and artifact of an artifact directory +// such as com/google/guava/guava. +func mavenCoordinates(artifactDir string) (group, artifact string, ok bool) { + i := strings.LastIndex(artifactDir, "/") + if i <= 0 || i == len(artifactDir)-1 { + return "", "", false + } + return strings.ReplaceAll(artifactDir[:i], "/", "."), artifactDir[i+1:], true +} + +// usableMavenVersion reports whether version can be put in a URL path as +// one segment. Versions come from upstream metadata. +func usableMavenVersion(version string) bool { + return version != "" && version != "." && version != ".." && !strings.ContainsAny(version, "/\\?#%") +} + +// mavenTimeKey returns the versions-table PURLs a version's time is stored +// under. A named repository's keys carry its upstream as repository_url: +// the same coordinates there can have been published at another time than +// in the default repository. +func (h *MavenHandler) mavenTimeKey(source mavenSource, group, artifact, version string) (versionPURL, packagePURL string, ok bool) { + if h.proxy.DB == nil { + return "", "", false + } + name := group + ":" + artifact + versionPURL, packagePURL = canonicalVersionPURL("maven", name, version), canonicalPackagePURL("maven", name) + if source.name != "" { + qualifier := "?repository_url=" + url.QueryEscape(source.upstreamURL) + versionPURL += qualifier + packagePURL += qualifier + } + return versionPURL, packagePURL, true +} + +// publishTime returns a version's publish time from the versions table, or +// from the Last-Modified of its .pom, which is then stored. A version +// without a .pom, or whose .pom has no Last-Modified, gets the zero time and +// is let through, as in the other ecosystems. A failed request is an error, +// so a rate-limited upstream can't let a version through. +func (h *MavenHandler) publishTime(ctx context.Context, source mavenSource, artifactDir, version string) (time.Time, error) { + group, artifact, ok := mavenCoordinates(artifactDir) + if !ok || !usableMavenVersion(version) { + return time.Time{}, nil + } + versionPURL, packagePURL, store := h.mavenTimeKey(source, group, artifact, version) + if store { + if ver, err := h.proxy.DB.GetVersionByPURL(versionPURL); err == nil && ver != nil && ver.PublishedAt.Valid { + return ver.PublishedAt.Time, nil + } + } + + pomPath := artifactDir + "/" + version + "/" + artifact + "-" + version + ".pom" + published, found, err := h.pomLastModified(ctx, source.upstreamURL+"/"+pomPath) + if err == nil && !found && source.fallbackURL != "" { + published, _, err = h.pomLastModified(ctx, source.fallbackURL+"/"+pomPath) + } + if err != nil { + return time.Time{}, err + } + if store && !published.IsZero() { + if err := h.proxy.DB.SetVersionPublishedAt(versionPURL, packagePURL, published); err != nil { + h.proxy.Logger.Warn("cooldown: could not store maven publish time", + "group", group, "artifact", artifact, "version", version, "error", err) + } + } + return published, nil +} + +// cooldownFromDownload returns a context that stores the publish time of a +// version from the download of its .pom or Gradle .module, and whether the +// cooldown check is to run after the download. It does so only for those +// files of a version whose time is not stored yet; for anything else the +// check runs before. Both files are deployed with the version, and +// whichever a client fetches first gives its time. +func (h *MavenHandler) cooldownFromDownload(ctx context.Context, source mavenSource, urlPath, version string) (context.Context, bool) { + if !h.cooldownEnabled() || strings.HasSuffix(version, mavenSnapshot) { + return ctx, false + } + artifactDir := path.Dir(path.Dir(urlPath)) + group, artifact, ok := mavenCoordinates(artifactDir) + if base := artifact + "-" + version; !ok || !usableMavenVersion(version) || + (path.Base(urlPath) != base+".pom" && path.Base(urlPath) != base+".module") { + return ctx, false + } + versionPURL, packagePURL, store := h.mavenTimeKey(source, group, artifact, version) + if !store { + return ctx, false + } + if ver, err := h.proxy.DB.GetVersionByPURL(versionPURL); err == nil && ver != nil && ver.PublishedAt.Valid { + return ctx, false + } + return WithUpstreamLastModified(ctx, func(published time.Time) { + if err := h.proxy.DB.SetVersionPublishedAt(versionPURL, packagePURL, published); err != nil { + h.proxy.Logger.Warn("cooldown: could not store maven publish time", + "group", group, "artifact", artifact, "version", version, "error", err) + } + }), true +} + +// pomLastModified sends a HEAD request for a .pom and returns its +// Last-Modified. found is false when upstream doesn't have the file. Only a +// 2xx response's header is used: an error page's date says nothing about the +// version. +func (h *MavenHandler) pomLastModified(ctx context.Context, pomURL string) (published time.Time, found bool, err error) { + req, err := http.NewRequestWithContext(ctx, http.MethodHead, pomURL, nil) + if err != nil { + return time.Time{}, false, err + } + // Name the proxy as its artifact downloads do; Maven Central asks + // tools not to send an HTTP library's default. + req.Header.Set("User-Agent", mavenTimeUserAgent) + resp, err := h.proxy.HTTPClient.Do(req) + if err != nil { + return time.Time{}, false, fmt.Errorf("reading pom time: %w", err) + } + _ = resp.Body.Close() + switch { + case resp.StatusCode == http.StatusNotFound || resp.StatusCode == http.StatusGone: + return time.Time{}, false, nil + case resp.StatusCode == http.StatusTooManyRequests && h.proxy.RateLimits != nil: + // The gate has just noted the upstream's Retry-After; pass it on. + if err := h.proxy.RateLimits.Held(pomURL); err != nil { + return time.Time{}, false, err + } + return time.Time{}, false, fmt.Errorf("reading pom time: upstream returned %d", resp.StatusCode) + case resp.StatusCode < 200 || resp.StatusCode > 299: + return time.Time{}, false, fmt.Errorf("reading pom time: upstream returned %d", resp.StatusCode) + } + published, err = http.ParseTime(resp.Header.Get(headerLastModified)) + if err != nil { + return time.Time{}, true, nil + } + return published, true, nil +} + +// checkCooldown answers a request for a file of a version in cooldown, or +// whose time couldn't be read, and reports whether it did. The answer is +// 403, as for a version on the denylist. +func (h *MavenHandler) checkCooldown(w http.ResponseWriter, r *http.Request, source mavenSource, urlPath, version string) bool { + if !h.cooldownEnabled() || strings.HasSuffix(version, mavenSnapshot) { + return false + } + artifactDir := path.Dir(path.Dir(urlPath)) + group, artifact, ok := mavenCoordinates(artifactDir) + if !ok || h.proxy.Cooldown.For("maven", mavenPackagePURL(group, artifact)) == 0 { + return false + } + published, err := h.publishTime(r.Context(), source, artifactDir, version) + if err != nil { + if writeUpstreamHeld(w, err) { + return true + } + h.proxy.Logger.Warn("cooldown: could not read maven version time", + "group", group, "artifact", artifact, "version", version, "error", err) + http.Error(w, "failed to check cooldown", http.StatusBadGateway) + return true + } + if !h.proxy.cooldown().IsAllowed("maven", mavenPackagePURL(group, artifact), published) { + h.proxy.Logger.Info("cooldown: withholding maven version", + "group", group, "artifact", artifact, "version", version) + http.Error(w, errMavenCooldown+": "+canonicalVersionPURL("maven", group+":"+artifact, version), http.StatusForbidden) + return true + } + return false +} + +// serveCooldownMetadata serves maven-metadata.xml without versions in +// cooldown, and its checksum files computed from what is served. It reports +// false for other files beside the metadata, such as a signature, when the +// metadata is served unchanged, so they are proxied as usual. +func (h *MavenHandler) serveCooldownMetadata(w http.ResponseWriter, r *http.Request, source mavenSource, urlPath string) bool { + filename := path.Base(urlPath) + suffix, ok := strings.CutPrefix(filename, mavenMetadataFile) + if !ok { + return false + } + metadataPath := path.Join(path.Dir(urlPath), mavenMetadataFile) + res, cacheKey := h.fetchMetadata(r.Context(), source, metadataPath) + if res.err != nil { + h.writeMetadataError(w, res.err) + return true + } + body, contentType := res.body, res.contentType + + m, err := h.proxy.cachedRewrite(r.Context(), "maven", h.proxyURL, cacheKey, body, "", func(in []byte) ([]byte, []string, error) { + // The rewrite is shared by requests waiting on it and cached, so it + // finishes even if the request that started it goes away. + out, err := h.filterMetadata(context.WithoutCancel(r.Context()), source, path.Dir(urlPath), in) + return out, nil, err + }) + if err != nil { + if r.Context().Err() != nil { + return true + } + if writeUpstreamHeld(w, err) { + return true + } + h.proxy.Logger.Warn("cooldown: could not filter maven metadata", "path", metadataPath, "error", err) + http.Error(w, "failed to check cooldown", http.StatusBadGateway) + return true + } + + switch { + case suffix == "": + // The metadata cache records JSON when an upstream sent no type, + // and maven-metadata.xml is always XML. + if contentType == "" || contentType == contentTypeJSON { + contentType = "text/xml" + } + markStale(w, res.stale) + serveRewrittenMetadataAs(w, r, m, contentType) + case mavenChecksums[suffix] != nil: + sum := mavenChecksums[suffix]() + _, _ = sum.Write(m.content()) + w.Header().Set(headerContentType, "text/plain") + _, _ = io.WriteString(w, hex.EncodeToString(sum.Sum(nil))) + case bytes.Equal(m.content(), body): + return false + default: + // A signature of the upstream metadata doesn't match what is served. + http.Error(w, "not found", http.StatusNotFound) + } + return true +} + +// filterMetadata removes versions in cooldown from an artifact's +// maven-metadata.xml and points and at the newest +// versions left. Metadata without a version list, such as a group's plugin +// list or a SNAPSHOT's build list, is returned unchanged. The document is +// edited in place rather than encoded again, so everything else in it stays +// as upstream sent it. +func (h *MavenHandler) filterMetadata(ctx context.Context, source mavenSource, artifactDir string, body []byte) ([]byte, error) { + doc, err := parseMavenMetadata(body) + if err != nil { + return nil, err + } + group, artifact, ok := mavenCoordinates(artifactDir) + if !ok || len(doc.versions) == 0 { + return body, nil + } + packagePURL := mavenPackagePURL(group, artifact) + // No version can be newer than the metadata listing it. + if lastUpdated, err := time.Parse(mavenLastUpdatedLayout, doc.lastUpdated); err == nil && + h.proxy.cooldown().IsAllowed("maven", packagePURL, lastUpdated) { + return body, nil + } + + removed := map[string]bool{} + for i := len(doc.versions) - 1; i >= 0; i-- { + v := doc.versions[i].value + if strings.HasSuffix(v, mavenSnapshot) { + continue + } + published, err := h.publishTime(ctx, source, artifactDir, v) + if err != nil { + return nil, fmt.Errorf("reading time of %s: %w", v, err) + } + if published.IsZero() { + continue + } + if h.proxy.cooldown().IsAllowed("maven", packagePURL, published) { + break + } + h.proxy.Logger.Info("cooldown: filtering maven version", "group", group, "artifact", artifact, "version", v) + removed[v] = true + } + if len(removed) == 0 { + return body, nil + } + return doc.without(body, removed), nil +} + +// mavenElement is an element of maven-metadata.xml: its text and where it +// starts and ends in the document. +type mavenElement struct { + value string + start, end int +} + +type mavenMetadata struct { + versions []mavenElement + latest, release *mavenElement + lastUpdated string +} + +// parseMavenMetadata reads the version list, , and +// of a maven-metadata.xml, with their offsets. +func parseMavenMetadata(body []byte) (*mavenMetadata, error) { + dec := xml.NewDecoder(bytes.NewReader(body)) + // Versions are ASCII, so any declared charset can be read as bytes. + dec.CharsetReader = func(_ string, in io.Reader) (io.Reader, error) { return in, nil } + + doc := &mavenMetadata{} + var stack []string + var current *mavenElement + for { + offset := int(dec.InputOffset()) + tok, err := dec.Token() + if errors.Is(err, io.EOF) { + break + } + if err != nil { + return nil, fmt.Errorf("parsing maven metadata: %w", err) + } + switch t := tok.(type) { + case xml.StartElement: + stack = append(stack, t.Name.Local) + switch strings.Join(stack, "/") { + case "metadata/versioning/versions/version", + "metadata/versioning/latest", + "metadata/versioning/release", + "metadata/versioning/lastUpdated": + current = &mavenElement{start: offset} + } + case xml.CharData: + if current != nil { + current.value += string(t) + } + case xml.EndElement: + if current != nil { + current.value = strings.TrimSpace(current.value) + current.end = int(dec.InputOffset()) + switch t.Name.Local { + case "version": + doc.versions = append(doc.versions, *current) + case "latest": + doc.latest = current + case "release": + doc.release = current + case "lastUpdated": + doc.lastUpdated = current.value + } + current = nil + } + if len(stack) > 0 { + stack = stack[:len(stack)-1] + } + } + } + return doc, nil +} + +// without returns body with the removed versions taken out of the version +// list, and and set to the last versions left in list +// order, which is how the repository chose them. Either is dropped when no +// version is left for it. +func (doc *mavenMetadata) without(body []byte, removed map[string]bool) []byte { + type edit struct { + start, end int + text string + } + var edits []edit + drop := func(e mavenElement) { + edits = append(edits, edit{start: lineStart(body, e.start), end: e.end}) + } + var latest, release string + for _, v := range doc.versions { + if removed[v.value] { + drop(v) + continue + } + latest = v.value + if !strings.HasSuffix(v.value, mavenSnapshot) { + release = v.value + } + } + for _, field := range []struct { + el *mavenElement + name string + next string + }{{doc.latest, "latest", latest}, {doc.release, "release", release}} { + if field.el == nil || !removed[field.el.value] { + continue + } + if field.next == "" { + drop(*field.el) + continue + } + edits = append(edits, edit{field.el.start, field.el.end, "<" + field.name + ">" + field.next + ""}) + } + + // Edits don't overlap; apply them in document order. + slices.SortFunc(edits, func(a, b edit) int { return a.start - b.start }) + out := make([]byte, 0, len(body)) + pos := 0 + for _, e := range edits { + out = append(out, body[pos:e.start]...) + out = append(out, e.text...) + pos = e.end + } + return append(out, body[pos:]...) +} + +// lineStart moves an element's start back over the indentation and line +// break before it, so removing the element removes its line. +func lineStart(body []byte, start int) int { + i := start + for i > 0 && (body[i-1] == ' ' || body[i-1] == '\t') { + i-- + } + if i > 0 && body[i-1] == '\n' { + i-- + if i > 0 && body[i-1] == '\r' { + i-- + } + return i + } + return start +} diff --git a/internal/handler/maven_cooldown_test.go b/internal/handler/maven_cooldown_test.go new file mode 100644 index 0000000..828d1ff --- /dev/null +++ b/internal/handler/maven_cooldown_test.go @@ -0,0 +1,530 @@ +package handler + +import ( + "compress/gzip" + "crypto/md5" + "crypto/sha1" + "crypto/sha256" + "crypto/sha512" + "encoding/hex" + "fmt" + "hash" + "io" + "net/http" + "net/http/httptest" + "slices" + "strings" + "sync" + "testing" + "time" + + "github.com/git-pkgs/cooldown" + registryclient "github.com/git-pkgs/registries/client" + "github.com/git-pkgs/registries/fetch" +) + +const mavenTestDir = "/com/example/lib/" + +// mavenCooldownUpstream serves com.example:lib. Each version's .pom has the +// Last-Modified in times; pomStatus overrides the status of a version's +// .pom. Requests for .pom files are counted. +type mavenCooldownUpstream struct { + server *httptest.Server + versions []string + latest string + release string + lastUpdated time.Time + times map[string]time.Time + pomStatus map[string]int + + mu sync.Mutex + poms map[string]int + heads int + userAgents []string +} + +func newMavenCooldownUpstream(t *testing.T) *mavenCooldownUpstream { + t.Helper() + now := time.Now() + u := &mavenCooldownUpstream{ + versions: []string{"1.0", "1.1", "2.0", "2.1", "3.0-SNAPSHOT"}, + latest: "3.0-SNAPSHOT", + release: "2.1", + lastUpdated: now.Add(-time.Hour), + times: map[string]time.Time{ + "1.0": now.Add(-30 * 24 * time.Hour), + "1.1": now.Add(-10 * 24 * time.Hour), + "2.0": now.Add(-2 * time.Hour), + "2.1": now.Add(-time.Hour), + "3.0-SNAPSHOT": now.Add(-time.Minute), + }, + pomStatus: map[string]int{}, + poms: map[string]int{}, + } + u.server = httptest.NewServer(http.HandlerFunc(u.serve)) + t.Cleanup(u.server.Close) + return u +} + +// serve answers for the default upstream and, under /portal, for the +// Gradle Plugin Portal fallback alike. +func (u *mavenCooldownUpstream) serve(w http.ResponseWriter, r *http.Request) { + rest, ok := strings.CutPrefix(strings.TrimPrefix(r.URL.Path, "/portal"), mavenTestDir) + if !ok { + http.NotFound(w, r) + return + } + switch rest { + case "maven-metadata.xml": + _, _ = w.Write([]byte(u.metadata())) + return + case "maven-metadata.xml.asc": + _, _ = w.Write([]byte("signature")) + return + } + version, file, _ := strings.Cut(rest, "/") + published, known := u.times[version] + if !known { + http.NotFound(w, r) + return + } + if strings.HasSuffix(file, ".module") { + w.Header().Set(headerLastModified, published.UTC().Format(http.TimeFormat)) + } + if strings.HasSuffix(file, ".pom") { + u.mu.Lock() + u.poms[version]++ + if r.Method == http.MethodHead { + u.heads++ + u.userAgents = append(u.userAgents, r.UserAgent()) + } + u.mu.Unlock() + w.Header().Set(headerLastModified, published.UTC().Format(http.TimeFormat)) + if status := u.pomStatus[version]; status != 0 { + // An error page dated long ago must not count as an old version. + w.Header().Set(headerLastModified, time.Unix(0, 0).UTC().Format(http.TimeFormat)) + if status == http.StatusTooManyRequests { + w.Header().Set("Retry-After", "60") + } + w.WriteHeader(status) + return + } + } + _, _ = w.Write([]byte(file + " of " + version)) +} + +func (u *mavenCooldownUpstream) metadata() string { + var b strings.Builder + b.WriteString("\n\n com.example\n lib\n \n") + b.WriteString(" " + u.latest + "\n " + u.release + "\n \n") + for _, v := range u.versions { + b.WriteString(" " + v + "\n") + } + b.WriteString(" \n " + u.lastUpdated.UTC().Format(mavenLastUpdatedLayout) + "\n \n\n") + return b.String() +} + +// pomRequests returns how many requests each version's .pom got. +func (u *mavenCooldownUpstream) pomRequests() map[string]int { + u.mu.Lock() + defer u.mu.Unlock() + out := make(map[string]int, len(u.poms)) + for v, n := range u.poms { + out[v] = n + } + return out +} + +func (u *mavenCooldownUpstream) totalPOMRequests() int { + total := 0 + for _, n := range u.pomRequests() { + total += n + } + return total +} + +func newMavenCooldownHandler(t *testing.T, u *mavenCooldownUpstream) (http.Handler, *Proxy) { + t.Helper() + proxy, _, store, _ := setupTestProxy(t) + store.seekable = true + proxy.HTTPClient = u.server.Client() + fetcher := fetch.NewFetcher(fetch.WithHTTPClient(u.server.Client()), fetch.WithMaxRetries(0)) + proxy.Fetcher = fetcher + t.Cleanup(func() { _ = fetcher.Close() }) + proxy.Cooldown = &cooldown.Config{Default: "3d"} + return NewMavenHandler(proxy, "http://localhost", u.server.URL, u.server.URL+"/portal").Routes(), proxy +} + +func mavenMetadataVersions(t *testing.T, body string) []string { + t.Helper() + doc, err := parseMavenMetadata([]byte(body)) + if err != nil { + t.Fatalf("served metadata does not parse: %v\n%s", err, body) + } + var versions []string + for _, v := range doc.versions { + versions = append(versions, v.value) + } + return versions +} + +func TestMavenCooldownFiltersMetadata(t *testing.T) { + u := newMavenCooldownUpstream(t) + h, proxy := newMavenCooldownHandler(t, u) + + w := getMaven(h, mavenTestDir+"maven-metadata.xml") + if w.Code != http.StatusOK { + t.Fatalf("status = %d: %s", w.Code, w.Body) + } + body := w.Body.String() + if got := strings.Join(mavenMetadataVersions(t, body), " "); got != "1.0 1.1 3.0-SNAPSHOT" { + t.Errorf("versions = %s, want 1.0 1.1 3.0-SNAPSHOT", got) + } + if !strings.Contains(body, "1.1") || !strings.Contains(body, "3.0-SNAPSHOT") { + t.Errorf("release or latest not recomputed:\n%s", body) + } + if strings.Contains(body, "\n\n") { + t.Errorf("removed versions left blank lines:\n%s", body) + } + + // The walk stops at 1.1, the first version old enough, and skips the + // SNAPSHOT. + want := map[string]int{"2.1": 1, "2.0": 1, "1.1": 1} + if got := u.pomRequests(); len(got) != len(want) || got["2.1"] != 1 || got["2.0"] != 1 || got["1.1"] != 1 { + t.Errorf("pom requests = %v, want %v", got, want) + } + + // Times are stored, so the next request makes no .pom requests. + ver, err := proxy.DB.GetVersionByPURL(canonicalVersionPURL("maven", "com.example:lib", "2.1")) + if err != nil || ver == nil || !ver.PublishedAt.Valid { + t.Fatalf("time of 2.1 not stored: %v %v", ver, err) + } + if w := getMaven(h, mavenTestDir+"maven-metadata.xml"); w.Body.String() != body { + t.Errorf("second response differs:\n%s", w.Body) + } + if n := u.totalPOMRequests(); n != 3 { + t.Errorf("pom requests after second metadata request = %d, want 3", n) + } +} + +func TestMavenCooldownRecomputesLatest(t *testing.T) { + u := newMavenCooldownUpstream(t) + u.versions = []string{"1.0", "1.1", "2.0", "2.1"} + u.latest = "2.1" + h, _ := newMavenCooldownHandler(t, u) + + body := getMaven(h, mavenTestDir+"maven-metadata.xml").Body.String() + if !strings.Contains(body, "1.1") || !strings.Contains(body, "1.1") { + t.Errorf("latest and release should be 1.1:\n%s", body) + } +} + +func TestMavenCooldownDropsLatestWhenNothingIsLeft(t *testing.T) { + u := newMavenCooldownUpstream(t) + u.versions = []string{"2.0", "2.1"} + u.latest = "2.1" + h, _ := newMavenCooldownHandler(t, u) + + body := getMaven(h, mavenTestDir+"maven-metadata.xml").Body.String() + if strings.Contains(body, "") || strings.Contains(body, "") || strings.Contains(body, "") { + t.Errorf("no version is out of cooldown:\n%s", body) + } + if !strings.Contains(body, "\n ") { + t.Errorf("version list not emptied in place:\n%s", body) + } +} + +func TestMavenCooldownChecksumsMatchMetadata(t *testing.T) { + u := newMavenCooldownUpstream(t) + h, _ := newMavenCooldownHandler(t, u) + + body := getMaven(h, mavenTestDir+"maven-metadata.xml").Body.Bytes() + for suffix, newHash := range map[string]func() hash.Hash{ + ".md5": md5.New, ".sha1": sha1.New, ".sha256": sha256.New, ".sha512": sha512.New, + } { + sum := newHash() + _, _ = sum.Write(body) + w := getMaven(h, mavenTestDir+"maven-metadata.xml"+suffix) + if w.Code != http.StatusOK || w.Body.String() != hex.EncodeToString(sum.Sum(nil)) { + t.Errorf("%s: status = %d body %q, want checksum of served metadata", suffix, w.Code, w.Body) + } + } + // A signature of the upstream metadata would not match. + if w := getMaven(h, mavenTestDir+"maven-metadata.xml.asc"); w.Code != http.StatusNotFound { + t.Errorf(".asc status = %d, want 404", w.Code) + } + + // Unchanged metadata keeps its signature. + u.lastUpdated = time.Now().Add(-4 * 24 * time.Hour) + if w := getMaven(h, mavenTestDir+"maven-metadata.xml.asc"); w.Code != http.StatusOK || w.Body.String() != "signature" { + t.Errorf("unchanged .asc: status = %d body %q, want upstream's", w.Code, w.Body) + } +} + +func TestMavenCooldownRefusesFiles(t *testing.T) { + u := newMavenCooldownUpstream(t) + h, _ := newMavenCooldownHandler(t, u) + + for _, file := range []string{"2.1/lib-2.1.pom", "2.1/lib-2.1.jar", "2.1/lib-2.1.jar.sha1", "2.0/lib-2.0-sources.jar"} { + w := getMaven(h, mavenTestDir+file) + if w.Code != http.StatusForbidden || !strings.Contains(w.Body.String(), errMavenCooldown) { + t.Errorf("%s: status = %d body %q, want 403 cooldown", file, w.Code, w.Body) + } + } + for _, file := range []string{"1.1/lib-1.1.jar", "3.0-SNAPSHOT/lib-3.0-SNAPSHOT.jar"} { + if w := getMaven(h, mavenTestDir+file); w.Code != http.StatusOK { + t.Errorf("%s: status = %d, want 200", file, w.Code) + } + } + // One .pom request per version, none for the SNAPSHOT. + if got := u.pomRequests(); got["2.1"] != 1 || got["2.0"] != 1 || got["1.1"] != 1 || got["3.0-SNAPSHOT"] != 0 { + t.Errorf("pom requests = %v", got) + } +} + +// TestMavenCooldownPOMDownloadCarriesItsTime checks that a build fetching +// pinned versions, which never reads maven-metadata.xml, costs no requests +// beyond its downloads: the .pom's own Last-Modified gives the version's +// time, and Maven fetches the .pom before the version's other files. +func TestMavenCooldownPOMDownloadCarriesItsTime(t *testing.T) { + u := newMavenCooldownUpstream(t) + h, proxy := newMavenCooldownHandler(t, u) + + for _, c := range []struct { + file string + want int + }{ + {"2.1/lib-2.1.pom", http.StatusForbidden}, + {"2.1/lib-2.1.jar", http.StatusForbidden}, + {"1.0/lib-1.0.pom", http.StatusOK}, + {"1.0/lib-1.0.jar", http.StatusOK}, + } { + if w := getMaven(h, mavenTestDir+c.file); w.Code != c.want { + t.Errorf("%s: status = %d, want %d", c.file, w.Code, c.want) + } + } + u.mu.Lock() + heads := u.heads + u.mu.Unlock() + if heads != 0 { + t.Errorf("HEAD requests = %d, want 0", heads) + } + if got := u.pomRequests(); got["2.1"] != 1 || got["1.0"] != 1 { + t.Errorf("pom requests = %v, want one GET each", got) + } + ver, _ := proxy.DB.GetVersionByPURL(canonicalVersionPURL("maven", "com.example:lib", "2.1")) + if ver == nil || !ver.PublishedAt.Valid || !ver.PublishedAt.Time.Equal(u.times["2.1"].Truncate(time.Second)) { + t.Errorf("stored time of 2.1 = %v, want %v", ver, u.times["2.1"]) + } +} + +// TestMavenCooldownModuleDownloadCarriesItsTime checks that a Gradle +// .module fetched before the .pom gives the version's time as the .pom +// would. +func TestMavenCooldownModuleDownloadCarriesItsTime(t *testing.T) { + u := newMavenCooldownUpstream(t) + h, _ := newMavenCooldownHandler(t, u) + + if w := getMaven(h, mavenTestDir+"2.1/lib-2.1.module"); w.Code != http.StatusForbidden { + t.Errorf("2.1 .module: status = %d, want 403", w.Code) + } + if w := getMaven(h, mavenTestDir+"1.0/lib-1.0.module"); w.Code != http.StatusOK { + t.Errorf("1.0 .module: status = %d, want 200", w.Code) + } + if w := getMaven(h, mavenTestDir+"1.0/lib-1.0.jar"); w.Code != http.StatusOK { + t.Errorf("1.0 .jar: status = %d, want 200", w.Code) + } + if n := u.totalPOMRequests(); n != 0 { + t.Errorf("pom requests = %d, want 0", n) + } +} + +// TestMavenCooldownTimeRequestsNameTheProxy checks the User-Agent of the +// HEAD requests for publish times: Maven Central asks tools to name +// themselves rather than send an HTTP library's default. +func TestMavenCooldownTimeRequestsNameTheProxy(t *testing.T) { + u := newMavenCooldownUpstream(t) + h, _ := newMavenCooldownHandler(t, u) + + getMaven(h, mavenTestDir+"maven-metadata.xml") + u.mu.Lock() + defer u.mu.Unlock() + if len(u.userAgents) == 0 { + t.Fatal("no HEAD requests") + } + for _, ua := range u.userAgents { + if ua != mavenTimeUserAgent { + t.Errorf("User-Agent = %q, want %q", ua, mavenTimeUserAgent) + } + } +} + +// TestMavenCooldownMetadataServedLikeOtherRewrites checks that filtered +// metadata is gzip-compressed for clients that accept it, as the other +// ecosystems' rewritten metadata is. +func TestMavenCooldownMetadataServedLikeOtherRewrites(t *testing.T) { + u := newMavenCooldownUpstream(t) + // Enough versions that the document compresses. + for i := range 50 { + v := fmt.Sprintf("0.%d", i) + u.versions = append([]string{v}, u.versions...) + u.times[v] = time.Now().Add(-100 * 24 * time.Hour) + } + h, proxy := newMavenCooldownHandler(t, u) + // The server always sets up the rewrite cache, which keeps the gzip copy. + proxy.SetMetadataRewriteCacheSize(1 << 20) + + req := httptest.NewRequest(http.MethodGet, mavenTestDir+"maven-metadata.xml", nil) + req.Header.Set(headerAcceptEncoding, "gzip") + w := httptest.NewRecorder() + h.ServeHTTP(w, req) + if w.Code != http.StatusOK || w.Header().Get(headerContentEncoding) != "gzip" { + t.Fatalf("status = %d, Content-Encoding %q; want gzip", w.Code, w.Header().Get(headerContentEncoding)) + } + if ct := w.Header().Get(headerContentType); !strings.Contains(ct, "xml") { + t.Errorf("Content-Type = %q, want XML", ct) + } + zr, err := gzip.NewReader(w.Body) + if err != nil { + t.Fatal(err) + } + body, _ := io.ReadAll(zr) + if versions := mavenMetadataVersions(t, string(body)); slices.Contains(versions, "2.1") { + t.Errorf("2.1 listed in the gzip body: %v", versions) + } +} + +func TestMavenCooldownOldLastUpdatedSkipsPOMs(t *testing.T) { + u := newMavenCooldownUpstream(t) + u.lastUpdated = time.Now().Add(-4 * 24 * time.Hour) + // The times would filter 2.0 and 2.1 if they were read. + h, _ := newMavenCooldownHandler(t, u) + + w := getMaven(h, mavenTestDir+"maven-metadata.xml") + if w.Body.String() != u.metadata() { + t.Errorf("metadata changed:\n%s", w.Body) + } + if n := u.totalPOMRequests(); n != 0 { + t.Errorf("pom requests = %d, want 0", n) + } +} + +func TestMavenCooldownIgnoresNon2xxPOMResponses(t *testing.T) { + u := newMavenCooldownUpstream(t) + u.pomStatus["2.1"] = http.StatusNotFound + h, proxy := newMavenCooldownHandler(t, u) + + // A missing .pom gives no time: 2.1 stays listed, and the walk goes on + // to 2.0 rather than stopping at the error page's old date. + versions := mavenMetadataVersions(t, getMaven(h, mavenTestDir+"maven-metadata.xml").Body.String()) + if got := strings.Join(versions, " "); got != "1.0 1.1 2.1 3.0-SNAPSHOT" { + t.Errorf("versions = %s, want 1.0 1.1 2.1 3.0-SNAPSHOT", got) + } + if ver, _ := proxy.DB.GetVersionByPURL(canonicalVersionPURL("maven", "com.example:lib", "2.1")); ver != nil && ver.PublishedAt.Valid { + t.Errorf("time of a 404 stored: %v", ver.PublishedAt.Time) + } + + // Any other error fails closed. + u.pomStatus["2.1"] = http.StatusTooManyRequests + for _, p := range []string{"maven-metadata.xml", "maven-metadata.xml.sha1", "2.1/lib-2.1.jar"} { + if w := getMaven(h, mavenTestDir+p); w.Code != http.StatusBadGateway { + t.Errorf("%s: status = %d, want 502", p, w.Code) + } + } + if ver, _ := proxy.DB.GetVersionByPURL(canonicalVersionPURL("maven", "com.example:lib", "2.1")); ver != nil && ver.PublishedAt.Valid { + t.Errorf("time of a 429 stored: %v", ver.PublishedAt.Time) + } +} + +// TestMavenCooldownRateLimitedPOMIsHeld checks that a 429 on a .pom time +// request is answered like any held upstream request, with 503 and the +// upstream's Retry-After, so clients wait instead of failing the build. +func TestMavenCooldownRateLimitedPOMIsHeld(t *testing.T) { + u := newMavenCooldownUpstream(t) + u.pomStatus["2.0"] = http.StatusTooManyRequests + h, proxy := newMavenCooldownHandler(t, u) + gate := registryclient.NewRateLimitGate(u.server.Client().Transport) + proxy.HTTPClient = &http.Client{Transport: gate} + proxy.RateLimits = gate + + // Not the .pom, so its time is read with a HEAD. + w := getMaven(h, mavenTestDir+"2.0/lib-2.0.jar") + if w.Code != http.StatusServiceUnavailable || w.Header().Get("Retry-After") == "" { + t.Errorf("status = %d, Retry-After %q; want 503 with Retry-After", w.Code, w.Header().Get("Retry-After")) + } +} + +func TestMavenCooldownDisabledPassesThrough(t *testing.T) { + u := newMavenCooldownUpstream(t) + h, proxy := newMavenCooldownHandler(t, u) + proxy.Cooldown = nil + + if w := getMaven(h, mavenTestDir+"maven-metadata.xml"); w.Body.String() != u.metadata() { + t.Errorf("metadata changed:\n%s", w.Body) + } + if w := getMaven(h, mavenTestDir+"2.1/lib-2.1.jar"); w.Code != http.StatusOK { + t.Errorf("jar status = %d, want 200", w.Code) + } + if n := u.totalPOMRequests(); n != 0 { + t.Errorf("pom requests = %d, want 0", n) + } +} + +func TestMavenCooldownPackageOverride(t *testing.T) { + u := newMavenCooldownUpstream(t) + h, proxy := newMavenCooldownHandler(t, u) + proxy.Cooldown = &cooldown.Config{Default: "3d", Packages: map[string]string{"pkg:maven/com.example/lib": "0"}} + + if w := getMaven(h, mavenTestDir+"maven-metadata.xml"); w.Body.String() != u.metadata() { + t.Errorf("metadata changed:\n%s", w.Body) + } + if w := getMaven(h, mavenTestDir+"2.1/lib-2.1.jar"); w.Code != http.StatusOK { + t.Errorf("jar status = %d, want 200", w.Code) + } + if n := u.totalPOMRequests(); n != 0 { + t.Errorf("pom requests = %d, want 0", n) + } +} + +func TestMavenCooldownNamedRepositoryStoresItsOwnTimes(t *testing.T) { + u := newMavenCooldownUpstream(t) + proxy, _, _, _ := setupTestProxy(t) + proxy.HTTPClient = u.server.Client() + proxy.Cooldown = &cooldown.Config{Default: "3d"} + // The named repository is the same server under /portal, which serves + // the same files. + h := NewMavenHandler(proxy, "http://localhost", u.server.URL, u.server.URL+"/portal"). + WithRepositories(map[string]string{"mirror": u.server.URL + "/portal"}).Routes() + + for range 2 { + versions := mavenMetadataVersions(t, getMaven(h, "/mirror"+mavenTestDir+"maven-metadata.xml").Body.String()) + if got := strings.Join(versions, " "); got != "1.0 1.1 3.0-SNAPSHOT" { + t.Fatalf("versions = %s, want 1.0 1.1 3.0-SNAPSHOT", got) + } + } + if w := getMaven(h, "/mirror"+mavenTestDir+"2.1/lib-2.1.jar"); w.Code != http.StatusForbidden { + t.Errorf("jar status = %d, want 403", w.Code) + } + if n := u.totalPOMRequests(); n != 3 { + t.Errorf("pom requests = %d, want 3", n) + } + + // The default repository doesn't use the named one's times. + _ = getMaven(h, mavenTestDir+"maven-metadata.xml") + if n := u.totalPOMRequests(); n != 6 { + t.Errorf("pom requests after default metadata = %d, want 6", n) + } +} + +func TestMavenMetadataWithoutCompact(t *testing.T) { + in := `2212` + doc, err := parseMavenMetadata([]byte(in)) + if err != nil { + t.Fatal(err) + } + got := string(doc.without([]byte(in), map[string]bool{"2": true})) + want := `111` + if got != want { + t.Errorf("got %s\nwant %s", got, want) + } +} diff --git a/internal/handler/maven_repositories_test.go b/internal/handler/maven_repositories_test.go new file mode 100644 index 0000000..e9b2fcf --- /dev/null +++ b/internal/handler/maven_repositories_test.go @@ -0,0 +1,225 @@ +package handler + +import ( + "io" + "net/http" + "net/http/httptest" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/git-pkgs/registries/fetch" +) + +// mavenRepoUpstream serves label-specific bytes for every path it knows and +// counts its requests. +func mavenRepoUpstream(t *testing.T, label string, known ...string) (*httptest.Server, *atomic.Int32) { + t.Helper() + var requests atomic.Int32 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + requests.Add(1) + for _, p := range known { + if r.URL.Path == p { + _, _ = io.WriteString(w, label+" "+r.URL.Path) + return + } + } + http.NotFound(w, r) + })) + t.Cleanup(srv.Close) + return srv, &requests +} + +func newMavenRepositoriesHandler(t *testing.T, central, portal, grails *httptest.Server) http.Handler { + t.Helper() + proxy, _, store, _ := setupTestProxy(t) + store.seekable = true + proxy.HTTPClient = central.Client() + fetcher := fetch.NewFetcher(fetch.WithHTTPClient(central.Client()), fetch.WithMaxRetries(0)) + proxy.Fetcher = fetcher + t.Cleanup(func() { _ = fetcher.Close() }) + return NewMavenHandler(proxy, "http://localhost", central.URL, portal.URL). + WithRepositories(map[string]string{"grails": grails.URL + "/restricted/"}).Routes() +} + +func getMaven(h http.Handler, path string) *httptest.ResponseRecorder { + w := httptest.NewRecorder() + h.ServeHTTP(w, httptest.NewRequest(http.MethodGet, path, nil)) + return w +} + +const ( + mavenJarPath = "/org/grails/grails-core/6.0.0/grails-core-6.0.0.jar" + mavenMetadataPath = "/org/grails/grails-core/maven-metadata.xml" +) + +func TestMavenRepositoriesAreServedFromTheirOwnUpstream(t *testing.T) { + central, _ := mavenRepoUpstream(t, "central", mavenJarPath, mavenMetadataPath) + portal, _ := mavenRepoUpstream(t, "portal") + grails, _ := mavenRepoUpstream(t, "grails", "/restricted"+mavenJarPath, "/restricted"+mavenMetadataPath) + h := newMavenRepositoriesHandler(t, central, portal, grails) + + // The same coordinates in both repositories are cached apart. + for range 2 { + if w := getMaven(h, "/grails"+mavenJarPath); w.Code != http.StatusOK || w.Body.String() != "grails /restricted"+mavenJarPath { + t.Fatalf("named jar: status = %d, body = %q", w.Code, w.Body) + } + if w := getMaven(h, mavenJarPath); w.Code != http.StatusOK || w.Body.String() != "central "+mavenJarPath { + t.Fatalf("default jar: status = %d, body = %q", w.Code, w.Body) + } + } + + if w := getMaven(h, "/grails"+mavenMetadataPath); w.Code != http.StatusOK || !strings.HasPrefix(w.Body.String(), "grails ") { + t.Errorf("named metadata: status = %d, body = %q", w.Code, w.Body) + } + if w := getMaven(h, mavenMetadataPath); w.Code != http.StatusOK || !strings.HasPrefix(w.Body.String(), "central ") { + t.Errorf("default metadata: status = %d, body = %q", w.Code, w.Body) + } +} + +func TestMavenRepositoriesDoNotFallBackToThePluginPortal(t *testing.T) { + const pluginPath = "/org/example/plugin/1.0/plugin-1.0.jar" + central, _ := mavenRepoUpstream(t, "central") + portal, portalRequests := mavenRepoUpstream(t, "portal", pluginPath, "/org/example/plugin/maven-metadata.xml") + grails, _ := mavenRepoUpstream(t, "grails") + h := newMavenRepositoriesHandler(t, central, portal, grails) + + for _, path := range []string{"/grails" + pluginPath, "/grails/org/example/plugin/maven-metadata.xml"} { + if w := getMaven(h, path); w.Code != http.StatusNotFound { + t.Errorf("GET %s status = %d, want 404", path, w.Code) + } + } + if n := portalRequests.Load(); n != 0 { + t.Errorf("named repository asked the plugin portal %d times", n) + } + if w := getMaven(h, pluginPath); w.Code != http.StatusOK || !strings.HasPrefix(w.Body.String(), "portal ") { + t.Errorf("default repository: status = %d, body = %q, want the plugin portal's copy", w.Code, w.Body) + } +} + +func TestMavenRepositoryRootIsNotFound(t *testing.T) { + central, centralRequests := mavenRepoUpstream(t, "central") + portal, _ := mavenRepoUpstream(t, "portal") + grails, _ := mavenRepoUpstream(t, "grails") + h := newMavenRepositoriesHandler(t, central, portal, grails) + + for _, path := range []string{"/grails", "/grails/"} { + if w := getMaven(h, path); w.Code != http.StatusNotFound { + t.Errorf("GET %s status = %d, want 404", path, w.Code) + } + } + if n := centralRequests.Load(); n != 0 { + t.Errorf("repository root went to the default upstream %d times", n) + } +} + +func TestMavenRepositoryRepointedServesTheNewUpstream(t *testing.T) { + central, _ := mavenRepoUpstream(t, "central") + portal, _ := mavenRepoUpstream(t, "portal") + staging, _ := mavenRepoUpstream(t, "staging", mavenJarPath) + production, _ := mavenRepoUpstream(t, "production", mavenJarPath) + + proxy, _, store, _ := setupTestProxy(t) + store.seekable = true + proxy.HTTPClient = central.Client() + fetcher := fetch.NewFetcher(fetch.WithHTTPClient(central.Client()), fetch.WithMaxRetries(0)) + proxy.Fetcher = fetcher + t.Cleanup(func() { _ = fetcher.Close() }) + + for _, upstream := range []struct { + srv *httptest.Server + label string + }{{staging, "staging"}, {production, "production"}} { + h := NewMavenHandler(proxy, "http://localhost", central.URL, portal.URL). + WithRepositories(map[string]string{"grails": upstream.srv.URL}).Routes() + if w := getMaven(h, "/grails"+mavenJarPath); w.Code != http.StatusOK || w.Body.String() != upstream.label+" "+mavenJarPath { + t.Errorf("%s: status = %d, body = %q", upstream.label, w.Code, w.Body) + } + } +} + +// TestMavenDottedGroupDirectoryNotCachedAsGroup checks that a file whose +// group directories contain dots or colons, which the Maven layout never +// has, is not served: it would either share the cache entry of the group +// the dots spell or be proxied past the denylist, scan and cooldown. +func TestMavenDottedGroupDirectoryNotCachedAsGroup(t *testing.T) { + const standard = "/org/foo/bar/1.0/bar-1.0.jar" + odd := []string{ + "/org.foo/bar/1.0/bar-1.0.jar", "/org.foo/bar/1.0/bar-1.0-linux.exe", + "/org/foo:x/bar/1.0/bar-1.0.jar", "/org/foo/b:ar/1.0/b:ar-1.0.jar", + } + central, requests := mavenRepoUpstream(t, "central", append([]string{standard}, odd...)...) + portal, _ := mavenRepoUpstream(t, "portal") + var restricted []string + for _, p := range odd { + restricted = append(restricted, "/restricted"+p) + } + grails, grailsRequests := mavenRepoUpstream(t, "grails", restricted...) + h := newMavenRepositoriesHandler(t, central, portal, grails) + + if w := getMaven(h, standard); w.Code != http.StatusOK || w.Body.String() != "central "+standard { + t.Errorf("GET %s = %d %q", standard, w.Code, w.Body.String()) + } + before := requests.Load() + grailsRequests.Load() + for _, p := range odd { + for _, path := range []string{p, "/grails" + p} { + if w := getMaven(h, path); w.Code != http.StatusNotFound { + t.Errorf("GET %s = %d %q, want 404", path, w.Code, w.Body.String()) + } + } + } + if n := requests.Load() + grailsRequests.Load() - before; n != 0 { + t.Errorf("%d upstream requests for paths outside the Maven layout", n) + } +} + +// TestMavenUncachedPathFallsBackToPluginPortal checks that a path proxied +// without caching, such as a catalog, still tries the Gradle Plugin Portal +// when the primary upstream lacks it. +func TestMavenUncachedPathFallsBackToPluginPortal(t *testing.T) { + const uncached = "/org/foo/archetype-catalog.xml" + central, _ := mavenRepoUpstream(t, "central") + portal, _ := mavenRepoUpstream(t, "portal", uncached) + grails, _ := mavenRepoUpstream(t, "grails") + h := newMavenRepositoriesHandler(t, central, portal, grails) + + if w := getMaven(h, uncached); w.Code != http.StatusOK || w.Body.String() != "portal "+uncached { + t.Errorf("GET %s = %d %q, want the Plugin Portal's copy", uncached, w.Code, w.Body.String()) + } +} + +func TestMavenUncachedPathKeepsByteRanges(t *testing.T) { + const uncached = "/org/foo/archetype-catalog.xml" + ranged := func() *httptest.Server { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("ETag", `"v2"`) + http.ServeContent(w, r, "archetype-catalog.xml", time.Time{}, strings.NewReader("0123456789")) + })) + t.Cleanup(srv.Close) + return srv + } + central, grails := ranged(), ranged() + portal, _ := mavenRepoUpstream(t, "portal") + h := newMavenRepositoriesHandler(t, central, portal, grails) + + for _, p := range []string{uncached, "/grails" + uncached} { + req := httptest.NewRequest(http.MethodGet, p, nil) + req.Header.Set("Range", "bytes=2-4") + w := httptest.NewRecorder() + h.ServeHTTP(w, req) + if w.Code != http.StatusPartialContent || w.Body.String() != "234" { + t.Errorf("GET %s with Range = %d %q, want 206 %q", p, w.Code, w.Body.String(), "234") + } + + // A Range for an older copy gets the whole current file. + req = httptest.NewRequest(http.MethodGet, p, nil) + req.Header.Set("Range", "bytes=2-4") + req.Header.Set("If-Range", `"v1"`) + w = httptest.NewRecorder() + h.ServeHTTP(w, req) + if w.Code != http.StatusOK || w.Body.String() != "0123456789" { + t.Errorf("GET %s with stale If-Range = %d %q, want 200 with the whole file", p, w.Code, w.Body.String()) + } + } +} diff --git a/internal/handler/maven_test.go b/internal/handler/maven_test.go index beaa8f7..14cb49f 100644 --- a/internal/handler/maven_test.go +++ b/internal/handler/maven_test.go @@ -31,6 +31,15 @@ func TestMavenParsePath(t *testing.T) { "short/path", "", "", "", "", }, + // Group directories never hold dots or are empty in the Maven + // layout; these would spell the same group as org/foo. + {"org.foo/bar/1.0/bar-1.0.jar", "", "", "", ""}, + {"org/.foo/bar/1.0/bar-1.0.jar", "", "", "", ""}, + {"org//foo/bar/1.0/bar-1.0.jar", "", "", "", ""}, + // Cache identity is group:artifact, so a colon in either would + // let org:foo/bar and org/foo:bar share one entry. + {"org:foo/bar/1.0/bar-1.0.jar", "", "", "", ""}, + {"org/foo:bar/1.0/bar-1.0.jar", "", "", "", ""}, } for _, tt := range tests { @@ -117,3 +126,28 @@ func TestMavenIsChecksumFile(t *testing.T) { } } } + +func TestMavenIsCoordinateFile(t *testing.T) { + h := &MavenHandler{} + + tests := []struct { + path string + want bool + }{ + {"com/google/protobuf/protoc/3.21.0/protoc-3.21.0-linux-x86_64.exe", true}, + {"com/google/protobuf/protoc/3.21.0/protoc-3.21.0-linux-x86_64.exe.sha1", true}, + {"org/example/plugin/1.0/plugin-1.0.hpi", true}, + {"org/example/lib/1.0-SNAPSHOT/lib-1.0-20240101.120000-1.exe", true}, + {"org/example/lib/1.0-SNAPSHOT/lib-1.0-SNAPSHOT.exe", true}, + {"com/google/protobuf/protoc/3.21.0/", false}, + {"com/google/protobuf/protoc/3.21.0/other-3.21.0.exe", false}, + {"com/google/protobuf/protoc/3.21.0/protoc-3.20.0.exe", false}, + {"archetype-catalog.xml", false}, + } + + for _, tt := range tests { + if got := h.isCoordinateFile(tt.path); got != tt.want { + t.Errorf("isCoordinateFile(%q) = %v, want %v", tt.path, got, tt.want) + } + } +} diff --git a/internal/handler/metadata_access_test.go b/internal/handler/metadata_access_test.go new file mode 100644 index 0000000..7b5e1cf --- /dev/null +++ b/internal/handler/metadata_access_test.go @@ -0,0 +1,181 @@ +package handler + +import ( + "context" + "net/http" + "net/http/httptest" + "testing" + "time" + + "github.com/git-pkgs/proxy/internal/database" +) + +// ageMetadataAccess moves a cache row's last access an hour back and returns +// that time. +func ageMetadataAccess(t *testing.T, db *database.DB, ecosystem, key string) time.Time { + t.Helper() + old := time.Now().Add(-time.Hour).UTC() + query := db.Rebind(`UPDATE metadata_cache SET last_accessed_at = ? WHERE ecosystem = ? AND name = ?`) + if _, err := db.Exec(query, old, ecosystem, key); err != nil { + t.Fatalf("ageing last access: %v", err) + } + return old +} + +func assertMetadataAccessedAfter(t *testing.T, db *database.DB, ecosystem, key string, old time.Time) { + t.Helper() + entry, err := db.GetMetadataCache(ecosystem, key) + if err != nil || entry == nil { + t.Fatalf("GetMetadataCache: %v, %v", entry, err) + } + if !entry.LastAccessedAt.Valid || !entry.LastAccessedAt.Time.After(old.Add(time.Minute)) { + t.Errorf("last_accessed_at = %v, want the time it was served from cache", entry.LastAccessedAt) + } +} + +func TestFetchOrCacheMetadata_CacheHitMarksAccess(t *testing.T) { + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"v":1}`)) + })) + t.Cleanup(upstream.Close) + + proxy, db, _, _ := setupTestProxy(t) + proxy.CacheMetadata = true + proxy.MetadataTTL = time.Hour + proxy.HTTPClient = upstream.Client() + ctx := context.Background() + + if _, _, err := proxy.FetchOrCacheMetadata(ctx, "test", "pkg", upstream.URL+"/pkg"); err != nil { + t.Fatalf("first fetch: %v", err) + } + old := ageMetadataAccess(t, db, "test", "pkg") + if _, _, err := proxy.FetchOrCacheMetadata(ctx, "test", "pkg", upstream.URL+"/pkg"); err != nil { + t.Fatalf("cached fetch: %v", err) + } + assertMetadataAccessedAfter(t, db, "test", "pkg", old) +} + +func TestProxyCached_NotModifiedMarksAccess(t *testing.T) { + const body = `{"v":1}` + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("ETag", `"v1"`) + if r.Header.Get("If-None-Match") == `"v1"` { + w.WriteHeader(http.StatusNotModified) + return + } + _, _ = w.Write([]byte(body)) + })) + t.Cleanup(upstream.Close) + + proxy, db, store, _ := setupTestProxy(t) + proxy.CacheMetadata = true + proxy.MetadataTTL = time.Nanosecond + proxy.HTTPClient = upstream.Client() + + for range 2 { + response := httptest.NewRecorder() + proxy.ProxyCached(response, httptest.NewRequest(http.MethodGet, "/pkg", nil), upstream.URL+"/pkg", "test", "pkg") + if response.Code != http.StatusOK || response.Body.String() != body { + t.Fatalf("response = %d %q, want 200 %q", response.Code, response.Body.String(), body) + } + if store.stores != 1 { + t.Fatalf("document stored %d times, want once", store.stores) + } + assertMetadataAccessedAfter(t, db, "test", "pkg", time.Now().Add(-time.Hour)) + ageMetadataAccess(t, db, "test", "pkg") + } +} + +func TestLoadContainerMetadata_MarksAccess(t *testing.T) { + proxy, db, _, _ := setupTestProxy(t) + h := NewContainerHandlerWithRegistry(proxy, "http://proxy.example.test", "") + ctx := context.Background() + + if _, err := h.storeContainerMetadata(ctx, "oci-test", "key", []byte("{}"), "", "", "application/json", "", time.Time{}, time.Now()); err != nil { + t.Fatalf("storing: %v", err) + } + old := ageMetadataAccess(t, db, "oci-test", "key") + if entry, _, err := h.loadContainerMetadata(ctx, "oci-test", "key"); err != nil || entry == nil { + t.Fatalf("loading: %v, %v", entry, err) + } + assertMetadataAccessedAfter(t, db, "oci-test", "key", old) +} + +func TestLoadContainerManifest_MarksAccess(t *testing.T) { + proxy, db, _, _ := setupTestProxy(t) + h := NewContainerHandlerWithRegistry(proxy, "http://proxy.example.test", "") + ctx := context.Background() + + manifest := &cachedContainerManifest{body: []byte("{}"), contentType: "application/json", fetchedAt: time.Now()} + if err := h.storeContainerManifest(ctx, "key", manifest); err != nil { + t.Fatalf("storing: %v", err) + } + old := ageMetadataAccess(t, db, containerManifestCacheEcosystem, "key") + if got, err := h.loadContainerManifest(ctx, "key"); err != nil || got == nil { + t.Fatalf("loading: %v, %v", got, err) + } + assertMetadataAccessedAfter(t, db, containerManifestCacheEcosystem, "key", old) +} + +func TestLoadContainerTags_MarksAccess(t *testing.T) { + proxy, db, _, _ := setupTestProxy(t) + h := NewContainerHandlerWithRegistry(proxy, "http://proxy.example.test", "") + ctx := context.Background() + + tags := &cachedContainerTags{body: []byte(`{"tags":[]}`), contentType: "application/json", fetchedAt: time.Now()} + if err := h.storeContainerTags(ctx, "key", tags); err != nil { + t.Fatalf("storing: %v", err) + } + old := ageMetadataAccess(t, db, containerTagsCacheEcosystem, "key") + if got, err := h.loadContainerTags(ctx, "key"); err != nil || got == nil { + t.Fatalf("loading: %v, %v", got, err) + } + assertMetadataAccessedAfter(t, db, containerTagsCacheEcosystem, "key", old) +} + +func TestStoredRewrite_MarksAccess(t *testing.T) { + proxy, db, _, _ := setupTestProxy(t) + proxy.CacheMetadata = true + proxy.MetadataTTL = time.Hour + proxy.SetMetadataRewriteCacheSize(1 << 20) + + body := []byte(`{}`) + proxy.cacheMetadataBlob(t.Context(), "npm", "demo", metadataStoragePath("npm", "demo"), &upstreamMetadata{body: body}) + key := rewriteCacheKey("npm", "http://proxy", "demo", body) + if _, err := proxy.rewrites.rewrite(t.Context(), key, body, nil, func(b []byte) ([]byte, error) { return b, nil }); err != nil { + t.Fatal(err) + } + old := ageMetadataAccess(t, db, "npm", "demo") + if _, ok := proxy.storedRewrite("npm", "demo", "http://proxy", "demo"); !ok { + t.Fatal("expected a stored rewrite") + } + assertMetadataAccessedAfter(t, db, "npm", "demo", old) +} + +// TestArchHandler_RefreshRestoresEvictedBlob covers a database row whose blob +// size eviction removed while a refresh re-created the row: the next refresh +// with the same bytes stores the blob again, so the stale fallback works. +func TestArchHandler_RefreshRestoresEvictedBlob(t *testing.T) { + db := []byte("core-db-bytes") + upstream := newArchUpstream(t, map[string][]byte{"/core/os/x86_64/core.db": db}) + proxy := newArchTestProxy(t, upstream) + h := NewArchHandler(proxy, "http://proxy.example", map[string]string{"archlinux": upstream.URL}) + path := "/archlinux/core/os/x86_64/core.db" + + assertArchBody(t, serveArchRequest(h, http.MethodGet, path, nil), "seed", db) + entry, err := proxy.DB.GetMetadataCache(archEcosystem, h.metadataCacheKey("archlinux", upstream.URL, "core/os/x86_64/core.db")) + if err != nil || entry == nil { + t.Fatalf("metadata entry: %v, %v", entry, err) + } + if err := proxy.Storage.Delete(t.Context(), entry.StoragePath); err != nil { + t.Fatalf("deleting blob: %v", err) + } + + ageMetadata(t, proxy, h, "archlinux", upstream.URL, "core/os/x86_64/core.db") + assertArchBody(t, serveArchRequest(h, http.MethodGet, path, nil), "refresh", db) + + ageMetadata(t, proxy, h, "archlinux", upstream.URL, "core/os/x86_64/core.db") + upstream.available.Store(false) + assertArchBody(t, serveArchRequest(h, http.MethodGet, path, nil), "stale", db) +} diff --git a/internal/handler/metadata_consistency_test.go b/internal/handler/metadata_consistency_test.go new file mode 100644 index 0000000..3e0220a --- /dev/null +++ b/internal/handler/metadata_consistency_test.go @@ -0,0 +1,324 @@ +package handler + +import ( + "bytes" + "compress/gzip" + "context" + "database/sql" + "errors" + "io" + "net/http" + "net/http/httptest" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/git-pkgs/proxy/internal/database" +) + +// proxyCachedRequest runs one ProxyCached request for key "pkg". +func proxyCachedRequest(proxy *Proxy, upstreamURL string, header http.Header) *httptest.ResponseRecorder { + w := httptest.NewRecorder() + r := httptest.NewRequest(http.MethodGet, "/pkg", nil) + for k, v := range header { + r.Header[k] = v + } + proxy.ProxyCached(w, r, upstreamURL+"/pkg", "test", "pkg") + return w +} + +// TestFetchedMetadataValidatorsDescribeBody checks that a document fetched +// fresh but not stored is served with upstream's validators, not those of the +// older row still in the cache. +func TestFetchedMetadataValidatorsDescribeBody(t *testing.T) { + var requests atomic.Int32 + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set(headerContentType, contentTypeJSON) + if requests.Add(1) == 1 { + w.Header().Set(headerETag, `"v1"`) + _, _ = w.Write([]byte(`{"v":1}`)) + return + } + w.Header().Set(headerETag, `"v2"`) + _, _ = w.Write([]byte(`{"v":2}`)) + })) + t.Cleanup(upstream.Close) + + proxy, _, store, _ := setupTestProxy(t) + proxy.CacheMetadata = true + proxy.MetadataTTL = time.Millisecond + proxy.HTTPClient = upstream.Client() + + if w := proxyCachedRequest(proxy, upstream.URL, nil); w.Code != http.StatusOK { + t.Fatalf("first request: %d", w.Code) + } + time.Sleep(5 * time.Millisecond) + store.mu.Lock() + store.storeErr = errors.New("disk full") + store.mu.Unlock() + + w := proxyCachedRequest(proxy, upstream.URL, nil) + if w.Code != http.StatusOK || w.Body.String() != `{"v":2}` { + t.Fatalf("second request = %d %q, want v2", w.Code, w.Body) + } + if got := w.Header().Get(headerETag); got != `"v2"` { + t.Errorf("ETag = %q, want %q", got, `"v2"`) + } + if got := w.Header().Get("Warning"); got != "" { + t.Errorf("Warning = %q on a fresh document", got) + } + + // A client holding v1 must get v2, not a 304. + w = proxyCachedRequest(proxy, upstream.URL, http.Header{"If-None-Match": {`"v1"`}}) + if w.Code != http.StatusOK || w.Body.String() != `{"v":2}` { + t.Errorf("conditional request = %d %q, want 200 v2", w.Code, w.Body) + } +} + +// TestStaleMetadataMarkedWithoutTTL checks that the stale fallback carries +// the Warning header with metadata_ttl 0, where every request revalidates. +func TestStaleMetadataMarkedWithoutTTL(t *testing.T) { + upstream := upstreamThen(t, `{"v":1}`, http.StatusBadGateway) + proxy, _, _, _ := setupTestProxy(t) + proxy.CacheMetadata = true + proxy.MetadataTTL = 0 + proxy.HTTPClient = upstream.Client() + + if w := proxyCachedRequest(proxy, upstream.URL, nil); w.Code != http.StatusOK { + t.Fatalf("first request: %d", w.Code) + } + w := proxyCachedRequest(proxy, upstream.URL, nil) + if w.Code != http.StatusOK || w.Body.String() != `{"v":1}` { + t.Fatalf("fallback = %d %q", w.Code, w.Body) + } + if got := w.Header().Get("Warning"); got != staleWarning { + t.Errorf("Warning = %q, want %q", got, staleWarning) + } +} + +// seedMetadataRow stores {"v":1} for key "pkg" with ETag "v1" and a row past +// its TTL. +func seedMetadataRow(t *testing.T, db *database.DB, store *mockStorage) string { + t.Helper() + const body, etag = `{"v":1}`, `"v1"` + path := metadataStoragePath("test", "pkg") + store.mu.Lock() + store.files[path] = []byte(body) + store.mu.Unlock() + if err := db.UpsertMetadataCache(&database.MetadataCacheEntry{ + Ecosystem: "test", + Name: "pkg", + StoragePath: path, + ETag: sql.NullString{String: etag, Valid: true}, + ContentType: sql.NullString{String: contentTypeJSON, Valid: true}, + ContentDigest: sql.NullString{String: "sha256:" + sha256Hex(body), Valid: true}, + Size: sql.NullInt64{Int64: int64(len(body)), Valid: true}, + FetchedAt: sql.NullTime{Time: time.Now().Add(-time.Hour), Valid: true}, + }); err != nil { + t.Fatal(err) + } + return path +} + +// v2Upstream answers If-None-Match "v1" with 304 after running onNotModified, +// and any other request with v2. +func v2Upstream(t *testing.T, onNotModified func()) *httptest.Server { + t.Helper() + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Header.Get("If-None-Match") == `"v1"` { + onNotModified() + w.WriteHeader(http.StatusNotModified) + return + } + w.Header().Set(headerContentType, contentTypeJSON) + w.Header().Set(headerETag, `"v2"`) + _, _ = w.Write([]byte(`{"v":2}`)) + })) + t.Cleanup(srv.Close) + return srv +} + +// TestNotModifiedChecksStoredBytes checks that a 304 for a row whose blob has +// meanwhile been replaced (by another instance sharing the store) does not +// serve the new bytes under the old ETag. +func TestNotModifiedChecksStoredBytes(t *testing.T) { + proxy, db, store, _ := setupTestProxy(t) + proxy.CacheMetadata = true + proxy.MetadataTTL = time.Minute + path := seedMetadataRow(t, db, store) + upstream := v2Upstream(t, func() { + // The other instance has written v2 but not yet its row. + store.mu.Lock() + store.files[path] = []byte(`{"v":2}`) + store.mu.Unlock() + }) + proxy.HTTPClient = upstream.Client() + + w := proxyCachedRequest(proxy, upstream.URL, nil) + if w.Code != http.StatusOK || w.Body.String() != `{"v":2}` { + t.Fatalf("response = %d %q", w.Code, w.Body) + } + if got := w.Header().Get(headerETag); got != `"v2"` { + t.Errorf("ETag = %q, want %q", got, `"v2"`) + } + row, err := db.GetMetadataCache("test", "pkg") + if err != nil || row == nil { + t.Fatal(row, err) + } + if row.ETag.String != `"v2"` || row.ContentDigest.String != "sha256:"+sha256Hex(`{"v":2}`) { + t.Errorf("row = etag %q digest %q, want v2's", row.ETag.String, row.ContentDigest.String) + } +} + +// TestNotModifiedAfterRowReplaced checks that a 304 for a row another +// instance has replaced since it was read does not store the old document +// back over the new one. +func TestNotModifiedAfterRowReplaced(t *testing.T) { + proxy, db, store, _ := setupTestProxy(t) + proxy.CacheMetadata = true + proxy.MetadataTTL = time.Minute + path := seedMetadataRow(t, db, store) + upstream := v2Upstream(t, func() { + // The other instance has recorded v2's row; its blob is not written + // yet. + _ = db.UpsertMetadataCache(&database.MetadataCacheEntry{ + Ecosystem: "test", + Name: "pkg", + StoragePath: path, + ETag: sql.NullString{String: `"v2"`, Valid: true}, + ContentType: sql.NullString{String: contentTypeJSON, Valid: true}, + ContentDigest: sql.NullString{String: "sha256:" + sha256Hex(`{"v":2}`), Valid: true}, + Size: sql.NullInt64{Int64: 7, Valid: true}, + FetchedAt: sql.NullTime{Time: time.Now(), Valid: true}, + }) + }) + proxy.HTTPClient = upstream.Client() + + res := proxy.fetchMetadataDocument(context.Background(), "test", "pkg", upstream.URL+"/pkg", contentTypeJSON, nil) + if res.err != nil || string(res.body) != `{"v":2}` { + t.Fatalf("fetch = %q, %v; want v2", res.body, res.err) + } + row, err := db.GetMetadataCache("test", "pkg") + if err != nil || row == nil { + t.Fatal(row, err) + } + if row.ETag.String != `"v2"` { + t.Errorf("row etag = %q, want %q", row.ETag.String, `"v2"`) + } +} + +// TestNotModifiedRejectedBodyNotRefreshed checks that a 304 for a stored +// document validate rejects does not mark that document fresh. +func TestNotModifiedRejectedBodyNotRefreshed(t *testing.T) { + proxy, db, store, _ := setupTestProxy(t) + proxy.CacheMetadata = true + proxy.MetadataTTL = time.Minute + seedMetadataRow(t, db, store) + before, err := db.GetMetadataCache("test", "pkg") + if err != nil || before == nil { + t.Fatal(before, err) + } + upstream := v2Upstream(t, func() {}) + proxy.HTTPClient = upstream.Client() + + reject := func(body []byte) error { + if string(body) == `{"v":1}` { + return errors.New("damaged") + } + return nil + } + proxy.fetchMetadataDocument(context.Background(), "test", "pkg", upstream.URL+"/pkg", contentTypeJSON, reject) + row, err := db.GetMetadataCache("test", "pkg") + if err != nil || row == nil { + t.Fatal(row, err) + } + if !row.FetchedAt.Time.Equal(before.FetchedAt.Time) { + t.Errorf("rejected v1 row fetched_at moved from %v to %v", before.FetchedAt.Time, row.FetchedAt.Time) + } +} + +// openHookStorage runs onOpen before the first Open. +type openHookStorage struct { + *mockStorage + once sync.Once + onOpen func() +} + +func (s *openHookStorage) Open(ctx context.Context, path string) (io.ReadCloser, error) { + s.once.Do(s.onOpen) + return s.mockStorage.Open(ctx, path) +} + +// TestStaleMetadataChecksStoredBytes checks that the stale fallback does not +// serve a blob another instance replaced after the row was read under that +// row's ETag. +func TestStaleMetadataChecksStoredBytes(t *testing.T) { + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusBadGateway) + })) + t.Cleanup(upstream.Close) + proxy, db, store, _ := setupTestProxy(t) + proxy.CacheMetadata = true + proxy.MetadataTTL = 0 + proxy.HTTPClient = upstream.Client() + path := seedMetadataRow(t, db, store) + proxy.Storage = &openHookStorage{mockStorage: store, onOpen: func() { + // The other instance has written v2 but not yet its row. + store.mu.Lock() + store.files[path] = []byte(`{"v":2}`) + store.mu.Unlock() + }} + + // No row describes v2 yet, so its encoding is unknown: nothing is served. + w := proxyCachedRequest(proxy, upstream.URL, http.Header{"If-None-Match": {`"v1"`}}) + if w.Code < http.StatusInternalServerError || w.Header().Get(headerETag) == `"v1"` { + t.Errorf("response = %d ETag %q for v2's bytes, want an error without v1 validators", w.Code, w.Header().Get(headerETag)) + } +} + +// TestStaleMetadataRereadsReplacedRow checks that when the stored bytes no +// longer match the row, the stale fallback reads the row again and serves +// the blob with the encoding and validators of the row that describes it. +func TestStaleMetadataRereadsReplacedRow(t *testing.T) { + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusBadGateway) + })) + t.Cleanup(upstream.Close) + proxy, db, store, _ := setupTestProxy(t) + proxy.CacheMetadata = true + proxy.MetadataTTL = 0 + proxy.HTTPClient = upstream.Client() + path := seedMetadataRow(t, db, store) + var gz bytes.Buffer + zw := gzip.NewWriter(&gz) + _, _ = zw.Write([]byte(`{"v":2}`)) + _ = zw.Close() + v2 := gz.Bytes() + proxy.Storage = &openHookStorage{mockStorage: store, onOpen: func() { + // The other instance stores v2 gzipped, then its row. + store.mu.Lock() + store.files[path] = v2 + store.mu.Unlock() + if err := db.UpsertMetadataCache(&database.MetadataCacheEntry{ + Ecosystem: "test", + Name: "pkg", + StoragePath: path, + ETag: sql.NullString{String: `"v2"`, Valid: true}, + ContentType: sql.NullString{String: contentTypeJSON, Valid: true}, + ContentEncoding: sql.NullString{String: "gzip", Valid: true}, + ContentDigest: sql.NullString{String: "sha256:" + sha256Hex(string(v2)), Valid: true}, + Size: sql.NullInt64{Int64: int64(len(v2)), Valid: true}, + FetchedAt: sql.NullTime{Time: time.Now().Add(-time.Hour), Valid: true}, + }); err != nil { + t.Error(err) + } + }} + + w := proxyCachedRequest(proxy, upstream.URL, http.Header{"Accept-Encoding": {"gzip"}}) + if w.Code != http.StatusOK || w.Header().Get("Content-Encoding") != "gzip" || + w.Header().Get(headerETag) != `"v2"` || !bytes.Equal(w.Body.Bytes(), v2) { + t.Errorf("response = %d, Content-Encoding %q, ETag %q; want v2 gzipped under its own row", + w.Code, w.Header().Get("Content-Encoding"), w.Header().Get(headerETag)) + } +} diff --git a/internal/handler/metadata_gzip_test.go b/internal/handler/metadata_gzip_test.go index 5826441..57d20cc 100644 --- a/internal/handler/metadata_gzip_test.go +++ b/internal/handler/metadata_gzip_test.go @@ -149,7 +149,10 @@ func TestRewrittenMetadataWithoutGzip(t *testing.T) { func TestRewrittenMetadataGzipOnlyFromRewriteCache(t *testing.T) { setups := map[string]func(*Proxy){ "cache disabled": func(p *Proxy) { p.SetMetadataRewriteCacheSize(0) }, - "cooldown": func(p *Proxy) { p.Cooldown = &cooldown.Config{Default: "3d"} }, + "cooldown without cache": func(p *Proxy) { + p.SetMetadataRewriteCacheSize(0) + p.Cooldown = &cooldown.Config{Default: "3d"} + }, } for _, c := range validatorCases { for name, setup := range setups { @@ -170,9 +173,10 @@ func TestRewrittenMetadataGzipOnlyFromRewriteCache(t *testing.T) { } } -// TestRewriteCache_KeepsGzipCopyOnlyWhenSmaller checks that the cache keeps a -// compressed copy of a rewrite, counted against its size, unless compressing -// does not make the rewrite smaller. +// TestRewriteCache_KeepsGzipCopyOnlyWhenSmaller checks that the cache keeps +// only a compressed copy of a rewrite, counted against its size, unless +// compressing does not make the rewrite smaller, and that the plain document +// is still there for callers that need it. func TestRewriteCache_KeepsGzipCopyOnlyWhenSmaller(t *testing.T) { c := newRewriteCache(1 << 20) identity := func(b []byte) ([]byte, error) { return b, nil } @@ -180,7 +184,7 @@ func TestRewriteCache_KeepsGzipCopyOnlyWhenSmaller(t *testing.T) { for _, doc := range [][]byte{large, []byte("abc")} { key := rewriteCacheKey("npm", "http://proxy", string(doc[:3]), doc) - if _, err := c.rewrite(t.Context(), key, doc, identity); err != nil { + if _, err := c.rewrite(t.Context(), key, doc, nil, identity); err != nil { t.Fatal(err) } } @@ -189,11 +193,17 @@ func TestRewriteCache_KeepsGzipCopyOnlyWhenSmaller(t *testing.T) { if !ok || m.gzipped == nil { t.Fatalf("large rewrite: cached %v, gzip copy %d bytes; want a gzip copy", ok, len(m.gzipped)) } - if c.size != int64(len(large)+len(m.gzipped)+3) { - t.Errorf("cache size = %d, want both rewrites and the gzip copy (%d)", c.size, len(large)+len(m.gzipped)+3) + if m.plain != nil { + t.Errorf("large rewrite: cached %d plain bytes besides the gzip copy, want none", len(m.plain)) } - if small, ok := c.get(rewriteCacheKey("npm", "http://proxy", "abc", []byte("abc"))); !ok || small.gzipped != nil { - t.Errorf("small rewrite: cached %v, gzip copy %d bytes; want none", ok, len(small.gzipped)) + if c.size != int64(len(m.gzipped)+3) { + t.Errorf("cache size = %d, want the gzip copy and the small rewrite (%d)", c.size, len(m.gzipped)+3) + } + if !bytes.Equal(m.content(), large) || m.size != len(large) { + t.Errorf("large rewrite content = %d bytes, size %d; want the %d bytes rewritten", len(m.content()), m.size, len(large)) + } + if small, ok := c.get(rewriteCacheKey("npm", "http://proxy", "abc", []byte("abc"))); !ok || small.gzipped != nil || string(small.content()) != "abc" { + t.Errorf("small rewrite: cached %v, gzip copy %d bytes, content %q; want abc uncompressed", ok, len(small.gzipped), small.content()) } } diff --git a/internal/handler/metadata_immutable.go b/internal/handler/metadata_immutable.go new file mode 100644 index 0000000..214077c --- /dev/null +++ b/internal/handler/metadata_immutable.go @@ -0,0 +1,115 @@ +package handler + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "errors" + "fmt" + "net/http" + + "github.com/git-pkgs/proxy/internal/metrics" +) + +// Some metadata documents never change once published: a Go module's .mod +// and .info for a canonical version, or an RPM repodata file named after its +// own checksum. Revalidating them every metadata TTL, or fetching them again +// on every request without cache_metadata, only costs upstream requests. They +// are kept in the metadata cache like other metadata, but served whatever +// their age and stored whether or not cache_metadata is set, the way +// artifacts are. + +// errImmutableDigest is returned when a stored immutable document doesn't +// match the digest recorded for it. +var errImmutableDigest = errors.New("stored metadata does not match its digest") + +// proxyImmutable answers a request for an immutable metadata document: from +// the metadata cache when it is stored, otherwise fetched once and stored. A +// document over the metadata size limit is streamed from upstream instead, +// uncached. +func (p *Proxy) proxyImmutable(w http.ResponseWriter, r *http.Request, upstreamURL, ecosystem, cacheKey, accept string) { + if p.serveStoredMetadata(w, r, ecosystem, cacheKey, true) { + return + } + res := p.fetchImmutableMetadata(r.Context(), ecosystem, cacheKey, upstreamURL, accept) + if errors.Is(res.err, ErrMetadataTooLarge) { + p.proxyMetadataStream(w, r, upstreamURL, "identity", accept) + return + } + if res.err != nil { + p.writeMetadataFetchError(w, res.err) + return + } + res.stale = false + writeMetadataResult(w, r, res) +} + +// fetchImmutableMetadata returns an immutable metadata document from the +// metadata cache whatever its age, or fetches and stores it. Upstream's bytes +// are kept as sent (Accept-Encoding: identity). Without a database or storage +// it falls back to the TTL lookup. +func (p *Proxy) fetchImmutableMetadata(ctx context.Context, ecosystem, cacheKey, upstreamURL, accept string) metadataResult { + if p.DB == nil || p.Storage == nil { + return p.lookupMetadata(ctx, ecosystem, cacheKey, upstreamURL, accept, "identity", nil) + } + if containsPathTraversal(cacheKey) { + return metadataResult{err: fmt.Errorf("invalid cache key: %q", cacheKey)} + } + if hit := p.storedImmutable(ctx, ecosystem, cacheKey); hit != nil { + metrics.RecordMetadataCacheHit(ecosystem, len(hit.body)) + return *hit + } + metrics.RecordMetadataCacheMiss(ecosystem) + + // Kept apart from TTL lookups of the same key, which don't store the + // document without cache_metadata. + key := metadataCoalesceKey(ecosystem, cacheKey, upstreamURL, accept, "identity", false) + "\x00immutable" + res, _ := p.coalesceMetadata(ctx, key, func(fetchCtx context.Context) metadataResult { + if hit := p.storedImmutable(fetchCtx, ecosystem, cacheKey); hit != nil { + return *hit + } + meta, err := p.fetchUpstreamMetadata(fetchCtx, upstreamURL, nil, accept, "identity") + if err != nil { + return metadataResult{err: err} + } + digest := p.cacheMetadataBlob(fetchCtx, ecosystem, cacheKey, metadataStoragePath(ecosystem, cacheKey), meta) + return fetchedResult(meta, digest) + }) + return res +} + +// storedImmutable reads an immutable document from the metadata cache, or +// returns nil. Since the copy is never revalidated, it is checked against the +// digest recorded when it was stored; a row without one, or whose bytes don't +// match, is a miss, and the fetch that follows replaces it. +func (p *Proxy) storedImmutable(ctx context.Context, ecosystem, cacheKey string) *metadataResult { + entry, err := p.DB.GetMetadataCache(ecosystem, cacheKey) + if err != nil || entry == nil { + return nil + } + entry = p.migrateLegacyMetadataEntry(ctx, ecosystem, cacheKey, entry) + if entry == nil || !entry.ContentDigest.Valid { + return nil + } + want := entry.ContentDigest.String + body, contentType, err := p.readCachedMetadata(ctx, entry, func(b []byte) error { + sum := sha256.Sum256(b) + if "sha256:"+hex.EncodeToString(sum[:]) != want { + return errImmutableDigest + } + return nil + }) + if errors.Is(err, errImmutableDigest) { + p.Logger.Error("cached metadata failed integrity check", + "ecosystem", ecosystem, "key", cacheKey, "path", entry.StoragePath) + metrics.RecordIntegrityFailure(ecosystem, metrics.FailureDetail{Path: entry.StoragePath, Err: err}) + if err := p.DB.DiscardMetadataCache(ecosystem, cacheKey, entry.StoragePath, want); err != nil { + p.Logger.Warn("failed to clear corrupt metadata from cache", "error", err) + } + } + if err != nil { + return nil + } + res := metadataResult{body: body, contentType: contentType, contentEncoding: entry.ContentEncoding.String}.describedBy(entry) + return &res +} diff --git a/internal/handler/metadata_immutable_test.go b/internal/handler/metadata_immutable_test.go new file mode 100644 index 0000000..95b1a17 --- /dev/null +++ b/internal/handler/metadata_immutable_test.go @@ -0,0 +1,270 @@ +package handler + +import ( + "context" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + "time" + + "github.com/git-pkgs/cooldown" +) + +// countingUpstream answers every path with body and counts requests per path. +type countingUpstream struct { + server *httptest.Server + mu sync.Mutex + hits map[string]int + body func(path string) (string, bool) +} + +func newCountingUpstream(t *testing.T, body func(path string) (string, bool)) *countingUpstream { + t.Helper() + u := &countingUpstream{hits: map[string]int{}, body: body} + u.server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + u.mu.Lock() + u.hits[r.URL.Path]++ + u.mu.Unlock() + b, ok := u.body(r.URL.Path) + if !ok { + http.NotFound(w, r) + return + } + _, _ = w.Write([]byte(b)) + })) + t.Cleanup(u.server.Close) + return u +} + +func (u *countingUpstream) count(path string) int { + u.mu.Lock() + defer u.mu.Unlock() + return u.hits[path] +} + +const goPseudoVersion = "v0.0.0-20240102150405-abcdefabcdef" + +func goImmutableUpstream(t *testing.T) *countingUpstream { + return newCountingUpstream(t, func(path string) (string, bool) { + rest, ok := strings.CutPrefix(path, "/example.com/!mod/") + if !ok { + return "", false + } + switch { + case rest == "@v/list": + return "v1.0.0\n", true + case rest == "@latest", rest == "@v/main.info": + return `{"Version":"v1.0.0","Time":"2020-01-01T00:00:00Z"}`, true + case rest == "@v/v1.0.0.info": + return `{"Version":"v1.0.0","Time":"2020-01-01T00:00:00Z"}`, true + case rest == "@v/"+goPseudoVersion+".info": + return `{"Version":"` + goPseudoVersion + `","Time":"2024-01-02T15:04:05Z"}`, true + case strings.HasSuffix(rest, ".mod"): + return "module example.com/Mod\n", true + } + return "", false + }) +} + +// TestGoVersionFilesAreNotRevalidated checks that a canonical version's .mod +// and .info are fetched once and then served from the cache, with or without +// cache_metadata and whatever the metadata TTL, while queries, @v/list and +// @latest still go upstream. +func TestGoVersionFilesAreNotRevalidated(t *testing.T) { + for _, tt := range []struct { + name string + cacheMetadata, cooldown bool + }{ + {"cache_metadata off", false, false}, + {"cache_metadata on", true, false}, + {"cache_metadata off, cooldown", false, true}, + {"cache_metadata on, cooldown", true, true}, + } { + t.Run(tt.name, func(t *testing.T) { + testGoVersionFilesAreNotRevalidated(t, tt.cacheMetadata, tt.cooldown) + }) + } +} + +func testGoVersionFilesAreNotRevalidated(t *testing.T, cacheMetadata, withCooldown bool) { + u := goImmutableUpstream(t) + proxy, _, _, _ := setupTestProxy(t) + proxy.CacheMetadata = cacheMetadata + proxy.MetadataTTL = time.Nanosecond // every TTL-bound entry is already expired + if withCooldown { + proxy.Cooldown = &cooldown.Config{Default: "3d"} + } + h := NewGoHandlerWithUpstream(proxy, "http://localhost:8080", u.server.URL).Routes() + + once := []string{ + "/example.com/!mod/@v/v1.0.0.mod", + "/example.com/!mod/@v/v1.0.0.info", + "/example.com/!mod/@v/" + goPseudoVersion + ".mod", + "/example.com/!mod/@v/" + goPseudoVersion + ".info", + } + every := []string{ + "/example.com/!mod/@v/main.info", + "/example.com/!mod/@v/list", + "/example.com/!mod/@latest", + } + for range 3 { + for _, p := range append(append([]string{}, once...), every...) { + if w := goGet(h, p); w.Code != http.StatusOK { + t.Fatalf("GET %s = %d: %s", p, w.Code, w.Body.String()) + } + } + } + for _, p := range once { + if w := goGet(h, p); w.Header().Get("Warning") != "" { + t.Errorf("GET %s marked stale", p) + } + if got := u.count(p); got != 1 { + t.Errorf("upstream requests for %s = %d, want 1", p, got) + } + } + for _, p := range every { + if got := u.count(p); got < 2 { + t.Errorf("upstream requests for %s = %d, want one per request", p, got) + } + } +} + +func TestGoVersionImmutable(t *testing.T) { + tests := map[string]bool{ + "v1.0.0": true, + "v1.0.0-!r!c1": true, // v1.0.0-RC1 + "v2.0.0+incompatible": true, + goPseudoVersion: true, + "v1.2": false, // resolves to v1.2.0 + "v1.0.0+build": false, + "main": false, + "latest": false, + "v1.0.0-RC1": false, // not a valid escaped version + "": false, + "master-20240102150405-x": false, + } + for v, want := range tests { + if got := goVersionImmutable(v); got != want { + t.Errorf("goVersionImmutable(%q) = %v, want %v", v, got, want) + } + } +} + +// TestImmutableMetadataRefetchedWhenCorrupt checks that a stored immutable +// document whose bytes no longer match their digest is fetched again rather +// than returned for good. (A streamed hit of such a document aborts, as +// TestCachedMetadataHitAbortsOnDigestMismatch checks.) +func TestImmutableMetadataRefetchedWhenCorrupt(t *testing.T) { + u := goImmutableUpstream(t) + proxy, db, store, _ := setupTestProxy(t) + const ( + path = "/example.com/!mod/@v/v1.0.0.info" + key = "example.com/Mod/@v/v1.0.0.info" + want = `{"Version":"v1.0.0","Time":"2020-01-01T00:00:00Z"}` + ) + fetch := func() string { + t.Helper() + res := proxy.fetchImmutableMetadata(context.Background(), "golang", key, u.server.URL+path, "*/*") + if res.err != nil { + t.Fatalf("fetch: %v", res.err) + } + return string(res.body) + } + + fetch() + entry, err := db.GetMetadataCache("golang", key) + if err != nil || entry == nil { + t.Fatalf("document not stored: %v", err) + } + if _, _, err := store.Store(context.Background(), entry.StoragePath, strings.NewReader(`{"Version":"v6.6.6"}`)); err != nil { + t.Fatal(err) + } + + if got := fetch(); got != want { + t.Fatalf("got %q, want the upstream document", got) + } + if got := u.count(path); got != 2 { + t.Errorf("upstream requests = %d, want 2", got) + } + if got := fetch(); got != want { + t.Fatalf("got %q after refetch, want the upstream document", got) + } + if got := u.count(path); got != 2 { + t.Errorf("upstream requests after refetch = %d, want 2", got) + } +} + +// TestRPMContentAddressedRepodataIsNotRevalidated checks that repodata files +// named after their checksum are fetched once, while repomd.xml and plainly +// named files follow the TTL. +func TestRPMContentAddressedRepodataIsNotRevalidated(t *testing.T) { + const ( + sum = "2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae" + primary = "/releases/40/Everything/x86_64/os/repodata/" + sum + "-primary.xml.zst" + repomd = "/releases/40/Everything/x86_64/os/repodata/repomd.xml" + plain = "/releases/40/Everything/x86_64/os/repodata/primary.xml.gz" + ) + for _, cacheMetadata := range []bool{false, true} { + u := newCountingUpstream(t, func(string) (string, bool) { return "data", true }) + proxy, _, _, _ := setupTestProxy(t) + proxy.CacheMetadata = cacheMetadata + proxy.MetadataTTL = time.Nanosecond + h := NewRPMHandlerWithUpstream(proxy, "http://localhost:8080", u.server.URL).Routes() + + for range 3 { + for _, p := range []string{primary, repomd, plain} { + if w := goGet(h, p); w.Code != http.StatusOK || w.Body.String() != "data" { + t.Fatalf("GET %s = %d %q", p, w.Code, w.Body.String()) + } + } + } + if got := u.count(primary); got != 1 { + t.Errorf("cache_metadata=%v: upstream requests for checksum-named file = %d, want 1", cacheMetadata, got) + } + for _, p := range []string{repomd, plain} { + if got := u.count(p); got != 3 { + t.Errorf("cache_metadata=%v: upstream requests for %s = %d, want 3", cacheMetadata, p, got) + } + } + } +} + +func TestRPMContentAddressed(t *testing.T) { + sha256 := strings.Repeat("a", 64) + tests := map[string]bool{ + "os/repodata/" + sha256 + "-primary.xml.gz": true, + "os/repodata/" + strings.Repeat("0", 40) + "-other.xml.gz": true, + "os/repodata/" + strings.Repeat("f", 128) + "-comps.xml": true, + "os/repodata/repomd.xml": false, + "os/repodata/repomd.xml.asc": false, + "os/repodata/primary.xml.gz": false, + "os/repodata/" + strings.Repeat("a", 63) + "-primary.xml.gz": false, + "os/repodata/" + strings.Repeat("A", 64) + "-primary.xml.gz": false, + "os/repodata/" + sha256: false, + } + for p, want := range tests { + if got := rpmContentAddressed(p); got != want { + t.Errorf("rpmContentAddressed(%q) = %v, want %v", p, got, want) + } + } +} + +// TestImmutableMetadataOverSizeLimitIsStreamed checks that a checksum-named +// repodata file too large to buffer is streamed from upstream rather than +// refused. +func TestImmutableMetadataOverSizeLimitIsStreamed(t *testing.T) { + const path = "/os/repodata/" + "2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae" + "-filelists.xml.gz" + u := newCountingUpstream(t, func(string) (string, bool) { return "large document", true }) + proxy, db, _, _ := setupTestProxy(t) + proxy.MetadataMaxSize = 4 + h := NewRPMHandlerWithUpstream(proxy, "http://localhost:8080", u.server.URL).Routes() + + if w := goGet(h, path); w.Code != http.StatusOK || w.Body.String() != "large document" { + t.Fatalf("got %d %q, want the upstream document", w.Code, w.Body.String()) + } + if entry, _ := db.GetMetadataCache("rpm", hashedCacheKey(u.server.URL, strings.TrimPrefix(path, "/"))); entry != nil { + t.Error("stored a document over the size limit") + } +} diff --git a/internal/handler/metadata_not_modified_test.go b/internal/handler/metadata_not_modified_test.go new file mode 100644 index 0000000..fd690df --- /dev/null +++ b/internal/handler/metadata_not_modified_test.go @@ -0,0 +1,112 @@ +package handler + +import ( + "context" + "database/sql" + "net/http" + "net/http/httptest" + "sync/atomic" + "testing" + "time" + + "github.com/git-pkgs/proxy/internal/database" +) + +// TestMetadataNotModifiedKeepsStoredDocument checks that a 304 from upstream +// refreshes the cache row without writing the unchanged document to storage +// again, and still serves it. +func TestMetadataNotModifiedKeepsStoredDocument(t *testing.T) { + const body = `{"v":1}` + var notModified atomic.Int32 + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set(headerETag, `"v1"`) + if r.Header.Get("If-None-Match") == `"v1"` { + notModified.Add(1) + w.WriteHeader(http.StatusNotModified) + return + } + w.Header().Set(headerContentType, contentTypeJSON) + _, _ = w.Write([]byte(body)) + })) + t.Cleanup(upstream.Close) + + proxy, db, store, _ := setupTestProxy(t) + proxy.CacheMetadata = true + proxy.MetadataTTL = time.Nanosecond // revalidate on every request + proxy.HTTPClient = upstream.Client() + + ctx := context.Background() + first := proxy.fetchMetadataDocument(ctx, "test", "pkg", upstream.URL+"/pkg", contentTypeJSON, nil) + if first.err != nil { + t.Fatal(first.err) + } + stored, err := db.GetMetadataCache("test", "pkg") + if err != nil || stored == nil { + t.Fatalf("cache row after first fetch: %v, %v", stored, err) + } + + for range 2 { + res := proxy.fetchMetadataDocument(ctx, "test", "pkg", upstream.URL+"/pkg", contentTypeJSON, nil) + if res.err != nil || string(res.body) != body || res.digest != first.digest { + t.Fatalf("revalidated fetch = %q, digest %q, err %v; want %q, digest %q", res.body, res.digest, res.err, body, first.digest) + } + } + if n := notModified.Load(); n != 2 { + t.Fatalf("upstream answered 304 %d times, want 2", n) + } + if store.stores != 1 { + t.Errorf("document stored %d times, want once", store.stores) + } + refreshed, err := db.GetMetadataCache("test", "pkg") + if err != nil { + t.Fatal(err) + } + if !refreshed.FetchedAt.Time.After(stored.FetchedAt.Time) { + t.Errorf("fetched_at = %v, want later than %v", refreshed.FetchedAt.Time, stored.FetchedAt.Time) + } + if refreshed.ContentDigest != stored.ContentDigest || refreshed.ETag != stored.ETag { + t.Errorf("row validators changed: %+v, want %+v", refreshed, stored) + } +} + +// TestMetadataNotModifiedStoresRowWithoutDigest checks that a 304 for a row +// written before digests were recorded stores the document as before, so the +// row gains its digest. +func TestMetadataNotModifiedStoresRowWithoutDigest(t *testing.T) { + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Header.Get("If-None-Match") == `"v1"` { + w.WriteHeader(http.StatusNotModified) + return + } + t.Errorf("unconditional upstream request") + })) + t.Cleanup(upstream.Close) + + proxy, db, store, _ := setupTestProxy(t) + proxy.CacheMetadata = true + proxy.MetadataTTL = time.Nanosecond + proxy.HTTPClient = upstream.Client() + + path := metadataStoragePath("test", "pkg") + store.files[path] = []byte(`{"v":1}`) + if err := db.UpsertMetadataCache(&database.MetadataCacheEntry{ + Ecosystem: "test", + Name: "pkg", + StoragePath: path, + ETag: sql.NullString{String: `"v1"`, Valid: true}, + FetchedAt: sql.NullTime{Time: time.Now().Add(-time.Hour), Valid: true}, + }); err != nil { + t.Fatal(err) + } + + res := proxy.fetchMetadataDocument(context.Background(), "test", "pkg", upstream.URL+"/pkg", contentTypeJSON, nil) + if res.err != nil || string(res.body) != `{"v":1}` { + t.Fatalf("fetch = %q, %v", res.body, res.err) + } + if want := "sha256:" + sha256Hex(`{"v":1}`); res.digest != want { + t.Errorf("digest = %q, want %q", res.digest, want) + } + if store.stores != 1 { + t.Errorf("document stored %d times, want once", store.stores) + } +} diff --git a/internal/handler/metadata_path.go b/internal/handler/metadata_path.go new file mode 100644 index 0000000..4637909 --- /dev/null +++ b/internal/handler/metadata_path.go @@ -0,0 +1,134 @@ +package handler + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "fmt" + "io" + + "github.com/git-pkgs/proxy/internal/database" +) + +// metadataStoragePath builds the storage path for cached metadata. Cache +// keys are case-sensitive, but on a case-insensitive filesystem (APFS, NTFS) +// keys that differ only in case, such as Go's github.com/Sirupsen/logrus and +// github.com/sirupsen/logrus, would share one file. Keys may also hold names +// Windows reserves or end in a dot. So the path carries a hash of the exact +// key. Keys that already are lowercase SHA-256 hex digests are used as they +// are, so their existing entries stay valid. +func metadataStoragePath(ecosystem, cacheKey string) string { + if !isSHA256Hex(cacheKey) { + digest := sha256.Sum256([]byte(cacheKey)) + cacheKey = hex.EncodeToString(digest[:]) + } + return legacyMetadataStoragePath(ecosystem, cacheKey) +} + +// legacyMetadataStoragePath is where metadata was stored before paths were +// hashed: under the cache key itself. +func legacyMetadataStoragePath(ecosystem, cacheKey string) string { + return "_metadata/" + ecosystem + "/" + cacheKey + "/metadata" +} + +func isSHA256Hex(s string) bool { + if len(s) != 2*sha256.Size { + return false + } + for i := range len(s) { + c := s[i] + if (c < '0' || c > '9') && (c < 'a' || c > 'f') { + return false + } + } + return true +} + +// migrateLegacyMetadataEntry handles a cache row whose blob is still at its +// legacy, unhashed path. On a case-insensitive filesystem keys differing only +// in case shared that blob, so it is served only if it matches the row's digest. +func (p *Proxy) migrateLegacyMetadataEntry(ctx context.Context, ecosystem, cacheKey string, entry *database.MetadataCacheEntry) *database.MetadataCacheEntry { + if entry == nil || p.Storage == nil { + return entry + } + legacy := legacyMetadataStoragePath(ecosystem, cacheKey) + hashed := metadataStoragePath(ecosystem, cacheKey) + if entry.StoragePath != legacy || legacy == hashed { + return entry + } + var matches bool + if entry.ContentDigest.Valid { + digest, err := p.storedDigest(ctx, legacy) + if err != nil { + p.Logger.Warn("failed to read legacy metadata blob", "ecosystem", ecosystem, "key", cacheKey, "error", err) + return nil + } + matches = digest == entry.ContentDigest.String + } + if !matches { + if err := p.DB.ForgetMetadataDocument(ecosystem, cacheKey, legacy, hashed); err != nil { + p.Logger.Warn("failed to drop legacy metadata row", "ecosystem", ecosystem, "key", cacheKey, "error", err) + return nil + } + p.queueLegacyMetadataBlob(ecosystem, cacheKey, legacy) + return nil + } + if !p.moveLegacyMetadataBlob(ctx, entry, legacy, hashed) { + return entry + } + p.queueLegacyMetadataBlob(ecosystem, cacheKey, legacy) + moved := *entry + moved.StoragePath = hashed + return &moved +} + +// storedDigest hashes the blob at path as cacheMetadataBlob records it. +func (p *Proxy) storedDigest(ctx context.Context, path string) (string, error) { + r, err := p.Storage.Open(ctx, path) + if err != nil { + return "", err + } + defer func() { _ = r.Close() }() + h := sha256.New() + if _, err := io.Copy(h, r); err != nil { + return "", err + } + return "sha256:" + hex.EncodeToString(h.Sum(nil)), nil +} + +// moveLegacyMetadataBlob copies entry's verified blob from legacy to hashed +// and points the row there, reporting whether it did. +func (p *Proxy) moveLegacyMetadataBlob(ctx context.Context, entry *database.MetadataCacheEntry, legacy, hashed string) bool { + logFailure := func(err error) { + p.Logger.Warn("failed to move legacy metadata blob", "ecosystem", entry.Ecosystem, "key", entry.Name, "error", err) + } + r, err := p.Storage.Open(ctx, legacy) + if err != nil { + logFailure(err) + return false + } + defer func() { _ = r.Close() }() + _, hash, err := p.Storage.Store(ctx, hashed, r) + if err != nil { + logFailure(err) + return false + } + if "sha256:"+hash != entry.ContentDigest.String { + logFailure(fmt.Errorf("blob changed while being copied")) + return false + } + moved, err := p.DB.MoveMetadataCache(entry.Ecosystem, entry.Name, legacy, hashed, entry.ContentDigest.String) + if err != nil { + logFailure(err) + return false + } + return moved +} + +// queueLegacyMetadataBlob queues a row's legacy blob for deletion once the row +// no longer reads it. Reclaim skips it while another row still points there. +func (p *Proxy) queueLegacyMetadataBlob(ecosystem, cacheKey, legacy string) { + if err := p.DB.QueuePendingDelete(legacy); err != nil { + p.Logger.Warn("failed to queue legacy metadata blob for deletion", "ecosystem", ecosystem, "key", cacheKey, "error", err) + } +} diff --git a/internal/handler/metadata_path_test.go b/internal/handler/metadata_path_test.go new file mode 100644 index 0000000..b1f040c --- /dev/null +++ b/internal/handler/metadata_path_test.go @@ -0,0 +1,351 @@ +package handler + +import ( + "bytes" + "context" + "crypto/sha256" + "database/sql" + "encoding/hex" + "io" + "log/slog" + "net/http" + "net/http/httptest" + "path/filepath" + "slices" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/git-pkgs/proxy/internal/database" + "github.com/git-pkgs/proxy/internal/storage" + "github.com/git-pkgs/registries/fetch" +) + +func TestMetadataStoragePathKeepsCaseApart(t *testing.T) { + for _, pair := range [][2]string{ + {"github.com/Sirupsen/logrus", "github.com/sirupsen/logrus"}, + {"JSONStream", "jsonstream"}, + } { + a, b := metadataStoragePath("go", pair[0]), metadataStoragePath("go", pair[1]) + if strings.EqualFold(a, b) { + t.Errorf("%q and %q map to paths %q and %q, which a case-insensitive filesystem treats as one", pair[0], pair[1], a, b) + } + } + for _, key := range []string{"CON", "nul", "trailing.", "a/../b"} { + p := metadataStoragePath("npm", key) + if strings.Contains(p, key) { + t.Errorf("path %q contains the raw key %q", p, key) + } + } + // Keys that already are digests keep their path, so existing entries + // stay valid. + sum := sha256.Sum256([]byte("generic")) + digest := hex.EncodeToString(sum[:]) + if got, want := metadataStoragePath("generic", digest), "_metadata/generic/"+digest+"/metadata"; got != want { + t.Errorf("digest key path = %q, want %q", got, want) + } +} + +// fileStorageProxy returns a proxy whose metadata is cached on the local +// filesystem, as with file:// storage. +func fileStorageProxy(t *testing.T, client *http.Client) (*Proxy, *database.DB) { + t.Helper() + dir := t.TempDir() + db, err := database.Create(filepath.Join(dir, "test.db")) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = db.Close() }) + store, err := storage.OpenBucket(context.Background(), "file://"+filepath.Join(dir, "cache")) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = store.Close() }) + proxy := NewProxy(db, store, &mockFetcher{}, fetch.NewResolver(), slog.New(slog.NewTextHandler(io.Discard, nil))) + proxy.HTTPClient = client + proxy.CacheMetadata = true + proxy.MetadataTTL = time.Hour + return proxy, db +} + +// TestMetadataKeysDifferingInCaseCachedApart caches metadata for two keys +// that differ only in case on file storage. On a case-insensitive filesystem +// they shared one file, and the first key was served the second's document. +func TestMetadataKeysDifferingInCaseCachedApart(t *testing.T) { + var requests atomic.Int32 + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + requests.Add(1) + _, _ = io.WriteString(w, "document for "+r.URL.Path) + })) + defer upstream.Close() + proxy, _ := fileStorageProxy(t, upstream.Client()) + + keys := []string{"github.com/Sirupsen/logrus", "github.com/sirupsen/logrus"} + for range 2 { + for _, key := range keys { + body, _, err := proxy.FetchOrCacheMetadata(context.Background(), "go", key, upstream.URL+"/"+key) + if err != nil { + t.Fatal(err) + } + if want := "document for /" + key; string(body) != want { + t.Errorf("%s: served %q, want %q", key, body, want) + } + } + } + if got := requests.Load(); got != 2 { + t.Errorf("upstream requests = %d, want 2", got) + } +} + +// seedLegacyMetadata stores blob at key's legacy path and a row pointing at +// it, fetched at fetchedAt. The row's digest is that of document, or unset +// when document is empty. +func seedLegacyMetadata(t *testing.T, proxy *Proxy, db *database.DB, key, blob, document string, fetchedAt time.Time) string { + t.Helper() + legacy := legacyMetadataStoragePath("go", key) + if _, _, err := proxy.Storage.Store(context.Background(), legacy, strings.NewReader(blob)); err != nil { + t.Fatal(err) + } + entry := &database.MetadataCacheEntry{ + Ecosystem: "go", + Name: key, + StoragePath: legacy, + ETag: sql.NullString{String: `"v1"`, Valid: true}, + Size: sql.NullInt64{Int64: int64(len(blob)), Valid: true}, + FetchedAt: sql.NullTime{Time: fetchedAt, Valid: true}, + } + if document != "" { + sum := sha256.Sum256([]byte(document)) + entry.ContentDigest = sql.NullString{String: "sha256:" + hex.EncodeToString(sum[:]), Valid: true} + } + if err := db.UpsertMetadataCache(entry); err != nil { + t.Fatal(err) + } + return legacy +} + +func pendingDeletes(t *testing.T, db *database.DB) []string { + t.Helper() + due, err := db.GetDuePendingDeletes(time.Now().Add(time.Hour), 100) + if err != nil { + t.Fatal(err) + } + return due +} + +func metadataRowPath(t *testing.T, db *database.DB, key string) string { + t.Helper() + entry, err := db.GetMetadataCache("go", key) + if err != nil || entry == nil { + t.Fatalf("cache row for %s: %v %v", key, entry, err) + } + return entry.StoragePath +} + +// TestLegacyMetadataMatchingBlobServedWhenUpstreamDown checks that a row at +// its legacy path whose blob matches its digest is still served as a stale +// fallback, and is moved to the hashed path. +func TestLegacyMetadataMatchingBlobServedWhenUpstreamDown(t *testing.T) { + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusBadGateway) + })) + defer upstream.Close() + proxy, db := fileStorageProxy(t, upstream.Client()) + + const key = "github.com/Sirupsen/logrus" + legacy := seedLegacyMetadata(t, proxy, db, key, "old", "old", time.Now().Add(-2*time.Hour)) + + for range 2 { + body, _, err := proxy.FetchOrCacheMetadata(context.Background(), "go", key, upstream.URL+"/x") + if err != nil { + t.Fatalf("legacy document not served while upstream is down: %v", err) + } + if string(body) != "old" { + t.Fatalf("served %q, want %q", body, "old") + } + } + if got, want := metadataRowPath(t, db, key), metadataStoragePath("go", key); got != want { + t.Errorf("storage path = %q, want %q", got, want) + } + if due := pendingDeletes(t, db); !slices.Contains(due, legacy) { + t.Errorf("pending deletes = %v, want %q", due, legacy) + } +} + +// TestLegacyMetadataMatchingBlobServedFromCache checks that a fresh row at +// its legacy path whose blob matches is served without asking upstream. +func TestLegacyMetadataMatchingBlobServedFromCache(t *testing.T) { + var requests atomic.Int32 + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + requests.Add(1) + _, _ = io.WriteString(w, "fresh") + })) + defer upstream.Close() + proxy, db := fileStorageProxy(t, upstream.Client()) + + const key = "github.com/Sirupsen/logrus" + seedLegacyMetadata(t, proxy, db, key, "old", "old", time.Now()) + + body, _, err := proxy.FetchOrCacheMetadata(context.Background(), "go", key, upstream.URL+"/x") + if err != nil { + t.Fatal(err) + } + if string(body) != "old" || requests.Load() != 0 { + t.Errorf("served %q after %d upstream requests, want the cached document", body, requests.Load()) + } +} + +// TestLegacyMetadataMismatchedBlobNotServed checks that a legacy blob that +// does not match the row's digest, as when another key's document +// overwrote it, is neither served nor used as a fallback. +func TestLegacyMetadataMismatchedBlobNotServed(t *testing.T) { + var down atomic.Bool + var requests atomic.Int32 + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + requests.Add(1) + if down.Load() { + w.WriteHeader(http.StatusBadGateway) + return + } + if r.Header.Get("If-None-Match") != "" { + t.Errorf("revalidated a document that was dropped") + } + _, _ = io.WriteString(w, "fresh") + })) + defer upstream.Close() + proxy, db := fileStorageProxy(t, upstream.Client()) + + const key = "github.com/Sirupsen/logrus" + seedLegacyMetadata(t, proxy, db, key, "other key's document", "old", time.Now()) + down.Store(true) + if body, _, err := proxy.FetchOrCacheMetadata(context.Background(), "go", key, upstream.URL+"/x"); err == nil { + t.Fatalf("served %q, want an error while upstream is down", body) + } + + down.Store(false) + body, _, err := proxy.FetchOrCacheMetadata(context.Background(), "go", key, upstream.URL+"/x") + if err != nil { + t.Fatal(err) + } + if string(body) != "fresh" { + t.Errorf("served %q, want %q", body, "fresh") + } + if got, want := metadataRowPath(t, db, key), metadataStoragePath("go", key); got != want { + t.Errorf("storage path = %q, want %q", got, want) + } +} + +// caseFoldingStorage stores paths differing only in case as one file, as a +// case-insensitive filesystem does. +type caseFoldingStorage struct{ storage.Storage } + +func (s caseFoldingStorage) Store(ctx context.Context, path string, r io.Reader) (int64, string, error) { + return s.Storage.Store(ctx, strings.ToLower(path), r) +} + +func (s caseFoldingStorage) Open(ctx context.Context, path string) (io.ReadCloser, error) { + return s.Storage.Open(ctx, strings.ToLower(path)) +} + +func (s caseFoldingStorage) Exists(ctx context.Context, path string) (bool, error) { + return s.Storage.Exists(ctx, strings.ToLower(path)) +} + +func (s caseFoldingStorage) Delete(ctx context.Context, path string) error { + return s.Storage.Delete(ctx, strings.ToLower(path)) +} + +func (s caseFoldingStorage) Size(ctx context.Context, path string) (int64, error) { + return s.Storage.Size(ctx, strings.ToLower(path)) +} + +// TestLegacyMetadataCaseVariantRefetchedAfterReclaim checks that on +// case-insensitive storage, a key whose legacy blob was shared with a case +// variant and deleted after that variant moved is fetched again rather than +// served. +func TestLegacyMetadataCaseVariantRefetchedAfterReclaim(t *testing.T) { + var requests atomic.Int32 + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + requests.Add(1) + _, _ = io.WriteString(w, "fresh") + })) + defer upstream.Close() + proxy, db := fileStorageProxy(t, upstream.Client()) + proxy.Storage = caseFoldingStorage{proxy.Storage} + + const upper, lower = "github.com/Sirupsen/logrus", "github.com/sirupsen/logrus" + seedLegacyMetadata(t, proxy, db, upper, "doc", "doc", time.Now()) + seedLegacyMetadata(t, proxy, db, lower, "doc", "doc", time.Now()) + + if body, _, err := proxy.FetchOrCacheMetadata(context.Background(), "go", upper, upstream.URL+"/x"); err != nil || string(body) != "doc" { + t.Fatalf("FetchOrCacheMetadata(%s) = %q, %v; want the migrated document", upper, body, err) + } + // Reclaim deletes the queued legacy blob, which is also lower's. + for _, path := range pendingDeletes(t, db) { + if err := proxy.Storage.Delete(context.Background(), path); err != nil { + t.Fatal(err) + } + } + + body, _, err := proxy.FetchOrCacheMetadata(context.Background(), "go", lower, upstream.URL+"/x") + if err != nil { + t.Fatal(err) + } + if string(body) != "fresh" || requests.Load() != 1 { + t.Errorf("served %q after %d upstream requests, want a fresh fetch", body, requests.Load()) + } + if got, want := metadataRowPath(t, db, lower), metadataStoragePath("go", lower); got != want { + t.Errorf("storage path = %q, want %q", got, want) + } +} + +// TestLegacyMetadataPathRefetched checks that a row at its legacy path with +// no digest to check its blob against is fetched again, moved to the hashed +// path, and its old blob queued for deletion. +func TestLegacyMetadataPathRefetched(t *testing.T) { + var requests atomic.Int32 + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + requests.Add(1) + _, _ = io.WriteString(w, "fresh") + })) + defer upstream.Close() + proxy, db := fileStorageProxy(t, upstream.Client()) + + const key = "github.com/Sirupsen/logrus" + legacy := legacyMetadataStoragePath("go", key) + if _, _, err := proxy.Storage.Store(context.Background(), legacy, bytes.NewReader([]byte("old"))); err != nil { + t.Fatal(err) + } + if err := db.UpsertMetadataCache(&database.MetadataCacheEntry{ + Ecosystem: "go", + Name: key, + StoragePath: legacy, + Size: sql.NullInt64{Int64: 3, Valid: true}, + FetchedAt: sql.NullTime{Time: time.Now(), Valid: true}, + }); err != nil { + t.Fatal(err) + } + + body, _, err := proxy.FetchOrCacheMetadata(context.Background(), "go", key, upstream.URL+"/x") + if err != nil { + t.Fatal(err) + } + if string(body) != "fresh" || requests.Load() != 1 { + t.Fatalf("served %q after %d upstream requests, want a fresh fetch", body, requests.Load()) + } + entry, err := db.GetMetadataCache("go", key) + if err != nil || entry == nil { + t.Fatalf("cache row: %v %v", entry, err) + } + if entry.StoragePath != metadataStoragePath("go", key) { + t.Errorf("storage path = %q, want %q", entry.StoragePath, metadataStoragePath("go", key)) + } + due, err := db.GetDuePendingDeletes(time.Now().Add(time.Hour), 10) + if err != nil { + t.Fatal(err) + } + if !slices.Contains(due, legacy) { + t.Errorf("pending deletes = %v, want %q", due, legacy) + } +} diff --git a/internal/handler/metadata_stored.go b/internal/handler/metadata_stored.go new file mode 100644 index 0000000..fc16d43 --- /dev/null +++ b/internal/handler/metadata_stored.go @@ -0,0 +1,313 @@ +package handler + +import ( + "context" + "crypto/rand" + "crypto/sha256" + "encoding/hex" + "errors" + "fmt" + "hash" + "io" + "net/http" + "time" + + "github.com/git-pkgs/proxy/internal/database" + "github.com/git-pkgs/proxy/internal/metrics" +) + +// A metadata document can be rewritten from storage instead of from memory: +// storedMetadataDocument streams it from upstream into storage, and the +// rewrite reads it back as often as it needs. Nothing holds the whole +// document, so its size is not limited by metadata_max_size or by memory. + +// errMetadataNotStored is returned when metadata is not cached in storage, so +// a document has to be read into memory. +var errMetadataNotStored = errors.New("metadata is not cached in storage") + +// errStoredMetadataChanged is returned when a stored document no longer has +// the digest its cache row records: a fetch replaced it while it was read. +var errStoredMetadataChanged = errors.New("stored metadata changed while it was read") + +// storedMetadataDocument returns the cache row of a metadata document stored +// uncompressed with its digest: the stored copy while it is within its TTL, +// or else the document fetched from upstream and stored, or the stored copy +// when upstream fails. The document is streamed from upstream into storage +// without being held in memory, so a fetch takes no metadata_max_size limit. +// Concurrent calls for one document share a fetch, and instances sharing the +// database take turns as for other metadata. +// +// validate, when not nil, checks a fetched document before it replaces the +// stored one; a document it rejects is not stored, and the stored copy is +// served as when upstream fails. It does not check a stored copy within its +// TTL. +// +// It returns errMetadataNotStored when the proxy doesn't cache metadata or +// storing the document failed, and the caller reads it into memory instead. +func (p *Proxy) storedMetadataDocument(ctx context.Context, ecosystem, cacheKey, upstreamURL, accept string, validate func(io.Reader) error) (*database.MetadataCacheEntry, error) { + res := p.storedMetadata(ctx, ecosystem, cacheKey, upstreamURL, accept, validate, "") + return res.entry, res.err +} + +// storedMetadata implements storedMetadataDocument, and reports in the +// result whether the row was read from cache or served stale. A row with +// the digest gone, one whose stored copy was missing or out of date when +// read, is not served or revalidated, within its TTL or not, and the +// document is fetched again. +func (p *Proxy) storedMetadata(ctx context.Context, ecosystem, cacheKey, upstreamURL, accept string, validate func(io.Reader) error, gone string) metadataResult { + if !p.CacheMetadata || p.DB == nil || p.Storage == nil || p.MetadataTTL <= 0 { + return metadataResult{err: errMetadataNotStored} + } + if containsPathTraversal(cacheKey) { + return metadataResult{err: fmt.Errorf("invalid cache key: %q", cacheKey)} + } + if entry, fresh := p.storedMetadataEntryState(ctx, ecosystem, cacheKey, gone); fresh { + metrics.RecordMetadataCacheHit(ecosystem, int(entry.Size.Int64)) + p.recordMetadataRead(entry) + return metadataResult{entry: entry, fromCache: true} + } + p.recordMetadataCacheMiss(ecosystem) + + key := metadataCoalesceKey(ecosystem, cacheKey, upstreamURL, accept, "", false) + "\x00stored" + res, _ := p.coalesceMetadata(ctx, key, func(fetchCtx context.Context) metadataResult { + entry, fresh := p.storedMetadataEntryState(fetchCtx, ecosystem, cacheKey, gone) + if fresh { + return metadataResult{entry: entry} + } + release, outcome, err := p.awaitFetchLease(fetchCtx, metrics.CacheKindMetadata, key, func() bool { + entry, fresh = p.storedMetadataEntryState(fetchCtx, ecosystem, cacheKey, gone) + return fresh + }) + if err != nil { + return metadataResult{err: err} + } + switch outcome { + case leaseStored: + return metadataResult{entry: entry} + case leaseFailed: + // Serve the stored copy, as the holder did, rather than trying + // the failing upstream again. + p.reloadUpstreamHolds() + if usableStoredMetadata(entry) { + return p.staleStoredMetadata(ecosystem, cacheKey, entry, errFetchFailedElsewhere) + } + case leaseFetch: + } + res := metadataResult{err: errSharedFetchAbandoned} + defer func() { release(res.err != nil || res.stale) }() + res = p.fetchStoredMetadata(fetchCtx, ecosystem, cacheKey, upstreamURL, accept, validate, entry) + return res + }) + return res +} + +// storedMetadataEntryState reads the cache row of a document and reports +// whether it is within its TTL and usable by storedMetadataDocument. A row +// with the digest gone is returned as nil. +func (p *Proxy) storedMetadataEntryState(ctx context.Context, ecosystem, cacheKey, gone string) (*database.MetadataCacheEntry, bool) { + entry, _ := p.DB.GetMetadataCache(ecosystem, cacheKey) + entry = p.migrateLegacyMetadataEntry(ctx, ecosystem, cacheKey, entry) + if gone != "" && entry != nil && entry.ContentDigest.String == gone { + return nil, false + } + fresh := usableStoredMetadata(entry) && entry.FetchedAt.Valid && time.Since(entry.FetchedAt.Time) < p.MetadataTTL + return entry, fresh +} + +// usableStoredMetadata reports whether entry describes a document stored +// uncompressed with its digest, which a rewrite can read back and check. +func usableStoredMetadata(entry *database.MetadataCacheEntry) bool { + return entry != nil && entry.ContentDigest.Valid && entry.ContentEncoding.String == "" +} + +// fetchStoredMetadata fetches a document from upstream into storage, +// revalidating entry when there is one, and falls back to entry when +// upstream fails or validate rejects what it sent. A failure to store is +// returned as it is, for the caller to read the document into memory. +func (p *Proxy) fetchStoredMetadata(ctx context.Context, ecosystem, cacheKey, upstreamURL, accept string, validate func(io.Reader) error, entry *database.MetadataCacheEntry) metadataResult { + revalidate := entry + if !usableStoredMetadata(entry) { + revalidate = nil + } + stored, err := p.storeUpstreamMetadata(ctx, ecosystem, cacheKey, upstreamURL, accept, validate, revalidate) + if errors.Is(err, errStale304) { + stored, err = p.storeUpstreamMetadata(ctx, ecosystem, cacheKey, upstreamURL, accept, validate, nil) + } + if err == nil { + return metadataResult{entry: stored} + } + // As in fetchMetadataFromUpstream, any upstream failure, a 404 included, + // falls back to the stored copy. + if !usableStoredMetadata(entry) || errors.Is(err, errMetadataNotStored) { + return metadataResult{err: err} + } + return p.staleStoredMetadata(ecosystem, cacheKey, entry, err) +} + +// staleStoredMetadata falls back to the stored document entry describes after +// the upstream fetch failed with err. +func (p *Proxy) staleStoredMetadata(ecosystem, cacheKey string, entry *database.MetadataCacheEntry, err error) metadataResult { + p.Logger.Warn("upstream metadata fetch failed, serving cached copy", + "ecosystem", ecosystem, "key", cacheKey, "error", err) + entry = p.currentMetadataEntry(ecosystem, cacheKey, entry) + if !usableStoredMetadata(entry) { + return metadataResult{err: fmt.Errorf("upstream failed and no usable cached metadata: %w", err)} + } + return metadataResult{entry: entry, stale: true, upstreamErr: err} +} + +// storeUpstreamMetadata fetches a document and streams it into storage, and +// returns its new cache row. On a 304 for entry it only moves the row's +// fetched_at on; errStale304 means the stored copy is gone or the row was +// replaced meanwhile, and the caller should fetch without validators. +// +// With validate, the document is staged under a path of its own and checked +// there first, so one validate rejects never replaces the stored copy. +func (p *Proxy) storeUpstreamMetadata(ctx context.Context, ecosystem, cacheKey, upstreamURL, accept string, validate func(io.Reader) error, entry *database.MetadataCacheEntry) (*database.MetadataCacheEntry, error) { + resp, err := p.requestUpstreamMetadata(ctx, upstreamURL, entry, accept, "") + if err != nil { + return nil, err + } + defer func() { _ = resp.Body.Close() }() + + if resp.StatusCode == http.StatusNotModified && entry != nil { + if ok, err := p.Storage.Exists(ctx, entry.StoragePath); err != nil || !ok { + return nil, errStale304 + } + refreshed, err := p.DB.RefreshMetadataCache(ecosystem, cacheKey, entry.ContentDigest.String, time.Now()) + if err != nil || !refreshed { + return nil, errStale304 + } + return p.currentMetadataEntry(ecosystem, cacheKey, entry), nil + } + if err := upstreamMetadataStatus(resp); err != nil { + return nil, err + } + + meta := &upstreamMetadata{ + contentType: resp.Header.Get(headerContentType), + etag: resp.Header.Get(headerETag), + } + if meta.contentType == "" { + meta.contentType = contentTypeJSON + } + if lm := resp.Header.Get(headerLastModified); lm != "" { + meta.lastModified, _ = http.ParseTime(lm) + } + limit := p.MetadataStreamMaxSize + if limit <= 0 { + limit = defaultMetadataStreamMaxSize + } + // Go decompresses the body, since no Accept-Encoding was set, so it is + // stored uncompressed. + var body io.Reader = &limitedBody{r: upstreamBodyReader{resp.Body}, left: limit} + if validate != nil { + staged, err := p.stageMetadata(ctx, ecosystem, cacheKey, body, validate) + if err != nil { + return nil, err + } + defer func() { _ = staged.Close() }() + body = staged + } + if _, err := p.storeMetadataBlob(ctx, ecosystem, cacheKey, metadataStoragePath(ecosystem, cacheKey), body, meta); err != nil { + return nil, notStored("", err) + } + stored, err := p.DB.GetMetadataCache(ecosystem, cacheKey) + if err != nil || !usableStoredMetadata(stored) { + return nil, fmt.Errorf("reading the stored metadata row: %w", errors.Join(err, errMetadataNotStored)) + } + return stored, nil +} + +// stageMetadata stores body under a staging path of its own, checks it with +// validate, and returns it opened for reading, to be stored in place of the +// cached copy. The staged copy is deleted when the reader is closed. A +// failure to store it is returned as errMetadataNotStored. +func (p *Proxy) stageMetadata(ctx context.Context, ecosystem, cacheKey string, body io.Reader, validate func(io.Reader) error) (io.ReadCloser, error) { + path := metadataStoragePath(ecosystem, cacheKey) + ".staged-" + rand.Text() + discard := func() { + if err := p.Storage.Delete(context.WithoutCancel(ctx), path); err != nil { + p.Logger.Warn("failed to delete staged metadata", "ecosystem", ecosystem, "key", cacheKey, "error", err) + } + } + if _, _, err := p.Storage.Store(ctx, path, body); err != nil { + discard() + return nil, notStored("staging: ", err) + } + if err := readStored(func() (io.ReadCloser, error) { return p.Storage.Open(ctx, path) }, validate); err != nil { + discard() + return nil, err + } + staged, err := p.Storage.Open(ctx, path) + if err != nil { + discard() + return nil, fmt.Errorf("%w: reading staged copy: %w", errMetadataNotStored, err) + } + return &stagedReader{ReadCloser: staged, discard: discard}, nil +} + +// limitedBody fails with ErrMetadataTooLarge, as an upstream failure, once +// r has sent more than left bytes. +type limitedBody struct { + r io.Reader + left int64 +} + +func (l *limitedBody) Read(b []byte) (int, error) { + n, err := l.r.Read(b) + if l.left -= int64(n); l.left < 0 { + return 0, &upstreamBodyError{ErrMetadataTooLarge} + } + return n, err +} + +// notStored returns a failure to store a document as errMetadataNotStored, +// unless reading it from upstream failed. +func notStored(what string, err error) error { + if body := (*upstreamBodyError)(nil); errors.As(err, &body) { + return body + } + return fmt.Errorf("%w: %s%w", errMetadataNotStored, what, err) +} + +// stagedReader deletes the staged copy it reads when closed. +type stagedReader struct { + io.ReadCloser + discard func() +} + +func (s *stagedReader) Close() error { + err := s.ReadCloser.Close() + s.discard() + return err +} + +// openStoredMetadata opens the document entry describes. Reading it to the +// end fails with errStoredMetadataChanged when its bytes don't have the +// digest entry records. +func (p *Proxy) openStoredMetadata(ctx context.Context, entry *database.MetadataCacheEntry) (io.ReadCloser, error) { + r, err := p.Storage.Open(ctx, entry.StoragePath) + if err != nil { + return nil, err + } + return &digestReader{r: r, h: sha256.New(), want: entry.ContentDigest.String}, nil +} + +// digestReader checks at the end of its reader that what it read has the +// digest want, in the form the metadata cache records it. +type digestReader struct { + r io.ReadCloser + h hash.Hash + want string +} + +func (d *digestReader) Read(b []byte) (int, error) { + n, err := d.r.Read(b) + d.h.Write(b[:n]) + if errors.Is(err, io.EOF) && "sha256:"+hex.EncodeToString(d.h.Sum(nil)) != d.want { + return n, errStoredMetadataChanged + } + return n, err +} + +func (d *digestReader) Close() error { return d.r.Close() } diff --git a/internal/handler/metadata_stream.go b/internal/handler/metadata_stream.go new file mode 100644 index 0000000..c165b81 --- /dev/null +++ b/internal/handler/metadata_stream.go @@ -0,0 +1,146 @@ +package handler + +import ( + "context" + "errors" + "io" + "net/http" + "strconv" + "strings" + "time" + + "github.com/git-pkgs/proxy/internal/database" + "github.com/git-pkgs/proxy/internal/metrics" +) + +// serveCachedMetadata answers a ProxyCached request from a fresh metadata +// cache row by streaming the stored document, rather than reading it into +// memory first, so concurrent hits on a large document don't each hold a copy +// of it. The bytes are checked against the row's digest as they are sent, and +// a mismatch aborts the response and drops the row, the way a corrupt cached +// artifact is handled. +// +// It reports false, having written nothing, when the request should take the +// buffered path instead: no fresh row, a row without a digest or size, a +// document over the metadata size limit, or one that can't be opened. +func (p *Proxy) serveCachedMetadata(w http.ResponseWriter, r *http.Request, ecosystem, cacheKey string) bool { + return p.serveStoredMetadata(w, r, ecosystem, cacheKey, false) +} + +// serveStoredMetadata is serveCachedMetadata. With immutable set the row is +// served whatever its age and never marked stale, for documents that can't +// change upstream (see proxyImmutable). +func (p *Proxy) serveStoredMetadata(w http.ResponseWriter, r *http.Request, ecosystem, cacheKey string, immutable bool) bool { + entry := p.storedMetadataEntry(ecosystem, cacheKey, immutable) + if entry == nil { + return false + } + return p.serveMetadataEntry(w, r, ecosystem, cacheKey, entry, immutable) +} + +// serveMetadataEntry is serveStoredMetadata for entry, a row +// storedMetadataEntry or streamableMetadata accepted. +func (p *Proxy) serveMetadataEntry(w http.ResponseWriter, r *http.Request, ecosystem, cacheKey string, entry *database.MetadataCacheEntry, immutable bool) bool { + body, err := p.openMetadataEntry(r.Context(), ecosystem, cacheKey, entry) + if err != nil { + return false + } + defer func() { _ = body.Close() }() + + p.recordStreamedMetadataHit(ecosystem, entry) + + cm := p.cachedMetaFor(entry) + if immutable { + cm.stale = false + } + if writeMetadataValidators(w, r, cm) { + return true + } + contentType := contentTypeJSON + if entry.ContentType.Valid { + contentType = entry.ContentType.String + } + w.Header().Set(headerContentType, contentType) + w.Header().Set(headerContentLength, strconv.FormatInt(entry.Size.Int64, 10)) + if entry.ContentEncoding.String != "" { + w.Header().Set(headerContentEncoding, entry.ContentEncoding.String) + } + markStale(w, cm.stale) + w.WriteHeader(http.StatusOK) + if r.Method != http.MethodHead { + copyArtifactBody(w, body, entry.Size.Int64, false) + } + return true +} + +// freshMetadataEntry returns the metadata cache row for ecosystem and +// cacheKey when its document can be streamed: the row is within its TTL and +// records a sha256 digest and a size within the metadata size limit. It +// returns nil otherwise. +func (p *Proxy) freshMetadataEntry(ecosystem, cacheKey string) *database.MetadataCacheEntry { + return p.storedMetadataEntry(ecosystem, cacheKey, false) +} + +// storedMetadataEntry is freshMetadataEntry, ignoring the row's age when +// immutable is set. +func (p *Proxy) storedMetadataEntry(ecosystem, cacheKey string, immutable bool) *database.MetadataCacheEntry { + if p.DB == nil || p.Storage == nil || (!immutable && p.MetadataTTL <= 0) || containsPathTraversal(cacheKey) { + return nil + } + entry, err := p.DB.GetMetadataCache(ecosystem, cacheKey) + if err != nil || entry == nil || !entry.FetchedAt.Valid { + return nil + } + if !immutable && time.Since(entry.FetchedAt.Time) >= p.MetadataTTL { + return nil + } + if !p.streamableMetadata(entry) { + return nil + } + return entry +} + +// streamableMetadata reports whether entry records a sha256 digest and a +// size within the metadata size limit, so its document can be streamed. +func (p *Proxy) streamableMetadata(entry *database.MetadataCacheEntry) bool { + limit := p.MetadataMaxSize + if limit <= 0 { + limit = defaultMetadataMaxSize + } + return entry.ContentDigest.Valid && strings.HasPrefix(entry.ContentDigest.String, "sha256:") && entry.Size.Valid && entry.Size.Int64 <= limit +} + +// openMetadataEntry opens the stored document of a row freshMetadataEntry +// returned. Its bytes are checked against the row's digest as they are read: +// a mismatch fails the read at the end and drops the row, so the next +// request fetches the document again. +func (p *Proxy) openMetadataEntry(ctx context.Context, ecosystem, cacheKey string, entry *database.MetadataCacheEntry) (io.ReadCloser, error) { + checks, err := newIntegrityChecks(strings.TrimPrefix(entry.ContentDigest.String, "sha256:"), "") + if err != nil { + return nil, err + } + stored, err := p.Storage.Open(ctx, entry.StoragePath) + if err != nil { + return nil, err + } + body, err := checks.wrapFailOnMismatch(stored, func(reason string) { + p.Logger.Error("cached metadata failed integrity check", + "ecosystem", ecosystem, "key", cacheKey, "path", entry.StoragePath, "reason", reason) + metrics.RecordIntegrityFailure(ecosystem, metrics.FailureDetail{ + Path: entry.StoragePath, Err: errors.New(reason)}) + if err := p.DB.DiscardMetadataCache(ecosystem, cacheKey, entry.StoragePath, entry.ContentDigest.String); err != nil { + p.Logger.Warn("failed to clear corrupt metadata from cache", "error", err) + } + }) + if err != nil { + _ = stored.Close() + return nil, err + } + return body, nil +} + +// recordStreamedMetadataHit counts a hit on a row served by streaming. +func (p *Proxy) recordStreamedMetadataHit(ecosystem string, entry *database.MetadataCacheEntry) { + p.recordMetadataRead(entry) + metrics.RecordMetadataCacheHit(ecosystem, int(entry.Size.Int64)) +} diff --git a/internal/handler/metadata_stream_test.go b/internal/handler/metadata_stream_test.go new file mode 100644 index 0000000..702eea8 --- /dev/null +++ b/internal/handler/metadata_stream_test.go @@ -0,0 +1,223 @@ +package handler + +import ( + "bytes" + "context" + "io" + "net/http" + "net/http/httptest" + "slices" + "strconv" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/git-pkgs/proxy/internal/storage" +) + +// stallingStorage hands out cached metadata readers that return the first +// head bytes and then block until release closes, so a test can see whether a +// response starts before the whole document has been read. +type stallingStorage struct { + storage.Storage + head int + release chan struct{} +} + +func (s *stallingStorage) Open(ctx context.Context, path string) (io.ReadCloser, error) { + rc, err := s.Storage.Open(ctx, path) + if err != nil || !strings.HasPrefix(path, "_metadata/") { + return rc, err + } + return &stallingReader{ReadCloser: rc, left: s.head, release: s.release}, nil +} + +type stallingReader struct { + io.ReadCloser + left int + release chan struct{} +} + +func (r *stallingReader) Read(p []byte) (int, error) { + if r.left == 0 { + <-r.release + return r.ReadCloser.Read(p) + } + if len(p) > r.left { + p = p[:r.left] + } + n, err := r.ReadCloser.Read(p) + r.left -= n + return n, err +} + +// cachedMetadataServer serves doc through ProxyCached and caches it with one +// request. upstreamHits counts the requests that reached the upstream. +func cachedMetadataServer(t *testing.T, doc []byte) (proxy *Proxy, store *mockStorage, srv *httptest.Server, upstreamHits *atomic.Int32) { + t.Helper() + upstreamHits = &atomic.Int32{} + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + upstreamHits.Add(1) + w.Header().Set(headerContentType, "application/x-test") + w.Header().Set(headerETag, `"v1"`) + _, _ = w.Write(doc) + })) + t.Cleanup(upstream.Close) + + proxy, _, store, _ = setupTestProxy(t) + proxy.CacheMetadata = true + proxy.MetadataTTL = time.Hour + proxy.HTTPClient = upstream.Client() + srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + proxy.ProxyCached(w, r, upstream.URL+"/doc", "test", "doc", "*/*") + })) + t.Cleanup(srv.Close) + + resp, err := http.Get(srv.URL) + if err != nil { + t.Fatalf("populating cache: %v", err) + } + _, _ = io.Copy(io.Discard, resp.Body) + _ = resp.Body.Close() + if resp.StatusCode != http.StatusOK { + t.Fatalf("populating cache: status %d", resp.StatusCode) + } + return proxy, store, srv, upstreamHits +} + +func TestConcurrentMetadataCacheHitsStream(t *testing.T) { + const callers = 10 + doc := bytes.Repeat([]byte("0123456789abcdef"), 1<<18) // 4 MB + proxy, store, srv, _ := cachedMetadataServer(t, doc) + + gate := &stallingStorage{Storage: store, head: 64 << 10, release: make(chan struct{})} + proxy.Storage = gate + var releaseOnce sync.Once + release := func() { releaseOnce.Do(func() { close(gate.release) }) } + t.Cleanup(release) + + // Every hit has to start its response while its reader is stalled after + // the first 64 KB. A hit that reads the document into memory first can't + // send anything until release. + type result struct { + resp *http.Response + first []byte + err error + } + started := make(chan result, callers) + for range callers { + go func() { + resp, err := http.Get(srv.URL) + if err != nil { + started <- result{err: err} + return + } + first := make([]byte, 1024) + _, err = io.ReadFull(resp.Body, first) + started <- result{resp: resp, first: first, err: err} + }() + } + results := make([]result, 0, callers) + timeout := time.After(5 * time.Second) + streamed := 0 + for len(results) < callers { + select { + case res := <-started: + results = append(results, res) + case <-timeout: + // Let the stalled hits finish, so the server can shut down. + release() + timeout = nil + streamed = len(results) + } + } + release() + t.Cleanup(func() { + for _, res := range results { + if res.resp != nil { + _ = res.resp.Body.Close() + } + } + }) + if timeout == nil { + t.Fatalf("%d of %d concurrent cache hits started their response before the document was read to its end", streamed, callers) + } + + for _, res := range results { + if res.err != nil { + t.Fatalf("cache hit: %v", res.err) + } + rest, err := io.ReadAll(res.resp.Body) + _ = res.resp.Body.Close() + if err != nil { + t.Fatalf("reading cache hit: %v", err) + } + if body := slices.Concat(res.first, rest); !bytes.Equal(body, doc) { + t.Fatalf("cache hit returned %d bytes, want the %d-byte document", len(body), len(doc)) + } + if got := res.resp.Header.Get(headerContentType); got != "application/x-test" { + t.Errorf("Content-Type = %q, want application/x-test", got) + } + if got := res.resp.Header.Get(headerContentLength); got != strconv.Itoa(len(doc)) { + t.Errorf("Content-Length = %q, want %d", got, len(doc)) + } + if got := res.resp.Header.Get(headerETag); got != `"v1"` { + t.Errorf("ETag = %q, want %q", got, `"v1"`) + } + } + + req, _ := http.NewRequest(http.MethodGet, srv.URL, nil) + req.Header.Set("If-None-Match", `"v1"`) + resp, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatalf("conditional cache hit: %v", err) + } + _ = resp.Body.Close() + if resp.StatusCode != http.StatusNotModified { + t.Errorf("conditional cache hit: status %d, want 304", resp.StatusCode) + } +} + +func TestCachedMetadataHitAbortsOnDigestMismatch(t *testing.T) { + doc := bytes.Repeat([]byte("metadata "), 1<<14) + _, store, srv, upstreamHits := cachedMetadataServer(t, doc) + + corrupt := bytes.Clone(doc) + corrupt[len(corrupt)-1] ^= 0xff + store.mu.Lock() + store.files[metadataStoragePath("test", "doc")] = corrupt + store.mu.Unlock() + + resp, err := http.Get(srv.URL) + if err != nil { + t.Fatalf("cache hit: %v", err) + } + defer func() { _ = resp.Body.Close() }() + body, err := io.ReadAll(resp.Body) + if err == nil { + t.Fatalf("cache hit completed with %d bytes of a document that doesn't match its digest, want the response aborted", len(body)) + } + if len(body) >= len(doc) { + t.Errorf("aborted response still delivered %d of %d bytes", len(body), len(doc)) + } + + // The corrupt row is dropped, so the next request fetches the document + // from upstream again instead of aborting until the TTL runs out. + resp, err = http.Get(srv.URL) + if err != nil { + t.Fatalf("request after abort: %v", err) + } + defer func() { _ = resp.Body.Close() }() + body, err = io.ReadAll(resp.Body) + if err != nil { + t.Fatalf("request after abort: %v", err) + } + if !bytes.Equal(body, doc) { + t.Errorf("request after abort got %d bytes, want the upstream document (%d bytes)", len(body), len(doc)) + } + if got := upstreamHits.Load(); got != 2 { + t.Errorf("upstream requests = %d, want 2 (populate, then refetch after the corrupt hit)", got) + } +} diff --git a/internal/handler/metadata_truncated_test.go b/internal/handler/metadata_truncated_test.go new file mode 100644 index 0000000..5044374 --- /dev/null +++ b/internal/handler/metadata_truncated_test.go @@ -0,0 +1,121 @@ +package handler + +import ( + "fmt" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + + "github.com/git-pkgs/cooldown" +) + +// cutMetadataUpstream serves one npm packument and, when cut is set, closes +// the connection halfway through the document it announced. +type cutMetadataUpstream struct { + *httptest.Server + mu sync.Mutex + body string + cut bool +} + +func newCutMetadataUpstream(t *testing.T, body string) *cutMetadataUpstream { + t.Helper() + u := &cutMetadataUpstream{body: body} + u.Server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + u.mu.Lock() + body, cut := u.body, u.cut + u.mu.Unlock() + if r.URL.Path != "/pkg" { + http.NotFound(w, r) + return + } + w.Header().Set("Content-Type", "application/json") + w.Header().Set("Content-Length", fmt.Sprint(len(body))) + if cut { + _, _ = io.WriteString(w, body[:len(body)/2]) + return + } + _, _ = io.WriteString(w, body) + })) + t.Cleanup(u.Close) + return u +} + +func (u *cutMetadataUpstream) set(body string, cut bool) { + u.mu.Lock() + defer u.mu.Unlock() + u.body, u.cut = body, cut +} + +// truncPackument is an npm packument with n versions published long ago. +func truncPackument(n int) string { + var versions, times []string + for i := range n { + v := fmt.Sprintf("1.0.%d", i) + versions = append(versions, fmt.Sprintf(`%q:{"name":"pkg","version":%q,"dist":{"tarball":"https://registry.npmjs.org/pkg/-/pkg-%s.tgz"}}`, v, v, v)) + times = append(times, fmt.Sprintf(`%q:"2020-01-01T00:00:00Z"`, v)) + } + return `{"name":"pkg","dist-tags":{"latest":"1.0.0"},"versions":{` + strings.Join(versions, ",") + + `},"time":{` + strings.Join(times, ",") + `}}` +} + +// TestMetadataTruncatedUpstream checks that a document upstream cuts off +// before its Content-Length is neither served nor cached: the cached copy is +// served instead, with and without cooldown. +func TestMetadataTruncatedUpstream(t *testing.T) { + for _, withCooldown := range []bool{false, true} { + t.Run(map[bool]string{false: "no cooldown", true: "cooldown"}[withCooldown], func(t *testing.T) { + u := newCutMetadataUpstream(t, truncPackument(50)) + proxy, db, _, _ := setupTestProxy(t) + proxy.HTTPClient = u.Client() + proxy.CacheMetadata = true + if withCooldown { + proxy.Cooldown = &cooldown.Config{Default: "3d"} + } + handler := NewNPMHandler(proxy, "http://proxy.example", u.URL).Routes() + + first := serve(handler, "/pkg", nil) + if first.Code != http.StatusOK { + t.Fatalf("first request: status %d", first.Code) + } + before, err := db.GetMetadataCache("npm", "pkg") + if err != nil || before == nil { + t.Fatalf("no metadata row after the first request: %v", err) + } + + u.set(truncPackument(51), true) + expireMetadata(t, db, "npm", "pkg") + proxy.SetMetadataRewriteCacheSize(0) + + rec := serve(handler, "/pkg", nil) + if rec.Code != http.StatusOK || rec.Body.String() != first.Body.String() { + t.Errorf("status %d, want 200 with the cached document", rec.Code) + } + after, err := db.GetMetadataCache("npm", "pkg") + if err != nil || after == nil || after.ContentDigest != before.ContentDigest { + t.Error("the cut-off document replaced the cached copy") + } + }) + } +} + +// TestMetadataTruncatedUpstreamUncached checks that a cut-off document with +// nothing cached fails the request and is not cached. +func TestMetadataTruncatedUpstreamUncached(t *testing.T) { + u := newCutMetadataUpstream(t, truncPackument(50)) + u.set(truncPackument(50), true) + proxy, db, _, _ := setupTestProxy(t) + proxy.HTTPClient = u.Client() + proxy.CacheMetadata = true + handler := NewNPMHandler(proxy, "http://proxy.example", u.URL).Routes() + + if rec := serve(handler, "/pkg", nil); rec.Code != http.StatusBadGateway { + t.Errorf("status %d, want 502", rec.Code) + } + if entry, _ := db.GetMetadataCache("npm", "pkg"); entry != nil { + t.Error("cached the cut-off document") + } +} diff --git a/internal/handler/metadata_validators_test.go b/internal/handler/metadata_validators_test.go index e34395d..340e3db 100644 --- a/internal/handler/metadata_validators_test.go +++ b/internal/handler/metadata_validators_test.go @@ -429,8 +429,8 @@ func TestRewrittenMetadataLastModifiedAcrossRestart(t *testing.T) { } // TestRewrittenMetadataValidatorsWithCooldown checks that with cooldown on, -// rewritten metadata keeps an exact ETag but has no Last-Modified: cooldown -// changes the rewrite as versions age in, while upstream stays the same. +// rewritten metadata from the rewrite cache has an ETag and a Last-Modified, +// so clients that only send If-Modified-Since, such as Composer, get 304. func TestRewrittenMetadataValidatorsWithCooldown(t *testing.T) { for _, c := range validatorCases { t.Run(c.ecosystem, func(t *testing.T) { @@ -444,15 +444,34 @@ func TestRewrittenMetadataValidatorsWithCooldown(t *testing.T) { if etag == "" { t.Fatal("no ETag with cooldown on") } - if lm := first.Header().Get("Last-Modified"); lm != "" { - t.Errorf("Last-Modified = %q with cooldown on, want none", lm) + lm := first.Header().Get("Last-Modified") + if lm == "" { + t.Fatal("no Last-Modified with cooldown on") } if rec := serve(handler, c.path, http.Header{"If-None-Match": {etag}}); rec.Code != http.StatusNotModified { t.Errorf("If-None-Match: status %d, want 304", rec.Code) } - future := time.Now().Add(time.Hour).Format(http.TimeFormat) - if rec := serve(handler, c.path, http.Header{"If-Modified-Since": {future}}); rec.Code != http.StatusOK { - t.Errorf("If-Modified-Since: status %d, want 200", rec.Code) + if rec := serve(handler, c.path, http.Header{"If-Modified-Since": {lm}}); rec.Code != http.StatusNotModified { + t.Errorf("If-Modified-Since: status %d, want 304", rec.Code) + } + }) + } +} + +// TestRewrittenMetadataWithCooldownIsGzipped checks that with cooldown on, +// clients accepting gzip get the cached compressed copy. +func TestRewrittenMetadataWithCooldownIsGzipped(t *testing.T) { + for _, c := range validatorCases { + t.Run(c.ecosystem, func(t *testing.T) { + u := newValidatorUpstream(t) + compressibleDocuments(u) + proxy := validatorProxy(t, u, time.Hour) + proxy.Cooldown = &cooldown.Config{Default: "3d"} + handler := c.handler(proxy, u) + for range 2 { + if rec := serve(handler, c.path, http.Header{"Accept-Encoding": {"gzip"}}); rec.Code != http.StatusOK || rec.Header().Get("Content-Encoding") != "gzip" { + t.Errorf("status %d, Content-Encoding %q; want 200 gzip", rec.Code, rec.Header().Get("Content-Encoding")) + } } }) } @@ -481,9 +500,9 @@ func TestRewriteCacheETag(t *testing.T) { exclaim := func(b []byte) ([]byte, error) { return []byte(string(b) + "!"), nil } key := rewriteCacheKey("npm", "http://proxy", "demo", []byte("doc")) - m, err := c.rewrite(t.Context(), key, []byte("doc"), exclaim) - if err != nil || string(m.body) != "doc!" { - t.Fatalf("rewrite = %q, %v", m.body, err) + m, err := c.rewrite(t.Context(), key, []byte("doc"), nil, exclaim) + if err != nil || string(m.content()) != "doc!" { + t.Fatalf("rewrite = %q, %v", m.content(), err) } if want := metadataETag([]byte("doc!")); m.etag != want { t.Errorf("rewrite ETag = %q, want %q", m.etag, want) @@ -685,33 +704,39 @@ func cooldownUpstream(t *testing.T) *validatorUpstream { // TestRewrittenMetadataETagWithCooldownFollowsKeptVersions checks that with // cooldown on, the ETag changes when a version leaves cooldown although the -// upstream document stays the same, and comes back when the same versions do. +// upstream document stays the same, once the cached rewrite has expired, and +// comes back when the same versions do. func TestRewrittenMetadataETagWithCooldownFollowsKeptVersions(t *testing.T) { for _, c := range validatorCases { t.Run(c.ecosystem, func(t *testing.T) { u := cooldownUpstream(t) - proxy := validatorProxy(t, u, time.Hour) + proxy, _, clock := validatorProxyWithDB(t, u, time.Hour) handler := c.handler(proxy, u) proxy.Cooldown = &cooldown.Config{Default: "1d"} etag := serve(handler, c.path, nil).Header().Get("ETag") proxy.Cooldown = &cooldown.Config{Default: "1h"} + if rec := serve(handler, c.path, http.Header{"If-None-Match": {etag}}); rec.Code != http.StatusNotModified { + t.Errorf("within the rewrite's lifetime: status %d, want 304 from the cached rewrite", rec.Code) + } + clock.advance(maxCooldownRewriteTTL) rec := serve(handler, c.path, http.Header{"If-None-Match": {etag}}) if rec.Code != http.StatusOK || rec.Header().Get("ETag") == etag { t.Errorf("after a version left cooldown: status %d, ETag %q; want 200 with a new ETag", rec.Code, rec.Header().Get("ETag")) } proxy.Cooldown = &cooldown.Config{Default: "1d"} + clock.advance(maxCooldownRewriteTTL) expectNotModified(t, serve(handler, c.path, http.Header{"If-None-Match": {etag}}), etag) }) } } // TestRewrittenMetadataETagWithCooldownComesFromInputs checks that with -// cooldown on, the ETag is derived from what fixes the rewrite rather than -// from the rewritten body, when the metadata cache knows the upstream -// digest, and falls back to the body when it does not. +// cooldown on and no rewrite cache, the ETag is derived from what fixes the +// rewrite rather than from the rewritten body, when the metadata cache knows +// the upstream digest, and falls back to the body when it does not. func TestRewrittenMetadataETagWithCooldownComesFromInputs(t *testing.T) { for _, c := range validatorCases { for _, cacheMetadata := range []bool{true, false} { @@ -719,6 +744,7 @@ func TestRewrittenMetadataETagWithCooldownComesFromInputs(t *testing.T) { u := cooldownUpstream(t) proxy := validatorProxy(t, u, time.Hour) proxy.CacheMetadata = cacheMetadata + proxy.SetMetadataRewriteCacheSize(0) proxy.Cooldown = &cooldown.Config{Default: "1d"} handler := c.handler(proxy, u) diff --git a/internal/handler/notfound_ecosystems_test.go b/internal/handler/notfound_ecosystems_test.go index e214124..cc61928 100644 --- a/internal/handler/notfound_ecosystems_test.go +++ b/internal/handler/notfound_ecosystems_test.go @@ -23,6 +23,8 @@ func TestArtifactDownloadUpstreamNotFoundReturns404(t *testing.T) { func(p *Proxy) http.Handler { return NewAPKHandler(p, "http://localhost", nil).Routes() }}, {"arch", "/archlinux/core/os/x86_64/bash-5.2.037-1-x86_64.pkg.tar.zst", func(p *Proxy) http.Handler { return NewArchHandler(p, "http://localhost", nil).Routes() }}, + {"freebsd", "/freebsd/FreeBSD:14:amd64/latest/All/Hashed/zsh-5.9_5~2$3rwh1rgp.pkg", + func(p *Proxy) http.Handler { return NewFreeBSDHandler(p, "http://localhost", nil).Routes() }}, {"nuget", "/v3-flatcontainer/newtonsoft.json/13.0.3/newtonsoft.json.13.0.3.nupkg", func(p *Proxy) http.Handler { return NewNuGetHandler(p, "http://localhost").Routes() }}, {"pypi", "/packages/packages/ab/cd/ef0123456789/requests-2.31.0-py3-none-any.whl", @@ -39,6 +41,8 @@ func TestArtifactDownloadUpstreamNotFoundReturns404(t *testing.T) { func(p *Proxy) http.Handler { return NewGemHandler(p, "http://localhost").Routes() }}, {"hex", "/tarballs/phoenix-1.7.10.tar", func(p *Proxy) http.Handler { return NewHexHandler(p, "http://localhost").Routes() }}, + {"chef", "/api/v1/cookbooks/apt/versions/7.5.22/download", + func(p *Proxy) http.Handler { return NewChefHandler(p, "http://localhost", "http://localhost").Routes() }}, } for _, tt := range tests { diff --git a/internal/handler/npm.go b/internal/handler/npm.go index 3f08c41..95576b5 100644 --- a/internal/handler/npm.go +++ b/internal/handler/npm.go @@ -2,6 +2,7 @@ package handler import ( "bytes" + "context" "errors" "fmt" "io" @@ -12,9 +13,11 @@ import ( "time" "github.com/git-pkgs/integrity" + "github.com/git-pkgs/proxy/internal/database" "github.com/git-pkgs/proxy/internal/jsonscan" "github.com/git-pkgs/proxy/internal/metadata/npm" "github.com/git-pkgs/proxy/internal/retention" + "github.com/git-pkgs/proxy/internal/storage" ) const ( @@ -29,6 +32,15 @@ const ( // npmKeysPath serves the registry signing keys `npm audit signatures` reads. npmKeysPath = "/-/npm/v1/keys" + // npmAttestationsPrefix serves a version's provenance and publish + // attestations, as /-/npm/v1/attestations/{name}@{version}. + npmAttestationsPrefix = "/-/npm/v1/attestations/" + + // npmSearchPath is what `npm search` queries, with the terms in the query + // string. npmPingPath is what `npm ping` checks. + npmSearchPath = "/-/v1/search" + npmPingPath = "/-/ping" + // npmSecurityMaxBody caps the audit payload. Buffering it lets an oversized // body be refused before the upstream request starts. npmSecurityMaxBody = 16 << 20 @@ -80,15 +92,43 @@ func (h *NPMHandler) Routes() http.Handler { return } + // pnpm 12 checks packuments with HEAD before fetching them, so + // packuments also answer HEAD; net/http leaves out the body. + if r.Method == http.MethodHead && isPackumentPath(r.URL.Path) { + h.handlePackageMetadata(w, r) + return + } + if r.Method != http.MethodGet { http.Error(w, "method not allowed", http.StatusMethodNotAllowed) return } - if r.URL.Path == npmKeysPath { + if strings.HasPrefix(r.URL.Path, npmAttestationsPrefix) { + h.handleAttestations(w, r) + return + } + + switch r.URL.Path { + case npmKeysPath: h.proxy.ProxyUpstream(w, r, h.upstreamURL+npmKeysPath, []string{headerAccept, headerAcceptEncoding}) return + case npmSearchPath, npmPingPath: + // Every query has its own answer, so these are relayed uncached + // and keep their query string. + upstreamURL := h.upstreamURL + r.URL.Path + if r.URL.RawQuery != "" { + upstreamURL += "?" + r.URL.RawQuery + } + h.proxy.ProxyUpstream(w, r, upstreamURL, + []string{headerAccept, headerAcceptEncoding}) + return + } + + if strings.HasPrefix(r.URL.Path, npmPackagePrefix) && strings.HasSuffix(r.URL.Path, npmDistTagsSuffix) { + h.handleDistTags(w, r) + return } path := strings.TrimPrefix(r.URL.Path, "/") @@ -104,6 +144,12 @@ func (h *NPMHandler) Routes() http.Handler { }) } +// isPackumentPath reports whether a request path names package metadata +// rather than a tarball or a registry endpoint under /-/. +func isPackumentPath(urlPath string) bool { + return !strings.HasPrefix(urlPath, "/-/") && !strings.Contains(strings.TrimPrefix(urlPath, "/"), "/-/") +} + // handleSecurity relays the npm audit endpoints to upstream. The request body // is the dependency tree being audited, so no two requests share a cache key, // and the response carries no tarball URLs to rewrite. @@ -195,7 +241,7 @@ func (h *NPMHandler) handlePackageMetadata(w http.ResponseWriter, r *http.Reques return } - h.proxy.Logger.Info("npm metadata request", "package", packageName, "path", packagePath) + h.proxy.Logger.Debug("npm metadata request", "package", packageName, "path", packagePath) registryURL, cacheKey := h.sourceFor(packageName) // A version or dist-tag is its own path segment. Escaping the whole path @@ -204,17 +250,7 @@ func (h *NPMHandler) handlePackageMetadata(w http.ResponseWriter, r *http.Reques upstreamURL := registryURL + "/" + registryPath metadataCacheKey := npmMetadataCacheKey(cacheKey, packagePath, packageName) - // Prefer the smaller abbreviated packument format but include application/json - // as a fallback so upstreams that reject the abbreviated type (e.g. JFrog - // Artifactory, which returns 406) can still respond with full metadata. - // When cooldown is enabled we must use full metadata exclusively because the - // abbreviated format omits the "time" map required for version age filtering. - // Operators can also force full metadata so clients that gate on publish - // age (for example Yarn's npmMinimalAgeGate) keep working through the proxy. - accept := npmAcceptDefault - if h.proxy.NPMFullMetadata || (h.proxy.Cooldown != nil && h.proxy.Cooldown.Enabled()) { - accept = contentTypeJSON - } + accept := h.packumentAccept() specifier, versionLookup := npmVersionSpecifier(packagePath, packageName) if h.serveLocalMetadata(w, r, npmMetadataRequest{packageName, specifier, versionLookup, upstreamURL, accept, metadataCacheKey}) { @@ -231,7 +267,15 @@ func (h *NPMHandler) handlePackageMetadata(w http.ResponseWriter, r *http.Reques return } - upstream := h.proxy.fetchMetadataDocument(r.Context(), "npm", metadataCacheKey, upstreamURL, accept) + if !versionLookup && h.serveStreamedPackument(w, r, packageName, upstreamURL, accept, metadataCacheKey) { + return + } + + var validate func([]byte) error + if !versionLookup { + validate = h.packumentValidator() + } + upstream := h.proxy.fetchMetadataDocument(r.Context(), "npm", metadataCacheKey, upstreamURL, accept, validate) if err := upstream.err; err != nil { if errors.Is(err, ErrUpstreamNotFound) { if versionLookup { @@ -264,7 +308,8 @@ func (h *NPMHandler) handlePackageMetadata(w http.ResponseWriter, r *http.Reques JSONError(w, http.StatusNotFound, ErrVersionNotFound.Error()) return } - if len(h.proxy.Denylist.Versions(canonicalPackagePURL("npm", packageName))) != 0 { + if h.proxy.mustFilterMetadata("npm", packageName) { + h.proxy.Logger.Error("failed to filter npm metadata", "package", packageName, "error", err) JSONError(w, http.StatusBadGateway, "failed to filter package metadata") return } @@ -279,11 +324,291 @@ func (h *NPMHandler) handlePackageMetadata(w http.ResponseWriter, r *http.Reques serveRewrittenMetadata(w, r, rewritten) } +// serveStreamedPackument serves a packument rewritten from storage: the +// document is streamed from upstream into storage, then read twice, once to +// collect the time map and version names cooldown and the denylist decide +// on, and once to copy each kept version. registry.npmjs.org writes +// dist-tags before versions and time after them, so one pass can't do it. +// Neither the packument nor its rewrite is held in memory uncompressed, and +// packuments larger than metadata_max_size can be served. +// +// It reports false when it leaves the request to the in-memory rewrite: +// without metadata or rewrite caching, for a document it can't stream, such +// as an abbreviated packument where the full one is required, and when the +// rewrite fails. The document is stored by then, so the in-memory path reads +// it from storage. +func (h *NPMHandler) serveStreamedPackument(w http.ResponseWriter, r *http.Request, packageName, upstreamURL, accept, metadataCacheKey string) bool { + if h.proxy.rewrites == nil { + return false + } + fullRequired := h.packumentValidator() != nil + options := h.npmRewriteOptions(packageName, nil) + var rewritten rewrittenMetadata + err, fetchErr := h.readStoredPackument(r.Context(), upstreamURL, accept, metadataCacheKey, func(entry *database.MetadataCacheEntry) (err error) { + rewritten, err = h.proxy.streamedRewrite(r.Context(), "npm", h.proxyURL, metadataCacheKey, entry, func(open func() (io.ReadCloser, error), out io.Writer) error { + var scan *npm.Scan + err := readStored(open, func(in io.Reader) (err error) { + scan, err = npm.ScanPackument(in) + return err + }) + if err != nil { + return err + } + if fullRequired && scan.Abbreviated() { + return npm.ErrNotStreamable + } + return readStored(open, func(in io.Reader) error { + _, err := npm.RewriteStream(packageName, scan, in, out, options) + return err + }) + }) + return err + }) + switch { + case errors.Is(fetchErr, errInMemory): + return false + case fetchErr != nil: + h.writeFetchError(w, fetchErr) + return true + } + if err != nil { + if r.Context().Err() != nil { + return true // the client left while waiting on a shared rewrite + } + if !errors.Is(err, npm.ErrNotStreamable) { + h.proxy.Logger.Warn("failed to rewrite stored npm metadata, rewriting in memory", + "package", packageName, "error", err) + } + return false + } + serveRewrittenMetadata(w, r, rewritten) + return true +} + +// npmFetchError is a failure to fetch a packument, answered as such rather +// than as a failure to filter it. +type npmFetchError struct{ err error } + +func (e *npmFetchError) Error() string { return e.err.Error() } +func (e *npmFetchError) Unwrap() error { return e.err } + +// writeFetchError answers a request whose packument could not be fetched. +func (h *NPMHandler) writeFetchError(w http.ResponseWriter, err error) { + switch { + case errors.Is(err, ErrUpstreamNotFound): + JSONError(w, http.StatusNotFound, ErrPackageNotFound.Error()) + case writeUpstreamHeld(w, err): + default: + h.proxy.Logger.Error("failed to fetch npm metadata", "error", err) + JSONError(w, http.StatusBadGateway, "failed to fetch from upstream") + } +} + +// errInMemory is returned when a packument has to be read into memory to +// answer the request: metadata is not cached in storage, or the stored +// document can't be read as a stream. +var errInMemory = errors.New("npm packument needs the in-memory path") + +// storedPackument returns the lookup of the packument stored for cacheKey, +// fetching it into storage first when needed. Its err is errInMemory when +// metadata isn't cached in storage, and ErrUpstreamNotFound and upstream +// errors as they come. +// With refresh, a stored copy within its TTL is fetched again rather than +// served. +func (h *NPMHandler) storedPackument(ctx context.Context, packumentURL, accept, cacheKey string, refresh bool) metadataResult { + var gone string + if refresh && h.proxy.DB != nil { + if row, _ := h.proxy.DB.GetMetadataCache("npm", cacheKey); usableStoredMetadata(row) { + gone = row.ContentDigest.String + } + } + res := h.proxy.storedMetadata(ctx, "npm", cacheKey, packumentURL, accept, h.packumentStreamValidator(), gone) + if errors.Is(res.err, errMetadataNotStored) { + res.err = errInMemory + } + return res +} + +// readStoredPackument reads the packument stored for cacheKey with read, +// fetching it into storage first when needed. When the stored copy is gone +// or no longer has the digest its row records, the packument is fetched +// again and read once more. fetchErr is what storedPackument returned when the packument +// couldn't be fetched, and err is what read returned. +func (h *NPMHandler) readStoredPackument(ctx context.Context, packumentURL, accept, cacheKey string, read func(*database.MetadataCacheEntry) error) (err, fetchErr error) { + fetched, err := h.lookupStoredPackument(ctx, packumentURL, accept, cacheKey, false, read) + return err, fetched.err +} + +// lookupStoredPackument implements readStoredPackument. fetched is the +// lookup of the packument read, whose err is set when it couldn't be +// fetched. +func (h *NPMHandler) lookupStoredPackument(ctx context.Context, packumentURL, accept, cacheKey string, refresh bool, read func(*database.MetadataCacheEntry) error) (fetched metadataResult, err error) { + fetched = h.storedPackument(ctx, packumentURL, accept, cacheKey, refresh) + if fetched.err != nil { + return fetched, nil + } + if err = read(fetched.entry); !errors.Is(err, storage.ErrNotFound) && !errors.Is(err, errStoredMetadataChanged) { + return fetched, err + } + h.proxy.Logger.Warn("stored npm metadata is missing or changed, fetching it again", "url", packumentURL, "error", err) + fetched = h.proxy.storedMetadata(ctx, "npm", cacheKey, packumentURL, accept, h.packumentStreamValidator(), fetched.entry.ContentDigest.String) + if errors.Is(fetched.err, errMetadataNotStored) { + fetched.err = errInMemory + } + if fetched.err != nil { + return fetched, nil + } + return fetched, read(fetched.entry) +} + +// packumentStreamValidator is packumentValidator for a packument read from +// storage. +func (h *NPMHandler) packumentStreamValidator() func(io.Reader) error { + if h.packumentValidator() == nil { + return nil + } + return func(r io.Reader) error { + entry, err := npm.LookupVersion(r, "") + if err != nil { + return err + } + if entry.Abbreviated { + return errAbbreviatedPackument + } + return nil + } +} + +// streamedVersionMetadata resolves a version or dist-tag through the +// packument stored in storage, as rewriteNPMVersionFromPackument does in +// memory: one pass collects what cooldown and the denylist decide on, and a +// second finds the version entry. It returns errInMemory when the request +// has to take the in-memory path. +func (h *NPMHandler) streamedVersionMetadata(ctx context.Context, packageName, specifier, packumentURL, accept, cacheKey, metadataCacheKey string) (rewrittenMetadata, error) { + if h.proxy.rewrites == nil { + return rewrittenMetadata{}, errInMemory + } + fullRequired := h.packumentValidator() != nil + options := h.npmRewriteOptions(packageName, nil) + var m rewrittenMetadata + err, fetchErr := h.readStoredPackument(ctx, packumentURL, accept, cacheKey, func(entry *database.MetadataCacheEntry) (err error) { + m, err = h.proxy.streamedRewrite(ctx, "npm", h.proxyURL, metadataCacheKey, entry, func(open func() (io.ReadCloser, error), out io.Writer) error { + var scan *npm.Scan + err := readStored(open, func(in io.Reader) (err error) { + scan, err = npm.ScanPackument(in) + return err + }) + if err != nil { + return err + } + if fullRequired && scan.Abbreviated() { + return npm.ErrNotStreamable + } + return readStored(open, func(in io.Reader) error { + version, err := npm.VersionStream(packageName, specifier, scan, in, options) + if err != nil { + return npmRewriteError(err) + } + _, err = out.Write(version) + return err + }) + }) + return err + }) + switch { + case errors.Is(fetchErr, errInMemory): + return rewrittenMetadata{}, fetchErr + case fetchErr != nil: + return rewrittenMetadata{}, &npmFetchError{fetchErr} + } + switch { + case err == nil, ctx.Err() != nil, errors.Is(err, ErrVersionDenied), errors.Is(err, ErrVersionNotFound): + return m, err + case !errors.Is(err, npm.ErrNotStreamable): + h.proxy.Logger.Warn("failed to read stored npm metadata, reading it in memory", + "package", packageName, "error", err) + } + return rewrittenMetadata{}, errInMemory +} + +// readStored opens a stored document and reads it with read. +func readStored(open func() (io.ReadCloser, error), read func(io.Reader) error) error { + in, err := open() + if err != nil { + return err + } + defer func() { _ = in.Close() }() + return read(in) +} + +// packumentAccept returns the Accept header packuments are requested with. +// It prefers the smaller abbreviated packument format but includes +// application/json as a fallback so upstreams that reject the abbreviated type +// (e.g. JFrog Artifactory, which returns 406) can still respond with full +// metadata. When cooldown is enabled we must use full metadata exclusively +// because the abbreviated format omits the "time" map required for version age +// filtering. Operators can also force full metadata so clients that gate on +// publish age (for example Yarn's npmMinimalAgeGate) keep working through the +// proxy. +// +// Every request for a packument uses it, since they share one cache row: a +// request with another Accept would replace the document the others are +// served with one in the other format. Cooldown profiles share that row too, +// so cooldown in any of them asks for full metadata in all of them. +func (h *NPMHandler) packumentAccept() string { + if h.proxy.NPMFullMetadata || h.proxy.anyCooldownEnabled() { + return contentTypeJSON + } + return npmAcceptDefault +} + +// errAbbreviatedPackument rejects an abbreviated packument where the full one +// is needed. +var errAbbreviatedPackument = errors.New("abbreviated packument where full metadata is required") + +// packumentValidator returns the check a packument must pass to be served or +// cached, or nil when any document will do. Packuments share one cache row +// whatever format they were fetched in, so one cached in abbreviated form +// before cooldown or full metadata was turned on would otherwise still be +// served, and used for the cooldown tarball check, while it stayed fresh or +// as a stale copy when upstream failed. It has no "time" map, so cooldown +// would let every version through. Rejecting it makes the lookup fetch the +// full document instead. +func (h *NPMHandler) packumentValidator() func([]byte) error { + if h.packumentAccept() != contentTypeJSON { + return nil + } + return requireFullPackument +} + +// requireFullPackument rejects an abbreviated packument (see +// npm.Abbreviated). A full document without a time map, as some registries +// serve, is let through as before, and so is anything that is not a JSON +// object, leaving it to the usual handling. +func requireFullPackument(body []byte) error { + if npm.Abbreviated(body) { + return errAbbreviatedPackument + } + return nil +} + // handleFilteredNPMVersionMetadata serves /pkg/ and /pkg/ from the // filtered packument so cooldown and dist-tags match the root metadata response. func (h *NPMHandler) handleFilteredNPMVersionMetadata(w http.ResponseWriter, r *http.Request, packageName, specifier, accept, registryURL, cacheKey, metadataCacheKey string) { _, packumentPath := npmMetadataPath(packageName) - packument, _, err := h.proxy.FetchOrCacheMetadata(r.Context(), "npm", cacheKey, registryURL+"/"+packumentPath, accept) + packumentURL := registryURL + "/" + packumentPath + rewritten, err := h.streamedVersionMetadata(r.Context(), packageName, specifier, packumentURL, accept, cacheKey, metadataCacheKey) + var fetchErr *npmFetchError + switch { + case errors.As(err, &fetchErr): + h.writeFetchError(w, fetchErr.err) + return + case !errors.Is(err, errInMemory): + h.writeVersionMetadata(w, r, packageName, rewritten, err) + return + } + + packument, _, err := h.proxy.fetchOrCacheMetadata(r.Context(), "npm", cacheKey, packumentURL, "", h.packumentValidator(), accept) if err != nil { if errors.Is(err, ErrUpstreamNotFound) { JSONError(w, http.StatusNotFound, ErrPackageNotFound.Error()) @@ -297,10 +622,16 @@ func (h *NPMHandler) handleFilteredNPMVersionMetadata(w http.ResponseWriter, r * return } - rewritten, err := h.proxy.cachedRewrite(r.Context(), "npm", h.proxyURL, metadataCacheKey, packument, "", func(b []byte) ([]byte, []string, error) { + rewritten, err = h.proxy.cachedRewrite(r.Context(), "npm", h.proxyURL, metadataCacheKey, packument, "", func(b []byte) ([]byte, []string, error) { out, err := h.rewriteNPMVersionFromPackument(packageName, specifier, b) return out, nil, err }) + h.writeVersionMetadata(w, r, packageName, rewritten, err) +} + +// writeVersionMetadata answers a version metadata request with its rewrite +// or the error that kept it from being made. +func (h *NPMHandler) writeVersionMetadata(w http.ResponseWriter, r *http.Request, packageName string, rewritten rewrittenMetadata, err error) { if err != nil { if r.Context().Err() != nil { return @@ -313,7 +644,8 @@ func (h *NPMHandler) handleFilteredNPMVersionMetadata(w http.ResponseWriter, r * JSONError(w, http.StatusNotFound, ErrVersionNotFound.Error()) return } - if len(h.proxy.Denylist.Versions(canonicalPackagePURL("npm", packageName))) != 0 { + if h.proxy.mustFilterMetadata("npm", packageName) { + h.proxy.Logger.Error("failed to filter npm metadata", "package", packageName, "error", err) JSONError(w, http.StatusBadGateway, "failed to filter package metadata") return } @@ -324,7 +656,7 @@ func (h *NPMHandler) handleFilteredNPMVersionMetadata(w http.ResponseWriter, r * w.Header().Set(headerContentType, contentTypeJSON) w.WriteHeader(http.StatusOK) - _, _ = w.Write(rewritten.body) + _, _ = w.Write(rewritten.content()) } // npmMetadataCacheKey qualifies routed-package metadata cache entries with the @@ -357,30 +689,45 @@ func (h *NPMHandler) npmVersionMetadataUsesFilteredPackument(packageName string) return false } +// rewriteNPMVersionFromPackument picks one version entry out of an already +// filtered packument and rewrites its tarball URL. func (h *NPMHandler) rewriteNPMVersionFromPackument(packageName, specifier string, packument []byte) ([]byte, error) { out, err := npm.Version(packageName, specifier, packument, h.npmRewriteOptions(packageName, nil)) return out, npmRewriteError(err) } +// rewriteMetadataKeeping rewrites tarball URLs in npm package metadata to +// point at this proxy, filters the versions cooldown and the denylist +// withhold, and reports the versions it kept. See npm.Rewrite. func (h *NPMHandler) rewriteMetadataKeeping(packageName string, body []byte) ([]byte, []string, error) { return h.rewriteMetadataWithLocal(packageName, body, nil) } +// rewriteMetadataWithLocal is rewriteMetadataKeeping that also lists the +// pushed versions in local, in place of any upstream entry with the same +// version. Cooldown and the denylist only filter upstream versions, and +// dist-tags stay as upstream has them. func (h *NPMHandler) rewriteMetadataWithLocal(packageName string, body []byte, local []npmLocalEntry) ([]byte, []string, error) { out, kept, err := npm.Rewrite(packageName, body, h.npmRewriteOptions(packageName, local)) return out, kept, npmRewriteError(err) } +// npmRewriteOptions gathers what a rewrite of packageName's metadata depends +// on from the proxy: its URL, the cooldown and denylist policy, the time +// cooldown is evaluated at, and the pushed versions to list. The callbacks +// log what the rewrite did. func (h *NPMHandler) npmRewriteOptions(packageName string, local []npmLocalEntry) npm.Options { return npm.Options{ ProxyURL: h.proxyURL, - Cooldown: h.proxy.Cooldown, + Cooldown: h.proxy.cooldown(), DeniedVersions: h.proxy.Denylist.Versions(canonicalPackagePURL("npm", packageName)), EvaluatedAt: time.Now(), LocalVersions: local, - OnTarballRewrite: func(version, oldURL, newURL string) { - h.proxy.Logger.Debug("rewrote tarball URL", "package", packageName, "version", version, - "old", oldURL, "new", newURL) + // Logged once per document: a line per version flooded debug logs, + // since packages such as eslint list hundreds of versions and with + // cooldown on every request rewrites the document again. + OnTarballsRewritten: func(count int) { + h.proxy.Logger.Debug("rewrote tarball URLs", "package", packageName, "count", count) }, OnCooldownFilter: func(version, publishedAt string) { h.proxy.Logger.Info("cooldown: filtering npm version", "package", packageName, "version", version, @@ -389,6 +736,8 @@ func (h *NPMHandler) npmRewriteOptions(packageName string, local []npmLocalEntry } } +// npmRewriteError maps the rewrite's errors to the handler's, which the +// routes answer with 403 and 404. func npmRewriteError(err error) error { switch { case errors.Is(err, npm.ErrVersionDenied): @@ -420,7 +769,7 @@ func (h *NPMHandler) handleDownload(w http.ResponseWriter, r *http.Request) { return } - h.proxy.Logger.Info("npm download request", + h.proxy.Logger.Debug("npm download request", "package", packageName, "version", version, "filename", filename) if h.proxy.versionDenied("npm", packageName, version) { @@ -443,12 +792,23 @@ func (h *NPMHandler) handleDownload(w http.ResponseWriter, r *http.Request) { return } registryURL, cacheKey := h.sourceFor(packageName) - metadata := sync.OnceValues(func() ([]byte, error) { - upstreamURL := registryURL + "/" + url.PathEscape(packageName) - body, _, err := h.proxy.FetchOrCacheMetadata(r.Context(), "npm", cacheKey, upstreamURL, contentTypeJSON) - return body, err + metadata := sync.OnceValues(func() (npmVersionData, error) { + return h.versionData(r.Context(), packageName, registryURL+"/"+url.PathEscape(packageName), cacheKey, version) }) - if h.versionInCooldown(packageName, version, metadata) { + inCooldown, err := h.versionInCooldown(packageName, version, metadata) + if err != nil { + if h.proxy.serveCachedDespiteCooldownError(w, r, "npm", packageName, version, h.routes.cacheFilename(packageName, filename), err) { + return + } + if writeUpstreamHeld(w, err) { + return + } + h.proxy.Logger.Warn("cooldown: could not read npm publish time", + "package", packageName, "version", version, "error", err) + JSONError(w, http.StatusBadGateway, "failed to check cooldown") + return + } + if inCooldown { h.proxy.Logger.Info("cooldown: withholding npm tarball", "package", packageName, "version", version) JSONError(w, http.StatusNotFound, ErrVersionNotFound.Error()) @@ -475,40 +835,43 @@ func (h *NPMHandler) handleDownload(w http.ResponseWriter, r *http.Request) { ServeArtifactRequest(w, r, result) } -func (h *NPMHandler) getTarball(r *http.Request, registryURL, packageName, version, filename string, metadata func() ([]byte, error)) (*CacheResult, error) { +func (h *NPMHandler) getTarball(r *http.Request, registryURL, packageName, version, filename string, metadata func() (npmVersionData, error)) (*CacheResult, error) { cacheFilename := h.routes.cacheFilename(packageName, filename) if cached, err := h.proxy.GetCachedArtifact(r.Context(), "npm", packageName, version, cacheFilename); err != nil || cached != nil { return cached, err } - downloadURL := fmt.Sprintf("%s/%s/-/%s", registryURL, escapeNPMDownloadPackage(packageName), url.PathEscape(filename)) - var sri string - body, err := metadata() - if err == nil { - if tarball := npmVersionTarball(body, version); tarball != "" { - downloadURL, err = validateTarballURL(tarball, registryURL) - if err != nil { - return nil, err - } - } - sri = npmVersionIntegrity(body, version) + // The packument says where the tarball is and what it must hash to. + // Without it the tarball could not be verified, and an unverified copy + // would be cached and served to everyone, so the download fails instead. + data, err := metadata() + if err != nil { + return nil, fmt.Errorf("fetching npm metadata to verify tarball: %w", err) } + downloadURL := fmt.Sprintf("%s/%s/-/%s", registryURL, escapeNPMDownloadPackage(packageName), url.PathEscape(filename)) + if tarball := npmEntryTarball(data.entry); tarball != "" { + downloadURL, err = validateTarballURL(tarball, registryURL) + if err != nil { + return nil, err + } + } + sri := npmEntryIntegrity(data.entry) return h.proxy.GetOrFetchArtifactFromURLWithIntegrity(r.Context(), "npm", packageName, version, cacheFilename, downloadURL, sri) } -// npmVersionIntegrity returns the integrity a packument declares for a -// version's tarball: dist.integrity when it is a Subresource Integrity string +// npmEntryIntegrity returns the integrity a version's packument entry +// declares for its tarball: dist.integrity when it is a Subresource Integrity string // the proxy can verify, or else the SHA-1 in dist.shasum, which is all // versions published before integrity existed carry, as "sha1-". It // returns "" when neither is usable, and the tarball is fetched unverified as // before. -func npmVersionIntegrity(body []byte, version string) string { - sri, _, _ := jsonscan.LookupString(body, "versions", version, "dist", "integrity") +func npmEntryIntegrity(entry []byte) string { + sri, _, _ := jsonscan.LookupString(entry, "dist", "integrity") if sri != "" { if _, err := integrity.ParseSRI(sri); err == nil { return sri } } - shasum, _, _ := jsonscan.LookupString(body, "versions", version, "dist", "shasum") + shasum, _, _ := jsonscan.LookupString(entry, "dist", "shasum") return sha1Checksum(shasum) } @@ -516,31 +879,121 @@ func npmVersionIntegrity(body []byte, version string) string { // or "" if it has none. It reads that one value in place rather than decoding // every version, since it runs on each tarball the proxy has not cached yet. func npmVersionTarball(body []byte, version string) string { - tarball, _, _ := jsonscan.LookupString(body, "versions", version, "dist", "tarball") + entry, _ := jsonscan.Lookup(body, "versions", version) + return npmEntryTarball(entry) +} + +// npmEntryTarball is npmVersionTarball for the version's entry. +func npmEntryTarball(entry []byte) string { + tarball, _, _ := jsonscan.LookupString(entry, "dist", "tarball") return tarball } -func validateTarballURL(raw, registryURL string) (string, error) { - tarball, err := url.Parse(raw) +// npmVersionData is what a tarball download reads from the packument: the +// version's entry, nil when it has none, and its publish time from the time +// map, "" when it has none. +type npmVersionData struct { + entry []byte + published string +} + +// versionData reads what a tarball download needs about version from the +// packument: from storage in one pass when metadata is cached there, and +// otherwise from the packument read into memory. +// +// A packument cached within its TTL can predate the version. Under cooldown a +// missing entry would let the version through with no publish time, so the +// packument is fetched again and the version decided on what upstream lists +// now, as the Composer handler does. +func (h *NPMHandler) versionData(ctx context.Context, packageName, packumentURL, cacheKey, version string) (npmVersionData, error) { + data, fromCache, err := h.readVersionData(ctx, packumentURL, cacheKey, version, false) + if err == nil && data.entry == nil && fromCache && h.proxy.cooldownApplies("npm", packageName) { + h.proxy.Logger.Info("cooldown: cached npm metadata lacks version, fetching it again", + "package", packageName, "version", version) + data, _, err = h.readVersionData(ctx, packumentURL, cacheKey, version, true) + } + return data, err +} + +// readVersionData implements versionData. fromCache reports whether the +// packument was a cached copy, within its TTL or served stale; refresh +// fetches it from upstream. +func (h *NPMHandler) readVersionData(ctx context.Context, packumentURL, cacheKey, version string, refresh bool) (data npmVersionData, fromCache bool, err error) { + accept := h.packumentAccept() + var found npm.VersionEntry + fetched, err := h.lookupStoredPackument(ctx, packumentURL, accept, cacheKey, refresh, func(entry *database.MetadataCacheEntry) error { + return readStored(func() (io.ReadCloser, error) { return h.proxy.openStoredMetadata(ctx, entry) }, func(in io.Reader) (err error) { + found, err = npm.LookupVersion(in, version) + return err + }) + }) + fetchErr := fetched.err + switch { + case fetchErr == nil && err == nil && (!found.Abbreviated || h.packumentValidator() == nil): + if refresh && fetched.stale { + return npmVersionData{}, false, errRefetchFailed(fetched) + } + return npmVersionData{entry: found.Entry, published: found.Published}, fetched.fromCache || fetched.stale, nil + case fetchErr == nil && err != nil: + h.proxy.Logger.Warn("failed to read stored npm metadata, reading it in memory", "url", packumentURL, "error", err) + case fetchErr != nil && !errors.Is(fetchErr, errInMemory): + return npmVersionData{}, false, fetchErr + } + + var res metadataResult + if refresh { + res = h.proxy.refreshMetadata(ctx, "npm", cacheKey, packumentURL, accept, "", h.packumentValidator()) + } else { + res = h.proxy.fetchMetadataDocument(ctx, "npm", cacheKey, packumentURL, accept, h.packumentValidator()) + } + if res.err != nil { + return npmVersionData{}, false, res.err + } + if refresh && res.stale { + return npmVersionData{}, false, errRefetchFailed(res) + } + entry, _ := jsonscan.Lookup(res.body, "versions", version) + published, _, err := jsonscan.LookupString(res.body, "time", version) if err != nil { - return "", fmt.Errorf("parsing npm tarball URL: %w", err) + return npmVersionData{}, false, fmt.Errorf("parsing npm metadata: %w", err) + } + return npmVersionData{entry: entry, published: published}, res.fromCache || res.stale, nil +} + +// errRefetchFailed is the error for a refetch that got only the stale copy +// back. That copy is what lacked the version, so it can't decide it. +func errRefetchFailed(res metadataResult) error { + return fmt.Errorf("npm metadata could not be fetched again: %w", res.upstreamErr) +} + +func validateTarballURL(raw, registryURL string) (string, error) { + return validateRegistryURL("tarball", raw, registryURL) +} + +// validateRegistryURL checks that a URL a packument lists for a version's +// file is on the package's registry, under its base path, and returns it. +// what names the file in errors. +func validateRegistryURL(what, raw, registryURL string) (string, error) { + parsed, err := url.Parse(raw) + if err != nil { + return "", fmt.Errorf("parsing npm %s URL: %w", what, err) } upstream, err := url.Parse(registryURL) if err != nil { return "", fmt.Errorf("parsing npm upstream URL: %w", err) } - if tarball.User != nil || tarball.Fragment != "" || - tarball.Scheme != upstream.Scheme || !strings.EqualFold(tarball.Host, upstream.Host) { - return "", errors.New("npm tarball URL does not match upstream registry") + if parsed.User != nil || parsed.Fragment != "" || + parsed.Scheme != upstream.Scheme || !strings.EqualFold(parsed.Host, upstream.Host) { + return "", fmt.Errorf("npm %s URL does not match upstream registry", what) } - if containsPathTraversal(tarball.Path) || strings.Contains(tarball.Path, "\\") { - return "", errors.New("npm tarball URL contains path traversal") + if containsPathTraversal(parsed.Path) || strings.Contains(parsed.Path, "\\") { + return "", fmt.Errorf("npm %s URL contains path traversal", what) } basePath := strings.TrimRight(upstream.Path, "/") - if basePath != "" && !strings.HasPrefix(tarball.Path, basePath+"/") { - return "", errors.New("npm tarball URL is outside upstream base path") + if basePath != "" && !strings.HasPrefix(parsed.Path, basePath+"/") { + return "", fmt.Errorf("npm %s URL is outside upstream base path", what) } - return tarball.String(), nil + return parsed.String(), nil } // versionInCooldown reports whether a version is still inside the cooldown @@ -553,7 +1006,8 @@ func validateTarballURL(raw, registryURL string) (string, error) { // proxy has never seen, persisting the parsed time so the packument is // fetched and parsed at most once per version. A version with no usable // publish time is allowed through, matching how applyCooldownFiltering -// treats it. +// treats it. A packument that can't be fetched or parsed is an error, so a +// failing upstream can't let a version through. // // The versions row is keyed by the plain version PURL, which does not say // which registry the version came from, so routed packages leave it alone: @@ -562,39 +1016,35 @@ func validateTarballURL(raw, registryURL string) (string, error) { // for a private version of the same name, a private time would hold back the // public version, and moving a route to another upstream would keep the old // one's times. -func (h *NPMHandler) versionInCooldown(packageName, version string, metadata func() ([]byte, error)) bool { - if h.proxy.Cooldown == nil || !h.proxy.Cooldown.Enabled() { - return false +func (h *NPMHandler) versionInCooldown(packageName, version string, metadata func() (npmVersionData, error)) (bool, error) { + if !h.proxy.cooldownApplies("npm", packageName) { + return false, nil } _, routed := h.routes.match(packageName) versionPURL := canonicalVersionPURL("npm", packageName, version) if !routed { if ver, err := h.proxy.DB.GetVersionByPURL(versionPURL); err == nil && ver != nil && ver.PublishedAt.Valid { - return !h.proxy.Cooldown.IsAllowed("npm", canonicalPackagePURL("npm", packageName), ver.PublishedAt.Time) + return !h.proxy.cooldown().IsAllowed("npm", canonicalPackagePURL("npm", packageName), ver.PublishedAt.Time), nil } } - body, err := metadata() + data, err := metadata() + if errors.Is(err, ErrUpstreamNotFound) { + return false, nil + } if err != nil { - h.proxy.Logger.Warn("cooldown: could not fetch npm metadata for download check", - "package", packageName, "version", version, "error", err) - return false + return false, err } - published, ok, err := jsonscan.LookupString(body, "time", version) - if err != nil { - h.proxy.Logger.Warn("cooldown: could not parse npm metadata for download check", - "package", packageName, "version", version, "error", err) - return false - } - if !ok { - return false + published := data.published + if published == "" { + return false, nil } publishedAt, err := time.Parse(time.RFC3339, published) if err != nil { - return false + return false, nil } if !routed { @@ -604,7 +1054,7 @@ func (h *NPMHandler) versionInCooldown(packageName, version string, metadata fun } } - return !h.proxy.Cooldown.IsAllowed("npm", canonicalPackagePURL("npm", packageName), publishedAt) + return !h.proxy.cooldown().IsAllowed("npm", canonicalPackagePURL("npm", packageName), publishedAt), nil } // npmMetadataPath returns the package name and the encoded registry path. diff --git a/internal/handler/npm_attestations.go b/internal/handler/npm_attestations.go new file mode 100644 index 0000000..cc84003 --- /dev/null +++ b/internal/handler/npm_attestations.go @@ -0,0 +1,110 @@ +package handler + +import ( + "errors" + "net/http" + "net/url" + "strings" + "sync" + + "github.com/git-pkgs/proxy/internal/jsonscan" +) + +// errNoAttestations answers a request for a version whose packument entry +// lists no attestations. +var errNoAttestations = errors.New("attestations not found") + +// handleAttestations serves /-/npm/v1/attestations/{name}@{version}, which +// `npm audit signatures` reads to verify provenance. Packuments point +// dist.attestations.url here (see npm.AttestationsURL). +func (h *NPMHandler) handleAttestations(w http.ResponseWriter, r *http.Request) { + packageName, version, ok := parseNPMAttestationsPath(strings.TrimPrefix(r.URL.Path, npmAttestationsPrefix)) + if !ok { + JSONError(w, http.StatusBadRequest, "invalid package name") + return + } + + if h.proxy.versionDenied("npm", packageName, version) { + JSONError(w, http.StatusForbidden, ErrVersionDenied.Error()+": "+canonicalVersionPURL("npm", packageName, version)) + return + } + local, err := h.npmLocalEntries(packageName) + if err != nil { + h.proxy.Logger.Error("failed to read pushed npm versions", "package", packageName, "error", err) + JSONError(w, http.StatusInternalServerError, "failed to read pushed versions") + return + } + if _, pushed := findNPMLocalEntry(local, version); pushed || h.proxy.hostedOnly("npm", packageName) { + JSONError(w, http.StatusNotFound, errNoAttestations.Error()) + return + } + + registryURL, cacheKey := h.sourceFor(packageName) + metadata := sync.OnceValues(func() (npmVersionData, error) { + return h.versionData(r.Context(), packageName, registryURL+"/"+url.PathEscape(packageName), cacheKey, version) + }) + + inCooldown, err := h.versionInCooldown(packageName, version, metadata) + if err != nil { + if writeUpstreamHeld(w, err) { + return + } + h.proxy.Logger.Warn("cooldown: could not read npm publish time", + "package", packageName, "version", version, "error", err) + JSONError(w, http.StatusBadGateway, "failed to check cooldown") + return + } + if inCooldown { + JSONError(w, http.StatusNotFound, ErrVersionNotFound.Error()) + return + } + + data, err := metadata() + if err != nil { + if errors.Is(err, ErrUpstreamNotFound) { + JSONError(w, http.StatusNotFound, ErrPackageNotFound.Error()) + return + } + if writeUpstreamHeld(w, err) { + return + } + h.proxy.Logger.Error("failed to fetch npm metadata", "error", err) + JSONError(w, http.StatusBadGateway, "failed to fetch from upstream") + return + } + listed, _, _ := jsonscan.LookupString(data.entry, "dist", "attestations", "url") + if listed == "" { + JSONError(w, http.StatusNotFound, errNoAttestations.Error()) + return + } + upstreamURL, err := validateRegistryURL("attestations", listed, registryURL) + if err != nil { + // Mirrors of npmjs can keep its URLs in packuments. The proxy only + // ever asks the package's own registry. + upstreamURL = registryURL + "/-/npm/v1/attestations/" + url.PathEscape(packageName) + "@" + url.PathEscape(version) + } + + h.proxy.proxyImmutable(w, r, upstreamURL, "npm", cacheKey+"/-/attestations/"+version, contentTypeJSON) +} + +// parseNPMAttestationsPath splits "{name}@{version}" as the attestations +// endpoint takes it, where name may be "@scope/name" with the slash encoded +// or not. It rejects anything that is not one package and one version. +func parseNPMAttestationsPath(spec string) (packageName, version string, ok bool) { + at := strings.LastIndex(spec, "@") + if at <= 0 { + return "", "", false + } + packageName, version = spec[:at], spec[at+1:] + if version == "" || strings.ContainsAny(version, "/\\") || containsPathTraversal(packageName) || containsPathTraversal(version) { + return "", "", false + } + scope, name, scoped := strings.Cut(packageName, "/") + switch { + case scoped: + ok = len(scope) > 1 && scope[0] == '@' && name != "" && !strings.ContainsAny(name, "/@") + default: + ok = !strings.ContainsAny(packageName, "@\\") + } + return packageName, version, ok +} diff --git a/internal/handler/npm_attestations_test.go b/internal/handler/npm_attestations_test.go new file mode 100644 index 0000000..3717eaf --- /dev/null +++ b/internal/handler/npm_attestations_test.go @@ -0,0 +1,191 @@ +package handler + +import ( + "net/http" + "slices" + "strings" + "testing" + "time" + + "github.com/git-pkgs/cooldown" +) + +const testAttestations = `{"attestations":[{"predicateType":"https://slsa.dev/provenance/v1","bundle":{}}]}` + +// attestedPackument returns a packument whose version lists attestations at +// attestationsURL, resolved against the upstream's URL when it starts with +// "/", and was published age ago. +func attestedPackument(name, version, attestationsURL string, age time.Duration) func(string) string { + published := time.Now().Add(-age).UTC().Format(time.RFC3339) + return func(baseURL string) string { + if strings.HasPrefix(attestationsURL, "/") { + attestationsURL = baseURL + attestationsURL + } + dist := `{"tarball":"` + baseURL + "/" + name + `/-/x-` + version + `.tgz"` + if attestationsURL != "" { + dist += `,"attestations":{"url":"` + attestationsURL + `","provenance":{"predicateType":"https://slsa.dev/provenance/v1"}}` + } + dist += "}" + return `{"name":"` + name + `","dist-tags":{"latest":"` + version + `"},` + + `"versions":{"` + version + `":{"version":"` + version + `","dist":` + dist + `}},` + + `"time":{"` + version + `":"` + published + `"}}` + } +} + +func attestationsFile(string) string { return testAttestations } + +func newAttestationsProxy(t *testing.T) *Proxy { + t.Helper() + proxy, _, _, _ := setupTestProxy(t) + proxy.HTTPClient = http.DefaultClient + proxy.CacheMetadata = true + proxy.MetadataTTL = time.Hour + return proxy +} + +func TestNPMAttestationsServedAndCached(t *testing.T) { + upstream := newNPMUpstream(t, map[string]func(string) string{ + "/sigstore": attestedPackument("sigstore", "3.0.0", "/-/npm/v1/attestations/sigstore@3.0.0", 30*24*time.Hour), + "/-/npm/v1/attestations/sigstore@3.0.0": attestationsFile, + }, http.StatusOK) + h := NewNPMHandler(newAttestationsProxy(t), "http://proxy.test", upstream.URL) + + for range 2 { + w := serveNPM(t, h, http.MethodGet, "/-/npm/v1/attestations/sigstore@3.0.0", nil, nil) + if w.Code != http.StatusOK || w.Body.String() != testAttestations { + t.Fatalf("status = %d, body = %s", w.Code, w.Body.String()) + } + } + fetched := 0 + for _, p := range upstream.requested() { + if p == "/-/npm/v1/attestations/sigstore@3.0.0" { + fetched++ + } + } + if fetched != 1 { + t.Errorf("attestations fetched %d times, want once: %v", fetched, upstream.requested()) + } +} + +func TestNPMAttestationsRoutedPackageStaysOnRoute(t *testing.T) { + public := newNPMUpstream(t, map[string]func(string) string{}, http.StatusOK) + private := newNPMUpstream(t, map[string]func(string) string{ + routedNPMPath: attestedPackument("@example/widgets", "1.0.0", "/registry/-/npm/v1/attestations/@example%2fwidgets@1.0.0", 0), + "/registry/-/npm/v1/attestations/@example/widgets@1.0.0": attestationsFile, + }, http.StatusOK) + h := newRoutedNPMHandler(newAttestationsProxy(t), public, private) + + for _, target := range []string{ + "/-/npm/v1/attestations/@example%2fwidgets@1.0.0", + "/-/npm/v1/attestations/@example/widgets@1.0.0", + } { + w := serveNPM(t, h, http.MethodGet, target, nil, nil) + if w.Code != http.StatusOK || w.Body.String() != testAttestations { + t.Errorf("%s: status = %d, body = %s", target, w.Code, w.Body.String()) + } + } + if got := public.requested(); len(got) != 0 { + t.Errorf("default registry was queried for a routed package: %v", got) + } +} + +// TestNPMAttestationsOnlyAskThePackageRegistry checks that an attestations +// URL on another host is not followed: the proxy asks the package's registry +// at its standard path instead. +func TestNPMAttestationsOnlyAskThePackageRegistry(t *testing.T) { + other := newNPMUpstream(t, map[string]func(string) string{"/-/npm/v1/attestations/demo@1.0.0": attestationsFile}, http.StatusOK) + upstream := newNPMUpstream(t, map[string]func(string) string{ + "/demo": attestedPackument("demo", "1.0.0", other.URL+"/-/npm/v1/attestations/demo@1.0.0", 0), + "/-/npm/v1/attestations/demo@1.0.0": attestationsFile, + }, http.StatusOK) + h := NewNPMHandler(newAttestationsProxy(t), "http://proxy.test", upstream.URL) + + w := serveNPM(t, h, http.MethodGet, "/-/npm/v1/attestations/demo@1.0.0", nil, nil) + if w.Code != http.StatusOK { + t.Fatalf("status = %d, body = %s", w.Code, w.Body.String()) + } + if got := other.requested(); len(got) != 0 { + t.Errorf("host named in the packument was queried: %v", got) + } + if !slices.Contains(upstream.requested(), "/-/npm/v1/attestations/demo@1.0.0") { + t.Errorf("registry not asked for attestations: %v", upstream.requested()) + } +} + +func TestNPMAttestationsWithheld(t *testing.T) { + tests := []struct { + name string + packument func(string) string + setup func(t *testing.T, p *Proxy) + wantStatus int + }{ + {"version has none", attestedPackument("demo", "1.0.0", "", 0), nil, http.StatusNotFound}, + {"version in cooldown", attestedPackument("demo", "1.0.0", "/-/npm/v1/attestations/demo@1.0.0", time.Hour), + func(_ *testing.T, p *Proxy) { p.Cooldown = &cooldown.Config{Default: "7d"} }, http.StatusNotFound}, + {"version denied", attestedPackument("demo", "1.0.0", "/-/npm/v1/attestations/demo@1.0.0", 0), + func(t *testing.T, p *Proxy) { setTestDenylist(t, p, "pkg:npm/demo@1.0.0") }, http.StatusForbidden}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + upstream := newNPMUpstream(t, map[string]func(string) string{ + "/demo": tt.packument, + "/-/npm/v1/attestations/demo@1.0.0": attestationsFile, + }, http.StatusOK) + proxy := newAttestationsProxy(t) + if tt.setup != nil { + tt.setup(t, proxy) + } + h := NewNPMHandler(proxy, "http://proxy.test", upstream.URL) + + w := serveNPM(t, h, http.MethodGet, "/-/npm/v1/attestations/demo@1.0.0", nil, nil) + if w.Code != tt.wantStatus { + t.Errorf("status = %d, want %d; body: %s", w.Code, tt.wantStatus, w.Body.String()) + } + if slices.Contains(upstream.requested(), "/-/npm/v1/attestations/demo@1.0.0") { + t.Error("attestations were fetched for a withheld version") + } + }) + } +} + +func TestNPMAttestationsRejectsInvalidPaths(t *testing.T) { + upstream := newNPMUpstream(t, map[string]func(string) string{}, http.StatusOK) + h := NewNPMHandler(newAttestationsProxy(t), "http://proxy.test", upstream.URL) + + for _, target := range []string{ + "/-/npm/v1/attestations/demo", + "/-/npm/v1/attestations/demo@", + "/-/npm/v1/attestations/@demo@1.0.0", + "/-/npm/v1/attestations/@scope/a/b@1.0.0", + "/-/npm/v1/attestations/demo@1.0.0/x", + "/-/npm/v1/attestations/..%2f..%2fetc@1.0.0", + } { + w := serveNPM(t, h, http.MethodGet, target, nil, nil) + if w.Code != http.StatusBadRequest { + t.Errorf("%s: status = %d, want 400", target, w.Code) + } + } + if got := upstream.requested(); len(got) != 0 { + t.Errorf("upstream queried for invalid paths: %v", got) + } +} + +func TestNPMMetadataRewritesAttestationsURL(t *testing.T) { + const attestations = "/registry/-/npm/v1/attestations/@example%2fwidgets@1.0.0" + upstream := newNPMUpstream(t, map[string]func(string) string{ + routedNPMPath: attestedPackument("@example/widgets", "1.0.0", attestations, 0), + routedNPMPath + "/1.0.0": func(baseURL string) string { + return `{"name":"@example/widgets","version":"1.0.0","dist":{"attestations":{"url":"` + baseURL + attestations + + `"},"tarball":"` + baseURL + `/registry/@example/widgets/-/widgets-1.0.0.tgz"}}` + }, + }, http.StatusOK) + h := newRoutedNPMHandler(newAttestationsProxy(t), upstream, upstream) + + for _, target := range []string{"/@example%2fwidgets", "/@example%2fwidgets/1.0.0"} { + w := serveNPM(t, h, http.MethodGet, target, nil, nil) + want := `"url":"http://proxy.test/npm/-/npm/v1/attestations/@example%2Fwidgets@1.0.0"` + if w.Code != http.StatusOK || !strings.Contains(w.Body.String(), want) { + t.Errorf("%s: status %d, attestations URL not rewritten: %s", target, w.Code, w.Body.String()) + } + } +} diff --git a/internal/handler/npm_dist_tags.go b/internal/handler/npm_dist_tags.go new file mode 100644 index 0000000..210b45f --- /dev/null +++ b/internal/handler/npm_dist_tags.go @@ -0,0 +1,115 @@ +package handler + +import ( + "context" + "errors" + "net/http" + "strings" + + "github.com/git-pkgs/proxy/internal/jsonscan" +) + +// npmPackagePrefix and npmDistTagsSuffix frame the path `npm dist-tag ls` +// reads: /-/package/{name}/dist-tags, with a scoped name's slash encoded. +const ( + npmPackagePrefix = "/-/package/" + npmDistTagsSuffix = "/dist-tags" +) + +// handleDistTags answers `npm dist-tag ls` from the dist-tags of the +// packument the proxy serves, not from upstream's, so a tag never names a +// version cooldown or the denylist holds back, and pushed versions and +// package routes count as they do for the packument. Changing tags is not +// supported; Routes answers anything but GET with 405. +func (h *NPMHandler) handleDistTags(w http.ResponseWriter, r *http.Request) { + packageName := strings.TrimSuffix(strings.TrimPrefix(r.URL.Path, npmPackagePrefix), npmDistTagsSuffix) + if !validNPMPackageName(packageName) { + JSONError(w, http.StatusBadRequest, "invalid package name") + return + } + + packument, stale, err := h.servedPackument(r.Context(), packageName) + if err != nil { + if r.Context().Err() != nil { + return + } + if errors.Is(err, ErrUpstreamNotFound) || errors.Is(err, ErrPackageNotFound) { + JSONError(w, http.StatusNotFound, ErrPackageNotFound.Error()) + return + } + if writeUpstreamHeld(w, err) { + return + } + h.proxy.Logger.Error("failed to read npm dist-tags", "package", packageName, "error", err) + JSONError(w, http.StatusBadGateway, "failed to fetch from upstream") + return + } + + tags, err := jsonscan.Lookup(packument, "dist-tags") + if err != nil || len(tags) == 0 || tags[0] != '{' { + tags = []byte("{}") + } + markStale(w, stale) + w.Header().Set(headerContentType, contentTypeJSON) + w.WriteHeader(http.StatusOK) + _, _ = w.Write(tags) +} + +// servedPackument returns the packument of packageName as the proxy serves +// it: from the package's registry or route, filtered by cooldown and the +// denylist, with pushed versions added, or built from the pushed versions +// alone in a hosted-only scope. stale reports a cached copy served because +// upstream failed. +func (h *NPMHandler) servedPackument(ctx context.Context, packageName string) (body []byte, stale bool, err error) { + local, err := h.npmLocalEntries(packageName) + if err != nil { + return nil, false, err + } + if h.proxy.hostedOnly("npm", packageName) { + if len(local) == 0 { + return nil, false, ErrPackageNotFound + } + body, err := localNPMPackument(packageName, local) + return body, false, err + } + + registryURL, cacheKey := h.sourceFor(packageName) + _, registryPath := npmMetadataPath(packageName) + upstream := h.proxy.fetchMetadataDocument(ctx, "npm", cacheKey, registryURL+"/"+registryPath, h.packumentAccept(), h.packumentValidator()) + switch { + case errors.Is(upstream.err, ErrUpstreamNotFound) && len(local) > 0: + body, err := localNPMPackument(packageName, local) + return body, false, err + case upstream.err != nil: + return nil, false, upstream.err + case len(local) > 0: + body, _, err := h.rewriteMetadataWithLocal(packageName, upstream.body, local) + return body, upstream.stale, err + } + + rewritten, err := h.proxy.cachedRewrite(ctx, "npm", h.proxyURL, cacheKey, upstream.body, upstream.digest, func(b []byte) ([]byte, []string, error) { + return h.rewriteMetadataKeeping(packageName, b) + }) + if err != nil { + if h.proxy.mustFilterMetadata("npm", packageName) { + return nil, false, err + } + // The packument route serves upstream's document when the rewrite + // fails and nothing has to be filtered out. + return upstream.body, upstream.stale, nil + } + return rewritten.content(), upstream.stale, nil +} + +// validNPMPackageName reports whether name is a plain or scoped package +// name, without path traversal. +func validNPMPackageName(name string) bool { + if name == "" || containsPathTraversal(name) || strings.ContainsAny(name, "\\") { + return false + } + scope, rest, scoped := strings.Cut(name, "/") + if !scoped { + return !strings.HasPrefix(name, "@") + } + return len(scope) > 1 && scope[0] == '@' && rest != "" && !strings.Contains(rest, "/") +} diff --git a/internal/handler/npm_dist_tags_test.go b/internal/handler/npm_dist_tags_test.go new file mode 100644 index 0000000..a23a1c9 --- /dev/null +++ b/internal/handler/npm_dist_tags_test.go @@ -0,0 +1,136 @@ +package handler + +import ( + "encoding/json" + "net/http" + "testing" + "time" + + "github.com/git-pkgs/cooldown" +) + +// taggedPackument has 1.0.0 published a month ago and 2.0.0 an hour ago, +// tagged latest. +func taggedPackument(name string) func(string) string { + month := time.Now().Add(-30 * 24 * time.Hour).UTC().Format(time.RFC3339) + hour := time.Now().Add(-time.Hour).UTC().Format(time.RFC3339) + return func(baseURL string) string { + return `{"name":"` + name + `","dist-tags":{"latest":"2.0.0","stable":"1.0.0"},"versions":{` + + `"1.0.0":{"version":"1.0.0","dist":{"tarball":"` + baseURL + `/x/-/x-1.0.0.tgz"}},` + + `"2.0.0":{"version":"2.0.0","dist":{"tarball":"` + baseURL + `/x/-/x-2.0.0.tgz"}}},` + + `"time":{"1.0.0":"` + month + `","2.0.0":"` + hour + `"}}` + } +} + +func decodeDistTags(t *testing.T, code int, body []byte) map[string]string { + t.Helper() + if code != http.StatusOK { + t.Fatalf("status = %d, body: %s", code, body) + } + var tags map[string]string + if err := json.Unmarshal(body, &tags); err != nil { + t.Fatalf("dist-tags are not a JSON object: %v: %s", err, body) + } + return tags +} + +func TestNPMDistTags(t *testing.T) { + upstream := newNPMUpstream(t, map[string]func(string) string{"/demo": taggedPackument("demo")}, http.StatusOK) + proxy, _, _, _ := setupTestProxy(t) + proxy.HTTPClient = http.DefaultClient + h := NewNPMHandler(proxy, "http://proxy.test", upstream.URL) + + w := serveNPM(t, h, http.MethodGet, "/-/package/demo/dist-tags", nil, nil) + tags := decodeDistTags(t, w.Code, w.Body.Bytes()) + if tags["latest"] != "2.0.0" || tags["stable"] != "1.0.0" || len(tags) != 2 { + t.Errorf("dist-tags = %v", tags) + } +} + +// TestNPMDistTagsFollowCooldown checks that latest never names a version +// cooldown holds back, as in the packument. +func TestNPMDistTagsFollowCooldown(t *testing.T) { + upstream := newNPMUpstream(t, map[string]func(string) string{"/demo": taggedPackument("demo")}, http.StatusOK) + proxy, _, _, _ := setupTestProxy(t) + proxy.HTTPClient = http.DefaultClient + proxy.Cooldown = &cooldown.Config{Default: "7d"} + h := NewNPMHandler(proxy, "http://proxy.test", upstream.URL) + + w := serveNPM(t, h, http.MethodGet, "/-/package/demo/dist-tags", nil, nil) + if tags := decodeDistTags(t, w.Code, w.Body.Bytes()); tags["latest"] != "1.0.0" { + t.Errorf("dist-tags = %v, want latest 1.0.0", tags) + } +} + +func TestNPMDistTagsRoutedPackage(t *testing.T) { + public := newNPMUpstream(t, map[string]func(string) string{"/@example/widgets": routedTestPackument("9.9.9", "")}, http.StatusOK) + private := newNPMUpstream(t, map[string]func(string) string{routedNPMPath: routedTestPackument("1.0.0", "/registry")}, http.StatusOK) + proxy, _, _, _ := setupTestProxy(t) + proxy.HTTPClient = http.DefaultClient + h := newRoutedNPMHandler(proxy, public, private) + + w := serveNPM(t, h, http.MethodGet, "/-/package/@example%2fwidgets/dist-tags", nil, nil) + if tags := decodeDistTags(t, w.Code, w.Body.Bytes()); tags["latest"] != "1.0.0" { + t.Errorf("dist-tags = %v, want the route's latest 1.0.0", tags) + } + if got := public.requested(); len(got) != 0 { + t.Errorf("default registry was queried for a routed package: %v", got) + } +} + +func TestNPMDistTagsHostedOnlyScope(t *testing.T) { + f := newNPMHostedFixture(t, nil) + f.proxy.HostedNPMScopes = []string{"@acme"} + f.push(t, "@acme/private", "1.10.0", `{"name":"@acme/private","version":"1.10.0"}`) + f.push(t, "@acme/private", "1.9.0", `{"name":"@acme/private","version":"1.9.0"}`) + + rec := f.get(t, "/-/package/@acme%2fprivate/dist-tags") + if tags := decodeDistTags(t, rec.Code, rec.Body.Bytes()); tags["latest"] != "1.10.0" { + t.Errorf("dist-tags = %v, want latest 1.10.0", tags) + } + if rec := f.get(t, "/-/package/@acme%2fother/dist-tags"); rec.Code != http.StatusNotFound { + t.Errorf("unpushed package status = %d, want 404", rec.Code) + } + if *f.upstreamRequests != 0 { + t.Errorf("hosted-only scope sent %d requests upstream", *f.upstreamRequests) + } +} + +func TestNPMDistTagsErrors(t *testing.T) { + upstream := newNPMUpstream(t, map[string]func(string) string{}, http.StatusOK) + proxy, _, _, _ := setupTestProxy(t) + proxy.HTTPClient = http.DefaultClient + h := NewNPMHandler(proxy, "http://proxy.test", upstream.URL) + + tests := []struct { + method, target string + want int + }{ + {http.MethodGet, "/-/package/missing/dist-tags", http.StatusNotFound}, + {http.MethodGet, "/-/package/@scope/dist-tags", http.StatusBadRequest}, + {http.MethodGet, "/-/package/a/b/c/dist-tags", http.StatusBadRequest}, + {http.MethodGet, "/-/package/..%2f..%2fetc/dist-tags", http.StatusBadRequest}, + {http.MethodPut, "/-/package/demo/dist-tags/beta", http.StatusMethodNotAllowed}, + {http.MethodDelete, "/-/package/demo/dist-tags/beta", http.StatusMethodNotAllowed}, + } + for _, tt := range tests { + if w := serveNPM(t, h, tt.method, tt.target, nil, nil); w.Code != tt.want { + t.Errorf("%s %s: status = %d, want %d", tt.method, tt.target, w.Code, tt.want) + } + } + if got := upstream.requested(); len(got) != 1 { + t.Errorf("upstream requests = %v, want only the missing package", got) + } +} + +// TestNPMDistTagsWithPushedVersion checks that a push next to upstream +// versions leaves the tags as upstream has them, as in the packument. +func TestNPMDistTagsWithPushedVersion(t *testing.T) { + f := newNPMHostedFixture(t, map[string]string{"/request": requestPackument}) + f.push(t, "request", "2.88.4", `{"name":"request","version":"2.88.4"}`) + + rec := f.get(t, "/-/package/request/dist-tags") + if tags := decodeDistTags(t, rec.Code, rec.Body.Bytes()); tags["latest"] != "2.88.2" { + t.Errorf("dist-tags = %v, want upstream's latest 2.88.2", tags) + } +} diff --git a/internal/handler/npm_hosted.go b/internal/handler/npm_hosted.go index 276d0e3..77f9227 100644 --- a/internal/handler/npm_hosted.go +++ b/internal/handler/npm_hosted.go @@ -93,7 +93,7 @@ func (h *NPMHandler) serveLocalMetadata(w http.ResponseWriter, r *http.Request, // When the upstream does not know the package, the packument holds only the // pushed versions. func (h *NPMHandler) serveMetadataWithLocal(w http.ResponseWriter, r *http.Request, packageName, upstreamURL, accept, metadataCacheKey string, local []npmLocalEntry) { - upstream := h.proxy.fetchMetadataDocument(r.Context(), "npm", metadataCacheKey, upstreamURL, accept) + upstream := h.proxy.fetchMetadataDocument(r.Context(), "npm", metadataCacheKey, upstreamURL, accept, h.packumentValidator()) var out []byte var err error switch { @@ -118,6 +118,7 @@ func (h *NPMHandler) serveMetadataWithLocal(w http.ResponseWriter, r *http.Reque JSONError(w, http.StatusBadGateway, "failed to rewrite package metadata") return } + markStale(w, upstream.stale) serveRewrittenMetadata(w, r, h.proxy.uncachedRewrite("npm", h.proxyURL, metadataCacheKey, out)) } diff --git a/internal/handler/npm_hosted_test.go b/internal/handler/npm_hosted_test.go index 7102046..083319a 100644 --- a/internal/handler/npm_hosted_test.go +++ b/internal/handler/npm_hosted_test.go @@ -60,11 +60,11 @@ func newNPMHostedFixture(t *testing.T, upstream map[string]string) npmHostedFixt func (f npmHostedFixture) push(t *testing.T, name, version, manifest string) HostedArtifact { t.Helper() - target, err := HostedTargetFor("npm", name, version) + target, err := HostedTargetFor("npm", name, version, "") if err != nil { t.Fatalf("HostedTargetFor: %v", err) } - pushed, err := f.proxy.PushLocalArtifact(context.Background(), "npm", target, bytes.NewReader(npmTarball(manifest)), "") + pushed, err := f.proxy.PushLocalArtifact(context.Background(), "npm", target, bytes.NewReader(npmTarball(manifest)), "", "") if err != nil { t.Fatalf("PushLocalArtifact: %v", err) } @@ -229,6 +229,24 @@ func TestNPMMetadataIgnoresPushesWhenHostedDisabled(t *testing.T) { } } +// With hosted packages disabled, a pushed archive is not served ahead of the +// upstream, but it is still never replaced by the upstream copy: the +// download is answered from its stored record like any cached archive. +func TestNPMDownloadWithHostedDisabledKeepsPush(t *testing.T) { + f := newNPMHostedFixture(t, map[string]string{"/request": requestPackument}) + manifest := `{"name":"request","version":"2.88.3"}` + f.push(t, "request", "2.88.3", manifest) + f.proxy.HostedEnabled = false + + rec := f.get(t, "/request/-/request-2.88.3.tgz") + if rec.Code != http.StatusOK || rec.Body.String() != string(npmTarball(manifest)) { + t.Errorf("download status = %d, want 200 and the pushed tarball", rec.Code) + } + if f.fetcher.fetchCalled { + t.Error("the upstream tarball was fetched for a pushed version") + } +} + func TestNPMDownloadOfPushedPackageWithCooldown(t *testing.T) { f := newNPMHostedFixture(t, nil) f.proxy.Cooldown = &cooldown.Config{Default: "7d"} diff --git a/internal/handler/npm_packument_accept_test.go b/internal/handler/npm_packument_accept_test.go new file mode 100644 index 0000000..07f4e63 --- /dev/null +++ b/internal/handler/npm_packument_accept_test.go @@ -0,0 +1,260 @@ +package handler + +import ( + "encoding/json" + "fmt" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/git-pkgs/cooldown" + "github.com/git-pkgs/registries/fetch" +) + +// TestNPMTarballKeepsCachedPackumentFormat checks that a tarball download +// revalidates the packument in the format the metadata route cached it in, +// rather than replacing the abbreviated document every client is served with +// the full one. +func TestNPMTarballKeepsCachedPackumentFormat(t *testing.T) { + const abbreviated = "application/vnd.npm.install-v1+json" + var ( + mu sync.Mutex + accepts []string + ) + var upstream *httptest.Server + upstream = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + accept := r.Header.Get("Accept") + mu.Lock() + accepts = append(accepts, accept) + mu.Unlock() + contentType, etag := contentTypeJSON, `"full"` + if strings.HasPrefix(accept, abbreviated) { + contentType, etag = abbreviated, `"abbreviated"` + } + w.Header().Set(headerETag, etag) + if r.Header.Get("If-None-Match") == etag { + w.WriteHeader(http.StatusNotModified) + return + } + w.Header().Set(headerContentType, contentType) + _, _ = fmt.Fprintf(w, `{"name":"demo","versions":{"1.0.0":{"name":"demo","version":"1.0.0","dist":{"tarball":%q}}}}`, + upstream.URL+"/demo/-/demo-1.0.0.tgz") + })) + t.Cleanup(upstream.Close) + + proxy, db, _, artifactFetcher := setupTestProxy(t) + proxy.CacheMetadata = true + proxy.MetadataTTL = time.Nanosecond // the tarball request revalidates + proxy.HTTPClient = upstream.Client() + artifactFetcher.artifact = &fetch.Artifact{Body: io.NopCloser(strings.NewReader("package")), ContentType: "application/gzip"} + h := NewNPMHandler(proxy, "http://proxy.test", upstream.URL) + + if w := serveNPM(t, h, http.MethodGet, "/demo", nil, nil); w.Code != http.StatusOK { + t.Fatalf("metadata: status %d: %s", w.Code, w.Body.String()) + } + if w := serveNPM(t, h, http.MethodGet, "/demo/-/demo-1.0.0.tgz", nil, nil); w.Code != http.StatusOK { + t.Fatalf("tarball: status %d: %s", w.Code, w.Body.String()) + } + + mu.Lock() + defer mu.Unlock() + if len(accepts) != 2 { + t.Fatalf("upstream packument requests = %d (%q), want 2", len(accepts), accepts) + } + for _, accept := range accepts { + if accept != npmAcceptDefault { + t.Errorf("packument requested with Accept %q, want %q", accept, npmAcceptDefault) + } + } + entry, err := db.GetMetadataCache("npm", "demo") + if err != nil || entry == nil { + t.Fatalf("cache row: %v, %v", entry, err) + } + if entry.ContentType.String != abbreviated { + t.Errorf("cached packument Content-Type = %q, want %q", entry.ContentType.String, abbreviated) + } +} + +// abbreviatedThenFullRegistry serves a packument with a 2.0.0 published an +// hour ago and a 1.0.0 published a month ago. The abbreviated form, like +// registry.npmjs.org's, has no time map. fail makes requests for the full +// document fail. +func abbreviatedThenFullRegistry(t *testing.T, fail *atomic.Bool, fullRequests *atomic.Int64) *httptest.Server { + t.Helper() + const abbreviated = "application/vnd.npm.install-v1+json" + var upstream *httptest.Server + upstream = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/demo" { + w.WriteHeader(http.StatusNotFound) + return + } + versions := fmt.Sprintf(`{"1.0.0":{"name":"demo","version":"1.0.0","dist":{"tarball":%q}},"2.0.0":{"name":"demo","version":"2.0.0","dist":{"tarball":%q}}}`, + upstream.URL+"/demo/-/demo-1.0.0.tgz", upstream.URL+"/demo/-/demo-2.0.0.tgz") + if strings.HasPrefix(r.Header.Get("Accept"), abbreviated) { + w.Header().Set(headerContentType, abbreviated) + _, _ = fmt.Fprintf(w, `{"name":"demo","modified":%q,"dist-tags":{"latest":"2.0.0"},"versions":%s}`, + time.Now().Format(time.RFC3339), versions) + return + } + fullRequests.Add(1) + if fail.Load() { + w.WriteHeader(http.StatusServiceUnavailable) + return + } + w.Header().Set(headerContentType, contentTypeJSON) + _, _ = fmt.Fprintf(w, `{"name":"demo","dist-tags":{"latest":"2.0.0"},"time":{"1.0.0":%q,"2.0.0":%q},"versions":%s}`, + time.Now().Add(-30*24*time.Hour).Format(time.RFC3339), time.Now().Add(-time.Hour).Format(time.RFC3339), versions) + })) + t.Cleanup(upstream.Close) + return upstream +} + +// seedAbbreviatedPackument caches the abbreviated packument for demo through +// the metadata route while cooldown is off, then turns cooldown on. +func seedAbbreviatedPackument(t *testing.T, upstream *httptest.Server) *NPMHandler { + t.Helper() + proxy, db, _, artifactFetcher := setupTestProxy(t) + proxy.CacheMetadata = true + proxy.MetadataTTL = time.Hour + proxy.HTTPClient = upstream.Client() + artifactFetcher.artifact = &fetch.Artifact{Body: io.NopCloser(strings.NewReader("package")), ContentType: "application/gzip"} + h := NewNPMHandler(proxy, "http://proxy.test", upstream.URL) + + if w := serveNPM(t, h, http.MethodGet, "/demo", nil, nil); w.Code != http.StatusOK { + t.Fatalf("seeding metadata: status %d: %s", w.Code, w.Body.String()) + } + entry, err := db.GetMetadataCache("npm", "demo") + if err != nil || entry == nil || entry.ContentType.String != "application/vnd.npm.install-v1+json" { + t.Fatalf("expected an abbreviated packument in the cache, got %+v (%v)", entry, err) + } + + proxy.Cooldown = &cooldown.Config{Default: "7d"} + return h +} + +// A packument cached in abbreviated form before cooldown was turned on has +// no publish times, so cooldown could not filter anything while it stayed +// fresh. With cooldown on it must be refetched in full. +func TestNPMCooldownRefetchesCachedAbbreviatedPackument(t *testing.T) { + var fail atomic.Bool + var fullRequests atomic.Int64 + upstream := abbreviatedThenFullRegistry(t, &fail, &fullRequests) + h := seedAbbreviatedPackument(t, upstream) + + w := serveNPM(t, h, http.MethodGet, "/demo", nil, nil) + if w.Code != http.StatusOK { + t.Fatalf("metadata: status %d: %s", w.Code, w.Body.String()) + } + var doc struct { + DistTags map[string]string `json:"dist-tags"` + Versions map[string]json.RawMessage `json:"versions"` + } + if err := json.Unmarshal(w.Body.Bytes(), &doc); err != nil { + t.Fatalf("decoding metadata: %v", err) + } + if _, ok := doc.Versions["2.0.0"]; ok { + t.Error("version 2.0.0, published an hour ago, was not filtered by cooldown") + } + if _, ok := doc.Versions["1.0.0"]; !ok { + t.Error("version 1.0.0 missing") + } + if doc.DistTags["latest"] != "1.0.0" { + t.Errorf("dist-tags.latest = %q, want 1.0.0", doc.DistTags["latest"]) + } + if fullRequests.Load() == 0 { + t.Error("full packument was never fetched from upstream") + } + + if w := serveNPM(t, h, http.MethodGet, "/demo/-/demo-2.0.0.tgz", nil, nil); w.Code != http.StatusNotFound { + t.Errorf("tarball 2.0.0: status %d, want %d (withheld by cooldown)", w.Code, http.StatusNotFound) + } +} + +// The tarball check alone must not trust the abbreviated packument either. +func TestNPMCooldownTarballRefetchesCachedAbbreviatedPackument(t *testing.T) { + var fail atomic.Bool + var fullRequests atomic.Int64 + upstream := abbreviatedThenFullRegistry(t, &fail, &fullRequests) + h := seedAbbreviatedPackument(t, upstream) + + if w := serveNPM(t, h, http.MethodGet, "/demo/-/demo-2.0.0.tgz", nil, nil); w.Code != http.StatusNotFound { + t.Errorf("tarball 2.0.0: status %d, want %d (withheld by cooldown)", w.Code, http.StatusNotFound) + } + if fullRequests.Load() == 0 { + t.Error("full packument was never fetched from upstream") + } +} + +// When upstream cannot supply the full packument, the abbreviated one must not +// stand in for it as a stale copy: it would let every version through. +func TestNPMCooldownSkipsAbbreviatedStaleFallback(t *testing.T) { + var fail atomic.Bool + var fullRequests atomic.Int64 + upstream := abbreviatedThenFullRegistry(t, &fail, &fullRequests) + h := seedAbbreviatedPackument(t, upstream) + h.proxy.MetadataTTL = time.Nanosecond // force a refetch + fail.Store(true) + + w := serveNPM(t, h, http.MethodGet, "/demo", nil, nil) + if w.Code != http.StatusBadGateway { + t.Errorf("metadata: status %d, want %d; body: %s", w.Code, http.StatusBadGateway, w.Body.String()) + } + if strings.Contains(w.Body.String(), "2.0.0") { + t.Errorf("served the abbreviated packument as a stale copy: %s", w.Body.String()) + } +} + +// Cooldown profiles share a packument's cache row with the unprefixed URLs. +// With cooldown on for only some of them, the others must not replace the +// full packument with the abbreviated one: the next request under cooldown +// would fetch it again, and have no stale copy when upstream fails. +func TestNPMCooldownProfilesShareFullPackument(t *testing.T) { + for _, tc := range []struct{ name, global, profile string }{ + {"cooldown in the profile", "0", "7d"}, + {"cooldown in the global policy", "7d", "0"}, + } { + t.Run(tc.name, func(t *testing.T) { + var fail atomic.Bool + var fullRequests atomic.Int64 + upstream := abbreviatedThenFullRegistry(t, &fail, &fullRequests) + proxy, db, _, _ := setupTestProxy(t) + proxy.CacheMetadata = true + proxy.MetadataTTL = time.Nanosecond // every request revalidates + proxy.HTTPClient = upstream.Client() + proxy.Cooldown = profilePolicy(t, tc.global) + global := NewNPMHandler(proxy, "http://proxy.test", upstream.URL) + profile := NewNPMHandler(proxy.WithCooldown(profilePolicy(t, tc.profile), 0), "http://proxy.test/cooldown/p", upstream.URL) + filtered, unfiltered := profile, global + if tc.global != "0" { + filtered, unfiltered = global, profile + } + + for _, h := range []*NPMHandler{filtered, unfiltered} { + if w := serveNPM(t, h, http.MethodGet, "/demo", nil, nil); w.Code != http.StatusOK { + t.Fatalf("metadata: status %d: %s", w.Code, w.Body.String()) + } + } + entry, err := db.GetMetadataCache("npm", "demo") + if err != nil || entry == nil { + t.Fatalf("cache row: %v, %v", entry, err) + } + if entry.ContentType.String != contentTypeJSON { + t.Errorf("cached packument Content-Type = %q, want %q", entry.ContentType.String, contentTypeJSON) + } + + fail.Store(true) + w := serveNPM(t, filtered, http.MethodGet, "/demo", nil, nil) + if w.Code != http.StatusOK { + t.Fatalf("metadata while upstream fails: status %d, want the stale full packument", w.Code) + } + if strings.Contains(w.Body.String(), "demo-2.0.0.tgz") { + t.Errorf("stale packument lists a version in cooldown: %s", w.Body.String()) + } + }) + } +} diff --git a/internal/handler/npm_portable_test.go b/internal/handler/npm_portable_test.go index f5b7965..d0bb193 100644 --- a/internal/handler/npm_portable_test.go +++ b/internal/handler/npm_portable_test.go @@ -3,6 +3,7 @@ package handler import ( "bytes" "encoding/json" + "fmt" "io" "log/slog" "net/http" @@ -28,8 +29,7 @@ func TestNPMMetadataLogsPolicyAndURLChanges(t *testing.T) { } want := map[string]map[string]string{ "cooldown: filtering npm version": {"level": "INFO", "package": "@example/widgets", "version": "3.0.0", "published": "2099-01-01T00:00:00Z"}, - "rewrote tarball URL": {"level": "DEBUG", "package": "@example/widgets", "version": "1.0.0", - "old": "https://registry.npmjs.org/@example/widgets/-/widgets-1.0.0.tgz", "new": "http://proxy.local/npm/@example%2Fwidgets/-/widgets-1.0.0.tgz"}, + "rewrote tarball URLs": {"level": "DEBUG", "package": "@example/widgets", "count": "1"}, } decoder := json.NewDecoder(&logs) for { @@ -45,7 +45,7 @@ func TestNPMMetadataLogsPolicyAndURLChanges(t *testing.T) { continue } for key, value := range fields { - if record[key] != value { + if fmt.Sprint(record[key]) != value { t.Errorf("%s: %s = %v, want %q", message, key, record[key], value) } } diff --git a/internal/handler/npm_rewrite_bench_test.go b/internal/handler/npm_rewrite_bench_test.go index 86552db..cf8b895 100644 --- a/internal/handler/npm_rewrite_bench_test.go +++ b/internal/handler/npm_rewrite_bench_test.go @@ -1,44 +1,13 @@ package handler import ( - "fmt" - "strings" "testing" + + "github.com/git-pkgs/proxy/internal/metadata/npm/npmbench" ) -// benchPackument builds a full packument shaped like a large real one: -// thousands of versions, each with dependencies, scripts and a readme. -func benchPackument(versions int) []byte { - var b strings.Builder - readme := strings.Repeat("Some documentation text. ", 160) - b.WriteString(`{"_id":"big","name":"big","dist-tags":{"latest":"1.0.` + fmt.Sprint(versions-1) + `"},"versions":{`) - for i := range versions { - if i > 0 { - b.WriteByte(',') - } - v := fmt.Sprintf("1.0.%d", i) - fmt.Fprintf(&b, `%q:{"name":"big","version":%q,"description":"A big package","main":"index.js",`+ - `"scripts":{"test":"node test.js","build":"tsc -p ."},"dependencies":{`, v, v) - for d := range 25 { - if d > 0 { - b.WriteByte(',') - } - fmt.Fprintf(&b, `"dep-%d":"^%d.0.0"`, d, d) - } - fmt.Fprintf(&b, `},"readme":%q,"dist":{"shasum":"0123456789abcdef0123456789abcdef01234567",`+ - `"integrity":"sha512-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA==",`+ - `"tarball":"https://registry.npmjs.org/big/-/big-%s.tgz"}}`, readme, v) - } - b.WriteString(`},"time":{"created":"2015-01-01T00:00:00.000Z"`) - for i := range versions { - fmt.Fprintf(&b, `,"1.0.%d":"2016-01-01T00:00:00.000Z"`, i) - } - b.WriteString(`}}`) - return []byte(b.String()) -} - func BenchmarkNPMRewriteMetadata(b *testing.B) { - body := benchPackument(5000) + body := npmbench.Packument(5000) h := &NPMHandler{proxy: testProxy(), proxyURL: "http://proxy.example"} b.SetBytes(int64(len(body))) b.ReportAllocs() @@ -50,7 +19,7 @@ func BenchmarkNPMRewriteMetadata(b *testing.B) { } func BenchmarkNPMVersionTarball(b *testing.B) { - body := benchPackument(5000) + body := npmbench.Packument(5000) b.SetBytes(int64(len(body))) b.ReportAllocs() for b.Loop() { diff --git a/internal/handler/npm_rewrite_test.go b/internal/handler/npm_rewrite_test.go index f05646d..9b8e35b 100644 --- a/internal/handler/npm_rewrite_test.go +++ b/internal/handler/npm_rewrite_test.go @@ -10,6 +10,8 @@ import ( "time" "github.com/git-pkgs/cooldown" + "github.com/git-pkgs/proxy/internal/metrics" + "github.com/prometheus/client_golang/prometheus/testutil" ) // TestMetadataServesRewriteWithoutReadingStorage checks that a repeat @@ -92,7 +94,7 @@ func TestNPMStoredRewriteSkippedWhenStale(t *testing.T) { body := []byte(`{}`) proxy.cacheMetadataBlob(t.Context(), "npm", "demo", metadataStoragePath("npm", "demo"), &upstreamMetadata{body: body}) key := rewriteCacheKey("npm", "http://proxy", "demo", body) - if _, err := proxy.rewrites.rewrite(t.Context(), key, body, func(b []byte) ([]byte, error) { return b, nil }); err != nil { + if _, err := proxy.rewrites.rewrite(t.Context(), key, body, nil, func(b []byte) ([]byte, error) { return b, nil }); err != nil { t.Fatal(err) } if _, ok := proxy.storedRewrite("npm", "demo", "http://proxy", "demo"); !ok { @@ -111,7 +113,47 @@ func TestNPMStoredRewriteSkippedWhenStale(t *testing.T) { proxy.Cooldown = &cooldown.Config{Default: "3d"} entry.FetchedAt.Time = time.Now() _ = db.UpsertMetadataCache(entry) - if _, ok := proxy.storedRewrite("npm", "demo", "http://proxy", "demo"); ok { - t.Error("cooldown on: expected no stored rewrite") + if _, ok := proxy.storedRewrite("npm", "demo", "http://proxy", "demo"); !ok { + t.Error("cooldown on, fresh row: expected the stored rewrite") + } +} + +// TestNPMStoredRewriteRecordsMetadataHit checks the digest fast path counts as +// a metadata cache hit with the bytes it serves, never as an artifact hit. +func TestNPMStoredRewriteRecordsMetadataHit(t *testing.T) { + proxy, _, _, _ := setupTestProxy(t) + proxy.CacheMetadata = true + proxy.MetadataTTL = time.Hour + proxy.SetMetadataRewriteCacheSize(1 << 20) + + body := []byte(`{"name":"demo"}`) + proxy.cacheMetadataBlob(t.Context(), "npm", "hit-demo", metadataStoragePath("npm", "hit-demo"), &upstreamMetadata{body: body}) + key := rewriteCacheKey("npm", "http://proxy", "hit-demo", body) + if _, err := proxy.rewrites.rewrite(t.Context(), key, body, nil, func(b []byte) ([]byte, error) { return b, nil }); err != nil { + t.Fatal(err) + } + + metadataHits := func() float64 { + return testutil.ToFloat64(metrics.CacheHits.WithLabelValues("npm", metrics.CacheKindMetadata)) + } + artifactHits := func() float64 { + return testutil.ToFloat64(metrics.CacheHits.WithLabelValues("npm", metrics.CacheKindArtifact)) + } + served := func() float64 { return testutil.ToFloat64(metrics.MetadataServedBytes.WithLabelValues("npm")) } + metadataBefore, artifactBefore, servedBefore := metadataHits(), artifactHits(), served() + + m, ok := proxy.storedRewrite("npm", "hit-demo", "http://proxy", "hit-demo") + if !ok { + t.Fatal("expected a stored rewrite") + } + + if diff := metadataHits() - metadataBefore; diff != 1 { + t.Errorf("metadata hits delta = %.0f, want 1", diff) + } + if diff := artifactHits() - artifactBefore; diff != 0 { + t.Errorf("artifact hits delta = %.0f, want 0", diff) + } + if diff := served() - servedBefore; diff != float64(len(m.content())) { + t.Errorf("metadata served bytes delta = %.0f, want %d", diff, len(m.content())) } } diff --git a/internal/handler/npm_routes_test.go b/internal/handler/npm_routes_test.go index a2ffb38..56fc952 100644 --- a/internal/handler/npm_routes_test.go +++ b/internal/handler/npm_routes_test.go @@ -190,10 +190,15 @@ func TestNPMRoutedDownloadWithoutMetadataStaysOnRoute(t *testing.T) { } h := newRoutedNPMHandler(proxy, public, private) - serveNPM(t, h, http.MethodGet, "/@example/widgets/-/widgets-1.0.0.tgz", nil, nil) + w := serveNPM(t, h, http.MethodGet, "/@example/widgets/-/widgets-1.0.0.tgz", nil, nil) - if !strings.HasPrefix(artifactFetcher.fetchedURL, private.URL+"/registry/") { - t.Errorf("fetched URL = %q, want one on the route %q", artifactFetcher.fetchedURL, private.URL+"/registry/") + // Without the route's metadata the tarball can't be verified, so it is + // not fetched at all, and in particular not from the default registry. + if w.Code != http.StatusBadGateway { + t.Errorf("status = %d, want 502", w.Code) + } + if artifactFetcher.fetchedURL != "" { + t.Errorf("fetched URL = %q, want none", artifactFetcher.fetchedURL) } } diff --git a/internal/handler/npm_stream_harden_test.go b/internal/handler/npm_stream_harden_test.go new file mode 100644 index 0000000..0cebf0a --- /dev/null +++ b/internal/handler/npm_stream_harden_test.go @@ -0,0 +1,238 @@ +package handler + +import ( + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + "time" +) + +// bigMetadataFiles returns a copy of what is in storage under the metadata path +// of big, staged copies included. +func bigMetadataFiles(store *mockStorage) map[string]string { + store.mu.Lock() + defer store.mu.Unlock() + files := map[string]string{} + for path, b := range store.files { + if strings.HasPrefix(path, metadataStoragePath("npm", "big")) { + files[path] = string(b) + } + } + return files +} + +// TestNPMStreamedPackumentBlobCorrupt checks that a stored copy whose bytes +// no longer match the digest of its row, within its TTL, is fetched again +// rather than failing the request, also above metadata_max_size. +func TestNPMStreamedPackumentBlobCorrupt(t *testing.T) { + body := bigPackument(400) + u := newStreamUpstream(t, body) + proxy, store, handler := streamProxy(t, u) + proxy.MetadataMaxSize = int64(len(body) / 4) + decodeStreamed(t, serve(handler, "/big", nil)) + + path := metadataStoragePath("npm", "big") + store.mu.Lock() + store.files[path] = []byte(strings.Replace(body, "1.0.5", "1.0.X", 1)) + store.mu.Unlock() + proxy.SetMetadataRewriteCacheSize(64 << 20) + + if doc := decodeStreamed(t, serve(handler, "/big", nil)); len(doc.Versions) != 400 { + t.Errorf("served %d versions, want 400", len(doc.Versions)) + } + if got := bigMetadataFiles(store)[path]; got != body { + t.Error("the corrupt copy was not replaced") + } +} + +// TestNPMStreamedPackumentTruncated checks that a document upstream cuts +// off halfway neither replaces the stored copy, which is served instead, +// nor leaves anything behind, with and without cooldown. +func TestNPMStreamedPackumentTruncated(t *testing.T) { + for _, withCooldown := range []bool{true, false} { + t.Run(map[bool]string{true: "cooldown", false: "no cooldown"}[withCooldown], func(t *testing.T) { + body := bigPackument(400) + u := newStreamUpstream(t, body) + proxy, store, handler := streamProxy(t, u) + if !withCooldown { + proxy.Cooldown = nil + } + proxy.MetadataMaxSize = int64(len(body) / 4) + want := len(decodeStreamed(t, serve(handler, "/big", nil)).Versions) + before := bigMetadataFiles(store) + + u.replace(bigPackument(401), `"v2"`) + u.truncate.Store(true) + proxy.MetadataTTL = time.Nanosecond + proxy.SetMetadataRewriteCacheSize(64 << 20) + + if doc := decodeStreamed(t, serve(handler, "/big", nil)); len(doc.Versions) != want { + t.Errorf("served %d versions, want the stored %d", len(doc.Versions), want) + } + after := bigMetadataFiles(store) + if len(after) != len(before) { + t.Errorf("storage holds %d files, %d before", len(after), len(before)) + } + for path, b := range before { + if after[path] != b { + t.Errorf("%s was changed", path) + } + } + }) + } +} + +// TestNPMStreamedPackumentTruncatedUncached checks that a document upstream +// cuts off halfway fails the request and is not kept. +func TestNPMStreamedPackumentTruncatedUncached(t *testing.T) { + body := bigPackument(400) + u := newStreamUpstream(t, body) + proxy, store, handler := streamProxy(t, u) + proxy.Cooldown = nil + proxy.MetadataMaxSize = int64(len(body) / 4) + u.truncate.Store(true) + + if rec := serve(handler, "/big", nil); rec.Code != http.StatusBadGateway { + t.Errorf("status %d, want 502", rec.Code) + } + if files := bigMetadataFiles(store); len(files) != 0 { + t.Errorf("left %d files in storage", len(files)) + } + if entry, _ := proxy.DB.GetMetadataCache("npm", "big"); entry != nil { + t.Error("left a metadata cache row") + } +} + +// TestNPMStreamedPackumentUncachedErrors checks the answers to upstream +// failures with nothing cached. +func TestNPMStreamedPackumentUncachedErrors(t *testing.T) { + for _, tt := range []struct { + name string + set func(*streamUpstream) + want int + }{ + {"not found", func(u *streamUpstream) { u.gone.Store(true) }, http.StatusNotFound}, + {"upstream down", func(u *streamUpstream) { u.fail.Store(true) }, http.StatusBadGateway}, + } { + t.Run(tt.name, func(t *testing.T) { + u := newStreamUpstream(t, bigPackument(10)) + _, store, handler := streamProxy(t, u) + tt.set(u) + if rec := serve(handler, "/big", nil); rec.Code != tt.want { + t.Errorf("status %d, want %d", rec.Code, tt.want) + } + if files := bigMetadataFiles(store); len(files) != 0 { + t.Errorf("left %d files in storage", len(files)) + } + }) + } +} + +// TestNPMStreamedPackumentConcurrent checks that concurrent requests for an +// uncached packument share one upstream fetch and all get it. +func TestNPMStreamedPackumentConcurrent(t *testing.T) { + body := bigPackument(400) + u := newStreamUpstream(t, body) + proxy, _, handler := streamProxy(t, u) + proxy.MetadataMaxSize = int64(len(body) / 4) + const n = 16 + var wg sync.WaitGroup + recs := make([]*httptest.ResponseRecorder, n) + for i := range n { + wg.Go(func() { recs[i] = serve(handler, "/big", nil) }) + } + wg.Wait() + for _, rec := range recs { + if doc := decodeStreamed(t, rec); len(doc.Versions) != 400 { + t.Errorf("served %d versions, want 400", len(doc.Versions)) + } + } + if got := u.sent.Load(); got != 1 { + t.Errorf("upstream sent the document %d times, want once", got) + } +} + +// TestNPMStreamedPackumentClientRevalidates checks that a client sending +// the ETag it got gets a 304, and a new ETag once the document changes. +func TestNPMStreamedPackumentClientRevalidates(t *testing.T) { + body := bigPackument(400) + u := newStreamUpstream(t, body) + proxy, _, handler := streamProxy(t, u) + proxy.MetadataMaxSize = int64(len(body) / 4) + + first := serve(handler, "/big", nil) + etag := first.Header().Get("ETag") + if first.Code != http.StatusOK || etag == "" { + t.Fatalf("status %d, ETag %q", first.Code, etag) + } + if rec := serve(handler, "/big", http.Header{"If-None-Match": {etag}}); rec.Code != http.StatusNotModified { + t.Errorf("same document: status %d, want 304", rec.Code) + } + + u.replace(bigPackument(401), `"v2"`) + proxy.MetadataTTL = time.Nanosecond + rec := serve(handler, "/big", http.Header{"If-None-Match": {etag}}) + if rec.Code != http.StatusOK || rec.Header().Get("ETag") == etag { + t.Errorf("changed document: status %d, ETag %q (was %q)", rec.Code, rec.Header().Get("ETag"), etag) + } + if doc := decodeStreamed(t, rec); len(doc.Versions) != 401 { + t.Errorf("served %d versions, want 401", len(doc.Versions)) + } +} + +// TestNPMStreamedPackumentOverStreamLimit checks that a document over +// MetadataStreamMaxSize is neither stored nor served: the stored copy is +// served instead, with and without cooldown, and with nothing stored the +// request fails. +func TestNPMStreamedPackumentOverStreamLimit(t *testing.T) { + for _, withCooldown := range []bool{true, false} { + t.Run(map[bool]string{true: "cooldown", false: "no cooldown"}[withCooldown], func(t *testing.T) { + body := bigPackument(400) + u := newStreamUpstream(t, body) + proxy, store, handler := streamProxy(t, u) + if !withCooldown { + proxy.Cooldown = nil + } + proxy.MetadataMaxSize = int64(len(body) / 4) + proxy.MetadataStreamMaxSize = int64(len(body) + 1000) + want := len(decodeStreamed(t, serve(handler, "/big", nil)).Versions) + before := bigMetadataFiles(store) + + u.replace(bigPackument(500), `"v2"`) + proxy.MetadataTTL = time.Nanosecond + proxy.SetMetadataRewriteCacheSize(64 << 20) + + if doc := decodeStreamed(t, serve(handler, "/big", nil)); len(doc.Versions) != want { + t.Errorf("served %d versions, want the stored %d", len(doc.Versions), want) + } + after := bigMetadataFiles(store) + if len(after) != len(before) { + t.Errorf("storage holds %d files, %d before", len(after), len(before)) + } + for path, b := range before { + if after[path] != b { + t.Errorf("%s was changed", path) + } + } + }) + } + t.Run("uncached", func(t *testing.T) { + body := bigPackument(400) + u := newStreamUpstream(t, body) + proxy, store, handler := streamProxy(t, u) + proxy.MetadataMaxSize = int64(len(body) / 4) + proxy.MetadataStreamMaxSize = int64(len(body) / 2) + + if rec := serve(handler, "/big", nil); rec.Code != http.StatusBadGateway { + t.Errorf("status %d, want 502", rec.Code) + } + if files := bigMetadataFiles(store); len(files) != 0 { + t.Errorf("left %d files in storage", len(files)) + } + if entry, _ := proxy.DB.GetMetadataCache("npm", "big"); entry != nil { + t.Error("left a metadata cache row") + } + }) +} diff --git a/internal/handler/npm_stream_test.go b/internal/handler/npm_stream_test.go new file mode 100644 index 0000000..5d2ab73 --- /dev/null +++ b/internal/handler/npm_stream_test.go @@ -0,0 +1,464 @@ +package handler + +import ( + "bytes" + "compress/gzip" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/git-pkgs/cooldown" + "github.com/git-pkgs/registries/fetch" +) + +// bigPackument returns a packument laid out as registry.npmjs.org writes +// them, dist-tags before versions and time after, with n old versions padded +// so the document is large, and a latest published an hour ago. +func bigPackument(n int) string { + return bigPackumentAt("https://registry.npmjs.org", n) +} + +// bigPackumentAt is bigPackument with tarballs under base. +func bigPackumentAt(base string, n int) string { + var b strings.Builder + b.WriteString(`{"_id":"big","name":"big","dist-tags":{"latest":"9.0.0","old":"1.0.0"},"versions":{`) + times := []string{`"created":"2015-01-01T00:00:00Z"`} + for i := range n { + v := fmt.Sprintf("1.0.%d", i) + if i == 0 { + v = "1.0.0" + } + fmt.Fprintf(&b, `%q:{"name":"big","version":%q,"readme":%q,"dist":{"tarball":"%s/big/-/big-%s.tgz"}},`, + v, v, strings.Repeat("x", 512), base, v) + times = append(times, fmt.Sprintf(`%q:"2016-01-01T00:%02d:%02dZ"`, v, i/60%60, i%60)) + } + recent := time.Now().Add(-time.Hour).UTC().Format(time.RFC3339) + b.WriteString(`"9.0.0":{"name":"big","version":"9.0.0","dist":{"tarball":"` + base + `/big/-/big-9.0.0.tgz"}}},`) + times = append(times, `"9.0.0":"`+recent+`"`) + b.WriteString(`"time":{` + strings.Join(times, ",") + `},"readme":"big"}`) + return b.String() +} + +type streamUpstream struct { + *httptest.Server + body atomic.Value // string + etag atomic.Value // string + fail atomic.Bool + gone atomic.Bool + // truncate makes upstream close the connection halfway through the + // document it announced. + truncate atomic.Bool + requests atomic.Int32 + // sent counts the responses that carried the document. + sent atomic.Int32 +} + +// replace makes upstream send body under a new ETag, so a revalidation +// gets it in a 200. +func (u *streamUpstream) replace(body, etag string) { + u.body.Store(body) + u.etag.Store(etag) +} + +func newStreamUpstream(t *testing.T, body string) *streamUpstream { + t.Helper() + u := &streamUpstream{} + u.replace(body, `"v1"`) + u.Server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + u.requests.Add(1) + switch { + case u.fail.Load(): + http.Error(w, "down", http.StatusBadGateway) + case u.gone.Load(): + http.NotFound(w, r) + case r.URL.Path == "/big" && r.Header.Get("If-None-Match") == u.etag.Load().(string): + w.WriteHeader(http.StatusNotModified) + case r.URL.Path == "/big": + u.sent.Add(1) + body := u.body.Load().(string) + w.Header().Set("Content-Type", "application/json") + w.Header().Set("ETag", u.etag.Load().(string)) + if u.truncate.Load() { + w.Header().Set("Content-Length", fmt.Sprint(len(body))) + _, _ = io.WriteString(w, body[:len(body)/2]) + return + } + _, _ = io.WriteString(w, body) + default: + http.NotFound(w, r) + } + })) + t.Cleanup(u.Close) + return u +} + +func streamProxy(t *testing.T, u *streamUpstream) (*Proxy, *mockStorage, http.Handler) { + t.Helper() + proxy, _, store, _ := setupTestProxy(t) + proxy.HTTPClient = u.Client() + proxy.CacheMetadata = true + proxy.MetadataTTL = time.Hour + proxy.SetMetadataRewriteCacheSize(64 << 20) + proxy.Cooldown = &cooldown.Config{Default: "3d"} + return proxy, store, NewNPMHandler(proxy, "http://proxy.example", u.URL).Routes() +} + +type packumentDoc struct { + DistTags map[string]string `json:"dist-tags"` + Versions map[string]json.RawMessage `json:"versions"` + Time map[string]string `json:"time"` +} + +func decodeStreamed(t *testing.T, rec *httptest.ResponseRecorder) packumentDoc { + t.Helper() + if rec.Code != http.StatusOK { + t.Fatalf("status %d: %s", rec.Code, rec.Body.String()) + } + body := rec.Body.Bytes() + if rec.Header().Get("Content-Encoding") == "gzip" { + zr, err := gzip.NewReader(bytes.NewReader(body)) + if err != nil { + t.Fatal(err) + } + if body, err = io.ReadAll(zr); err != nil { + t.Fatal(err) + } + } + var doc packumentDoc + if err := json.Unmarshal(body, &doc); err != nil { + t.Fatalf("response is not JSON: %v", err) + } + return doc +} + +// TestNPMStreamedPackument requests a packument larger than +// metadata_max_size with cooldown on, its time map after its versions and +// its latest inside cooldown. The in-memory rewrite can't read it at all. +func TestNPMStreamedPackument(t *testing.T) { + const versions = 400 + body := bigPackument(versions) + u := newStreamUpstream(t, body) + proxy, _, handler := streamProxy(t, u) + proxy.MetadataMaxSize = int64(len(body) / 4) + + for _, header := range []http.Header{nil, {"Accept-Encoding": {"gzip"}}} { + doc := decodeStreamed(t, serve(handler, "/big", header)) + if len(doc.Versions) != versions { + t.Errorf("%d versions, want %d without 9.0.0", len(doc.Versions), versions) + } + if _, ok := doc.Versions["9.0.0"]; ok { + t.Error("9.0.0 is listed although it is inside cooldown") + } + if _, ok := doc.Time["9.0.0"]; ok { + t.Error("time still lists 9.0.0") + } + if doc.DistTags["latest"] != fmt.Sprintf("1.0.%d", versions-1) || doc.DistTags["old"] != "1.0.0" { + t.Errorf("dist-tags = %v, want latest moved to the newest version left", doc.DistTags) + } + if !strings.Contains(string(doc.Versions["1.0.0"]), `"tarball":"http://proxy.example/npm/big/-/big-1.0.0.tgz"`) { + t.Errorf("tarball not rewritten: %s", doc.Versions["1.0.0"]) + } + } + if n := u.requests.Load(); n != 1 { + t.Errorf("upstream asked %d times, want once", n) + } + + // Without the rewrite cache the in-memory path runs, which the size + // limit stops. + proxy.SetMetadataRewriteCacheSize(0) + if rec := serve(handler, "/big", nil); rec.Code == http.StatusOK { + t.Error("in-memory rewrite served a packument over metadata_max_size; the test no longer covers the stream") + } +} + +// TestNPMStreamedPackumentMatchesInMemory checks that both paths serve the +// same document and ETag. +func TestNPMStreamedPackumentMatchesInMemory(t *testing.T) { + body := bigPackument(50) + u := newStreamUpstream(t, body) + _, _, streamed := streamProxy(t, u) + inMemory, _, handler := streamProxy(t, u) + inMemory.CacheMetadata = false + + a, b := serve(streamed, "/big", nil), serve(handler, "/big", nil) + if a.Code != http.StatusOK || b.Code != http.StatusOK { + t.Fatalf("status %d and %d", a.Code, b.Code) + } + var ca, cb bytes.Buffer + if err := json.Compact(&ca, a.Body.Bytes()); err != nil { + t.Fatal(err) + } + if err := json.Compact(&cb, b.Body.Bytes()); err != nil { + t.Fatal(err) + } + if !bytes.Equal(ca.Bytes(), cb.Bytes()) { + t.Error("streamed and in-memory rewrites differ") + } +} + +// TestNPMStreamedPackumentStale serves the stored copy when upstream fails +// after the TTL, and 404 for a package upstream doesn't have. +func TestNPMStreamedPackumentStale(t *testing.T) { + u := newStreamUpstream(t, bigPackument(10)) + proxy, _, handler := streamProxy(t, u) + decodeStreamed(t, serve(handler, "/big", nil)) + + proxy.MetadataTTL = time.Nanosecond + proxy.SetMetadataRewriteCacheSize(64 << 20) // drop the cached rewrite + u.fail.Store(true) + if doc := decodeStreamed(t, serve(handler, "/big", nil)); len(doc.Versions) != 10 { + t.Errorf("stale copy has %d versions, want 10", len(doc.Versions)) + } + + u.fail.Store(false) + if rec := serve(handler, "/missing", nil); rec.Code != http.StatusNotFound { + t.Errorf("missing package: status %d, want 404", rec.Code) + } +} + +// TestNPMStreamedPackumentStaleOn404 checks that a stored copy past its TTL +// is served when upstream answers 404, as the in-memory path does. +func TestNPMStreamedPackumentStaleOn404(t *testing.T) { + u := newStreamUpstream(t, bigPackument(10)) + proxy, _, handler := streamProxy(t, u) + decodeStreamed(t, serve(handler, "/big", nil)) + + proxy.MetadataTTL = time.Nanosecond + u.gone.Store(true) + for _, size := range []int64{64 << 20, 0} { // streamed, then in memory + proxy.SetMetadataRewriteCacheSize(size) + if doc := decodeStreamed(t, serve(handler, "/big", nil)); len(doc.Versions) != 10 { + t.Errorf("rewrite cache %d: stale copy has %d versions, want 10", size, len(doc.Versions)) + } + } +} + +// TestNPMStreamedPackumentBlobMissing checks that a row whose document is +// gone from storage, within its TTL or revalidated by a 304 after it, fetches +// the document again, also when it is larger than metadata_max_size. +func TestNPMStreamedPackumentBlobMissing(t *testing.T) { + for _, tt := range []struct { + name string + ttl time.Duration + }{ + {"fresh row", time.Hour}, + {"expired row", time.Nanosecond}, + } { + t.Run(tt.name, func(t *testing.T) { + body := bigPackument(400) + u := newStreamUpstream(t, body) + proxy, store, handler := streamProxy(t, u) + proxy.MetadataMaxSize = int64(len(body) / 4) + decodeStreamed(t, serve(handler, "/big", nil)) + + path := metadataStoragePath("npm", "big") + store.mu.Lock() + delete(store.files, path) + store.mu.Unlock() + proxy.MetadataTTL = tt.ttl + proxy.SetMetadataRewriteCacheSize(64 << 20) + + if doc := decodeStreamed(t, serve(handler, "/big", nil)); len(doc.Versions) != 400 { + t.Errorf("served %d versions, want 400", len(doc.Versions)) + } + if n := u.sent.Load(); n != 2 { + t.Errorf("upstream sent the document %d times, want 2", n) + } + store.mu.Lock() + defer store.mu.Unlock() + if string(store.files[path]) != body { + t.Error("the document was not stored again") + } + }) + } +} + +// TestNPMStreamedVersionBlobMissing checks that a version request and a +// tarball download fetch a packument again whose stored copy is gone while +// its row is within the TTL. +func TestNPMStreamedVersionBlobMissing(t *testing.T) { + u := newStreamUpstream(t, "") + u.body.Store(bigPackumentAt(u.URL, 100)) + proxy, store, handler := streamProxy(t, u) + proxy.MetadataMaxSize = 1024 + fetcher := proxy.Fetcher.(*mockFetcher) + fetcher.artifact = &fetch.Artifact{Body: io.NopCloser(strings.NewReader("package"))} + path := metadataStoragePath("npm", "big") + + for _, req := range []string{"/big/1.0.5", "/big/-/big-1.0.5.tgz"} { + decodeStreamed(t, serve(handler, "/big", nil)) + store.mu.Lock() + delete(store.files, path) + store.mu.Unlock() + proxy.SetMetadataRewriteCacheSize(64 << 20) + + if rec := serve(handler, req, nil); rec.Code != http.StatusOK { + t.Errorf("%s: status %d: %.200s", req, rec.Code, rec.Body.String()) + } + store.mu.Lock() + _, ok := store.files[path] + store.mu.Unlock() + if !ok { + t.Errorf("%s: the packument was not stored again", req) + } + } +} + +// TestNPMStreamedPackumentChangedInStorage checks that a document replaced +// in storage between the two passes isn't rewritten from mixed bytes. +func TestNPMStreamedPackumentChangedInStorage(t *testing.T) { + u := newStreamUpstream(t, bigPackument(10)) + proxy, store, _ := streamProxy(t, u) + entry, err := proxy.storedMetadataDocument(context.Background(), "npm", "big", u.URL+"/big", contentTypeJSON, nil) + if err != nil { + t.Fatal(err) + } + store.mu.Lock() + store.files[entry.StoragePath] = []byte(bigPackument(11)) + store.mu.Unlock() + + r, err := proxy.openStoredMetadata(context.Background(), entry) + if err != nil { + t.Fatal(err) + } + defer func() { _ = r.Close() }() + if _, err := io.ReadAll(r); !errors.Is(err, errStoredMetadataChanged) { + t.Errorf("read error %v, want errStoredMetadataChanged", err) + } +} + +// TestNPMStreamedPackumentRevalidates checks that a 304 after the TTL keeps +// the stored document and its cached rewrite, without storing it again. +func TestNPMStreamedPackumentRevalidates(t *testing.T) { + u := newStreamUpstream(t, bigPackument(10)) + proxy, store, handler := streamProxy(t, u) + first := serve(handler, "/big", nil) + decodeStreamed(t, first) + store.mu.Lock() + stores := store.stores + store.mu.Unlock() + + proxy.MetadataTTL = time.Nanosecond + second := serve(handler, "/big", nil) + decodeStreamed(t, second) + if second.Header().Get("ETag") != first.Header().Get("ETag") { + t.Errorf("ETag changed from %s to %s", first.Header().Get("ETag"), second.Header().Get("ETag")) + } + if n := u.requests.Load(); n != 2 { + t.Errorf("upstream asked %d times, want 2", n) + } + store.mu.Lock() + defer store.mu.Unlock() + if store.stores != stores { + t.Errorf("the 304 stored the document again (%d stores, %d before)", store.stores, stores) + } +} + +// TestNPMStreamedPackumentKeepsFullCopy checks that an abbreviated packument +// from upstream, where cooldown needs the full one, doesn't replace the full +// copy in storage, which is served instead as when upstream fails. +func TestNPMStreamedPackumentKeepsFullCopy(t *testing.T) { + full := bigPackument(10) + u := newStreamUpstream(t, full) + proxy, store, handler := streamProxy(t, u) + decodeStreamed(t, serve(handler, "/big", nil)) + + proxy.MetadataTTL = time.Nanosecond + proxy.SetMetadataRewriteCacheSize(64 << 20) + u.replace(`{"name":"big","modified":"2026-01-01T00:00:00Z","dist-tags":{"latest":"1.0.0"},"versions":{"1.0.0":{}}}`, `"v2"`) + if doc := decodeStreamed(t, serve(handler, "/big", nil)); len(doc.Versions) != 10 { + t.Errorf("served %d versions, want the 10 of the full copy", len(doc.Versions)) + } + if n := u.sent.Load(); n != 2 { + t.Fatalf("upstream sent a document %d times, want 2: the abbreviated one was not fetched", n) + } + + store.mu.Lock() + defer store.mu.Unlock() + if got := string(store.files[metadataStoragePath("npm", "big")]); got != full { + t.Errorf("stored packument was replaced: %.80s", got) + } + for path := range store.files { + if strings.Contains(path, ".staged-") { + t.Errorf("staged copy %s left in storage", path) + } + } +} + +// TestNPMStreamedPackumentStorageFails checks that a packument is still +// served, read into memory, when storing it fails. +func TestNPMStreamedPackumentStorageFails(t *testing.T) { + u := newStreamUpstream(t, bigPackument(10)) + _, store, handler := streamProxy(t, u) + store.storeErr = errors.New("no space left on device") + doc := decodeStreamed(t, serve(handler, "/big", nil)) + if len(doc.Versions) != 10 || doc.DistTags["latest"] != "1.0.9" { + t.Errorf("served %d versions, latest %q; want 10 and 1.0.9", len(doc.Versions), doc.DistTags["latest"]) + } +} + +// TestNPMStreamedVersionMetadata resolves versions and dist-tags of a +// packument larger than metadata_max_size. +func TestNPMStreamedVersionMetadata(t *testing.T) { + body := bigPackument(100) + u := newStreamUpstream(t, body) + proxy, _, handler := streamProxy(t, u) + proxy.MetadataMaxSize = int64(len(body) / 4) + + for path, want := range map[string]string{ + "/big/1.0.5": "1.0.5", + "/big/latest": "1.0.99", // 9.0.0 is inside cooldown + "/big/old": "1.0.0", + } { + rec := serve(handler, path, nil) + var v struct { + Version string `json:"version"` + Dist struct { + Tarball string `json:"tarball"` + } `json:"dist"` + } + if rec.Code != http.StatusOK || json.Unmarshal(rec.Body.Bytes(), &v) != nil { + t.Errorf("%s: status %d: %.200s", path, rec.Code, rec.Body.String()) + continue + } + if v.Version != want || v.Dist.Tarball != "http://proxy.example/npm/big/-/big-"+want+".tgz" { + t.Errorf("%s = %s with tarball %s, want %s", path, v.Version, v.Dist.Tarball, want) + } + } + if rec := serve(handler, "/big/9.0.0", nil); rec.Code != http.StatusNotFound { + t.Errorf("version inside cooldown: status %d, want 404", rec.Code) + } + if n := u.requests.Load(); n != 1 { + t.Errorf("upstream asked %d times, want once", n) + } +} + +// TestNPMStreamedTarballCooldown checks the tarball download against a +// packument larger than metadata_max_size: the version's publish time and +// tarball URL are read from storage. +func TestNPMStreamedTarballCooldown(t *testing.T) { + u := newStreamUpstream(t, "") + u.body.Store(bigPackumentAt(u.URL, 100)) + proxy, _, handler := streamProxy(t, u) + proxy.MetadataMaxSize = 1024 + fetcher := proxy.Fetcher.(*mockFetcher) + fetcher.artifact = &fetch.Artifact{Body: io.NopCloser(strings.NewReader("package"))} + + if rec := serve(handler, "/big/-/big-9.0.0.tgz", nil); rec.Code != http.StatusNotFound { + t.Errorf("tarball inside cooldown: status %d, want 404", rec.Code) + } + if rec := serve(handler, "/big/-/big-1.0.5.tgz", nil); rec.Code != http.StatusOK || rec.Body.String() != "package" { + t.Errorf("tarball: status %d, body %q", rec.Code, rec.Body.String()) + } + if want := u.URL + "/big/-/big-1.0.5.tgz"; fetcher.fetchedURL != want { + t.Errorf("fetched %s, want %s from the packument", fetcher.fetchedURL, want) + } +} diff --git a/internal/handler/npm_tarball_test.go b/internal/handler/npm_tarball_test.go index 303f218..6bca0f6 100644 --- a/internal/handler/npm_tarball_test.go +++ b/internal/handler/npm_tarball_test.go @@ -1,6 +1,7 @@ package handler import ( + "context" "encoding/json" "fmt" "io" @@ -13,6 +14,7 @@ import ( "time" "github.com/git-pkgs/cooldown" + registryclient "github.com/git-pkgs/registries/client" "github.com/git-pkgs/registries/fetch" ) @@ -92,12 +94,9 @@ func npmContentAddressedRegistry(t *testing.T, metadataCalls, tarballCalls *atom } func TestNPMTarballMetadataFallback(t *testing.T) { - for _, body := range []string{`{"versions":{}}`, `{"versions":{"1.0.0":{"dist":{}}}}`, `not json`, "unavailable"} { + for _, body := range []string{`{"versions":{}}`, `{"versions":{"1.0.0":{"dist":{}}}}`} { t.Run(body, func(t *testing.T) { upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { - if body == "unavailable" { - w.WriteHeader(http.StatusServiceUnavailable) - } _, _ = io.WriteString(w, body) })) t.Cleanup(upstream.Close) @@ -106,12 +105,10 @@ func TestNPMTarballMetadataFallback(t *testing.T) { p.MetadataTTL = time.Hour fetcher.artifact = &fetch.Artifact{Body: io.NopCloser(strings.NewReader("package"))} h := NewNPMHandler(p, "http://proxy.test", upstream.URL) - if body != "unavailable" { - if _, _, err := p.FetchOrCacheMetadata(t.Context(), "npm", "@example/widget", upstream.URL); err != nil { - t.Fatal(err) - } - upstream.Close() + if _, _, err := p.FetchOrCacheMetadata(t.Context(), "npm", "@example/widget", upstream.URL); err != nil { + t.Fatal(err) } + upstream.Close() response := httptest.NewRecorder() h.Routes().ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/@example/widget/-/widget-1.0.0.tgz", nil)) if response.Code != http.StatusOK { @@ -124,6 +121,60 @@ func TestNPMTarballMetadataFallback(t *testing.T) { } } +// TestNPMTarballWithoutMetadataIsNotFetched checks that a tarball whose +// packument can't be read, so its integrity is unknown, is neither fetched +// nor cached. +func TestNPMTarballWithoutMetadataIsNotFetched(t *testing.T) { + for _, tc := range []struct { + name string + status int + body string + limit int64 + }{ + {name: "unavailable", status: http.StatusServiceUnavailable, body: "unavailable"}, + {name: "over metadata_max_size", status: http.StatusOK, body: `{"versions":{"1.0.0":{"dist":{"integrity":"` + sha512SRI("package") + `"}}}}`, limit: 16}, + } { + t.Run(tc.name, func(t *testing.T) { + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(tc.status) + _, _ = io.WriteString(w, tc.body) + })) + t.Cleanup(upstream.Close) + p, _, _, fetcher := setupTestProxy(t) + if tc.limit > 0 { + p.MetadataMaxSize = tc.limit + } + fetcher.artifact = &fetch.Artifact{Body: io.NopCloser(strings.NewReader("tampered"))} + h := NewNPMHandler(p, "http://proxy.test", upstream.URL) + + response := httptest.NewRecorder() + h.Routes().ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/@example/widget/-/widget-1.0.0.tgz", nil)) + if response.Code != http.StatusBadGateway { + t.Fatalf("status = %d, want 502: %s", response.Code, response.Body.String()) + } + if fetcher.fetchedURL != "" { + t.Errorf("fetched %q without the metadata to verify it", fetcher.fetchedURL) + } + cached, err := p.GetCachedArtifact(t.Context(), "npm", "@example/widget", "1.0.0", "widget-1.0.0.tgz") + if err != nil { + t.Fatal(err) + } + if cached != nil { + _ = cached.Reader.Close() + t.Error("tarball was cached without verification") + } + }) + } +} + +// serveEmptyPackuments answers every metadata request with a packument that +// lists no versions, for tests about the tarball download itself. +func serveEmptyPackuments(p *Proxy) { + p.HTTPClient = &http.Client{Transport: pypiRoundTripFunc(func(r *http.Request) (*http.Response, error) { + return pypiHTTPResponse(r, "application/json", `{"versions":{}}`), nil + })} +} + func TestNPMTarballRejectsUnsafeMetadataURL(t *testing.T) { for _, target := range []string{ "https://outside.invalid/package.tgz", "//outside.invalid/package.tgz", "/registry/package.tgz", @@ -152,3 +203,224 @@ func TestNPMTarballRejectsUnsafeMetadataURL(t *testing.T) { }) } } + +// TestNPMTarballCooldownRefetchesStalePackument checks that a tarball for a +// version the cached packument does not list yet is decided on the packument +// upstream serves now, not let through for want of a publish time. +func TestNPMTarballCooldownRefetchesStalePackument(t *testing.T) { + for _, tc := range []struct { + name string + published time.Time + down bool + want int + }{ + {"recent", time.Now().Add(-time.Hour), false, http.StatusNotFound}, + // Without upstream the version can't be checked, so it isn't served. + {"upstream down", time.Now().Add(-time.Hour), true, http.StatusBadGateway}, + // The refetched entry's integrity is checked, so a tarball that + // doesn't match it is refused rather than served unverified. + {"old", time.Now().Add(-30 * 24 * time.Hour), false, http.StatusBadGateway}, + } { + t.Run(tc.name, func(t *testing.T) { + var released atomic.Bool + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + old := time.Now().Add(-60 * 24 * time.Hour).Format(time.RFC3339) + if released.Load() && tc.down { + w.WriteHeader(http.StatusServiceUnavailable) + return + } + if !released.Load() { + _, _ = fmt.Fprintf(w, `{"name":"widget","time":{"1.0.0":%q},"versions":{"1.0.0":{"dist":{}}}}`, old) + return + } + _, _ = fmt.Fprintf(w, `{"name":"widget","time":{"1.0.0":%q,"2.0.0":%q},"versions":{"1.0.0":{"dist":{}},"2.0.0":{"dist":{"integrity":%q}}}}`, + old, tc.published.Format(time.RFC3339), sha512SRI("package")) + })) + t.Cleanup(upstream.Close) + p, _, _, fetcher := setupTestProxy(t) + p.CacheMetadata = true + p.MetadataTTL = time.Hour + p.Cooldown = &cooldown.Config{Default: "7d"} + p.HTTPClient = upstream.Client() + fetcher.artifact = &fetch.Artifact{Body: io.NopCloser(strings.NewReader("tampered"))} + h := NewNPMHandler(p, "http://proxy.test", upstream.URL) + + metadata := httptest.NewRecorder() + h.Routes().ServeHTTP(metadata, httptest.NewRequest(http.MethodGet, "/widget", nil)) + if metadata.Code != http.StatusOK { + t.Fatalf("metadata status = %d: %s", metadata.Code, metadata.Body.String()) + } + released.Store(true) + + response := httptest.NewRecorder() + h.Routes().ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/widget/-/widget-2.0.0.tgz", nil)) + if response.Code != tc.want { + t.Fatalf("status = %d, want %d: %s", response.Code, tc.want, response.Body.String()) + } + }) + } +} + +// widgetPackument is a packument listing only widget 1.0.0, published long +// ago. +func widgetPackument() string { + old := time.Now().Add(-60 * 24 * time.Hour).Format(time.RFC3339) + return fmt.Sprintf(`{"name":"widget","time":{"1.0.0":%q},"versions":{"1.0.0":{"dist":{}}}}`, old) +} + +// cooldownNPMHandler returns an npm handler for upstream with cooldown on +// and a tarball fetcher that would serve anything asked of it. +func cooldownNPMHandler(t *testing.T, upstream *httptest.Server, ttl time.Duration) *NPMHandler { + t.Helper() + p, _, _, fetcher := setupTestProxy(t) + p.CacheMetadata = true + p.MetadataTTL = ttl + p.Cooldown = &cooldown.Config{Default: "7d"} + p.HTTPClient = upstream.Client() + fetcher.artifact = &fetch.Artifact{Body: io.NopCloser(strings.NewReader("package"))} + return NewNPMHandler(p, "http://proxy.test", upstream.URL) +} + +// TestNPMTarballCooldownStalePackument checks that a stale packument served +// because upstream failed doesn't let through a version it doesn't list, +// and that the upstream failure decides the response. +func TestNPMTarballCooldownStalePackument(t *testing.T) { + for _, tc := range []struct { + name string + status int + limited bool + want int + }{ + {"upstream down", http.StatusServiceUnavailable, false, http.StatusBadGateway}, + {"not found", http.StatusNotFound, false, http.StatusNotFound}, + {"rate limited", http.StatusTooManyRequests, true, http.StatusServiceUnavailable}, + } { + t.Run(tc.name, func(t *testing.T) { + var down atomic.Bool + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + if down.Load() { + w.Header().Set("Retry-After", "60") + w.WriteHeader(tc.status) + return + } + _, _ = io.WriteString(w, widgetPackument()) + })) + t.Cleanup(upstream.Close) + // With no TTL the packument is read in memory and every read + // asks upstream. + h := cooldownNPMHandler(t, upstream, 0) + if tc.limited { + gate := registryclient.NewRateLimitGate(http.DefaultTransport) + h.proxy.HTTPClient = &http.Client{Transport: gate} + h.proxy.RateLimits = gate + } + + metadata := httptest.NewRecorder() + h.Routes().ServeHTTP(metadata, httptest.NewRequest(http.MethodGet, "/widget", nil)) + if metadata.Code != http.StatusOK { + t.Fatalf("metadata status = %d: %s", metadata.Code, metadata.Body.String()) + } + down.Store(true) + + response := httptest.NewRecorder() + h.Routes().ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/widget/-/widget-2.0.0.tgz", nil)) + if response.Code != tc.want { + t.Fatalf("status = %d, want %d: %s", response.Code, tc.want, response.Body.String()) + } + if tc.limited && response.Header().Get("Retry-After") == "" { + t.Error("no Retry-After on a rate-limited response") + } + }) + } +} + +// TestNPMTarballCooldownFetchesMissingVersionOnce checks that a packument +// just fetched from upstream isn't fetched again because it doesn't list the +// requested version. +func TestNPMTarballCooldownFetchesMissingVersionOnce(t *testing.T) { + var requests atomic.Int32 + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + requests.Add(1) + _, _ = io.WriteString(w, widgetPackument()) + })) + t.Cleanup(upstream.Close) + h := cooldownNPMHandler(t, upstream, time.Hour) + + response := httptest.NewRecorder() + h.Routes().ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/widget/-/widget-99.0.0.tgz", nil)) + if n := requests.Load(); n != 1 { + t.Errorf("upstream packument requests = %d, want 1", n) + } +} + +// TestNPMTarballCooldownRefreshIgnoresSharedStale checks that a refetch of a +// stored packument lacking the version, joining another caller's fetch that +// falls back to the stored copy, doesn't take that copy as upstream's answer. +func TestNPMTarballCooldownRefreshIgnoresSharedStale(t *testing.T) { + var blocked atomic.Bool + arrived := make(chan struct{}, 1) + release := make(chan struct{}) + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if !blocked.Load() { + _, _ = io.WriteString(w, widgetPackument()) + return + } + arrived <- struct{}{} + select { + case <-release: + case <-r.Context().Done(): + } + w.WriteHeader(http.StatusServiceUnavailable) + })) + t.Cleanup(upstream.Close) + h := cooldownNPMHandler(t, upstream, time.Hour) + p := h.proxy + + metadata := httptest.NewRecorder() + h.Routes().ServeHTTP(metadata, httptest.NewRequest(http.MethodGet, "/widget", nil)) + if metadata.Code != http.StatusOK { + t.Fatalf("metadata status = %d: %s", metadata.Code, metadata.Body.String()) + } + registryURL, cacheKey := h.sourceFor("widget") + packumentURL := registryURL + "/widget" + accept := h.packumentAccept() + row, err := p.DB.GetMetadataCache("npm", cacheKey) + if err != nil || row == nil { + t.Fatalf("no stored packument row: %v", err) + } + setFetchedAt := func(at time.Time) { + t.Helper() + if ok, err := p.DB.RefreshMetadataCache("npm", cacheKey, row.ContentDigest.String, at); err != nil || !ok { + t.Fatalf("setting fetched_at: %t, %v", ok, err) + } + } + + // Another caller revalidates the expired copy, and upstream holds it. + setFetchedAt(time.Now().Add(-2 * time.Hour)) + blocked.Store(true) + other := make(chan error, 1) + go func() { + _, err := p.storedMetadataDocument(context.Background(), "npm", cacheKey, packumentURL, accept, h.packumentStreamValidator()) + other <- err + }() + <-arrived + + // The tarball request reads the copy as within its TTL and refetches it, + // joining that fetch. + setFetchedAt(time.Now()) + response := httptest.NewRecorder() + done := make(chan struct{}) + go func() { + defer close(done) + h.Routes().ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/widget/-/widget-2.0.0.tgz", nil)) + }() + waitForMetadataWaiters(t, p, metadataCoalesceKey("npm", cacheKey, packumentURL, accept, "", false)+"\x00stored", 1) + close(release) + <-done + if err := <-other; err != nil { + t.Fatalf("other caller: %v", err) + } + if response.Code != http.StatusBadGateway { + t.Fatalf("status = %d, want %d: %s", response.Code, http.StatusBadGateway, response.Body.String()) + } +} diff --git a/internal/handler/npm_test.go b/internal/handler/npm_test.go index 721e5a4..9b9a6c3 100644 --- a/internal/handler/npm_test.go +++ b/internal/handler/npm_test.go @@ -96,6 +96,7 @@ func TestNPMHandlerUsesConfiguredUpstream(t *testing.T) { Body: io.NopCloser(strings.NewReader("package")), ContentType: "application/gzip", } + serveEmptyPackuments(proxy) h := NewNPMHandler(proxy, "http://proxy.test", "https://npm.example.test/root/") req := httptest.NewRequest(http.MethodGet, "/testpkg/-/testpkg-1.0.0.tgz", nil) @@ -117,6 +118,7 @@ func TestNPMHandlerUsesConfiguredUpstream(t *testing.T) { Body: io.NopCloser(strings.NewReader("package")), ContentType: "application/gzip", } + serveEmptyPackuments(proxy) h := NewNPMHandler(proxy, "http://proxy.test", "https://npm.example.test/root/") req := httptest.NewRequest(http.MethodGet, "/@scope/name/-/name-1.0.0.tgz", nil) @@ -174,6 +176,26 @@ func TestNPMRewriteMetadata(t *testing.T) { } } +func TestNPMRewriteMetadataLogsOncePerDocument(t *testing.T) { + var logs bytes.Buffer + proxy := testProxy() + proxy.Logger = slog.New(slog.NewTextHandler(&logs, &slog.HandlerOptions{Level: slog.LevelDebug})) + h := &NPMHandler{proxy: proxy, proxyURL: "http://localhost:8080"} + + input := `{"name":"lodash","versions":{ + "4.17.19":{"dist":{"tarball":"https://registry.npmjs.org/lodash/-/lodash-4.17.19.tgz"}}, + "4.17.20":{"dist":{"tarball":"https://registry.npmjs.org/lodash/-/lodash-4.17.20.tgz"}}, + "4.17.21":{"dist":{"tarball":"https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz"}}}}` + if _, _, err := h.rewriteMetadataKeeping("lodash", []byte(input)); err != nil { + t.Fatalf("rewriteMetadata failed: %v", err) + } + + lines := strings.Split(strings.TrimSpace(logs.String()), "\n") + if len(lines) != 1 || !strings.Contains(lines[0], `msg="rewrote tarball URLs"`) || !strings.Contains(lines[0], "count=3") { + t.Errorf("logs = %q, want one line counting 3 rewrites", logs.String()) + } +} + func TestNPMRewriteMetadataScopedPackage(t *testing.T) { h := &NPMHandler{ proxy: testProxy(), @@ -539,10 +561,10 @@ func TestNPMDownloadCooldownDisabled(t *testing.T) { proxy, _, _, _ := setupTestProxy(t) h := NewNPMHandler(proxy, "http://proxy.test", "") - if h.versionInCooldown("leftpad", testVersion100, func() ([]byte, error) { + if inCooldown, _ := h.versionInCooldown("leftpad", testVersion100, func() (npmVersionData, error) { t.Fatal("cooldown must not request metadata when disabled") - return nil, nil - }) { + return npmVersionData{}, nil + }); inCooldown { t.Error("versionInCooldown = true, want false when cooldown is not configured") } } @@ -673,6 +695,7 @@ func TestNPMDownloadErrorResponsesAreJSON(t *testing.T) { ContentType: "application/octet-stream", } + serveEmptyPackuments(proxy) h := NewNPMHandler(proxy, "http://proxy.test", "http://upstream.invalid") srv := httptest.NewServer(h.Routes()) defer srv.Close() @@ -1033,6 +1056,7 @@ func TestNPMTarballStillRoutesToDownload(t *testing.T) { Body: io.NopCloser(strings.NewReader("package")), ContentType: "application/gzip", } + serveEmptyPackuments(proxy) h := NewNPMHandler(proxy, "http://proxy.test", "https://npm.example.test") w := serveNPM(t, h, http.MethodGet, "/lodash/-/lodash-4.17.21.tgz", nil, nil) @@ -1308,3 +1332,100 @@ func TestNPMVersionMetadataDenied(t *testing.T) { t.Fatalf("status = %d, want 403; body: %s", w.Code, w.Body.String()) } } + +// `npm search` asks for /-/v1/search?text=.... The path used to fall through to +// the package dispatch, which dropped the query string, escaped the path into +// a package name and cached the answer, so every later search got the first +// one's results. +func TestNPMSearchRelaysQueryUncached(t *testing.T) { + var ( + requests int + gotPaths []string + ) + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + requests++ + gotPaths = append(gotPaths, r.URL.EscapedPath()) + if r.URL.EscapedPath() != "/-/v1/search" { + w.WriteHeader(http.StatusNotFound) + return + } + w.Header().Set("Content-Type", "application/json") + _, _ = fmt.Fprintf(w, `{"objects":[],"total":0,"query":%q}`, r.URL.RawQuery) + })) + defer upstream.Close() + + proxy, db, _, _ := setupTestProxy(t) + proxy.CacheMetadata = true + proxy.MetadataTTL = time.Hour + proxy.HTTPClient = upstream.Client() + h := NewNPMHandler(proxy, "http://proxy.test", upstream.URL) + + for _, query := range []string{"text=foo&size=20", "text=bar&size=20", "text=foo&size=20"} { + w := serveNPM(t, h, http.MethodGet, "/-/v1/search?"+query, nil, nil) + if w.Code != http.StatusOK { + t.Fatalf("search %q: status = %d; body: %s", query, w.Code, w.Body.String()) + } + if want := fmt.Sprintf(`{"objects":[],"total":0,"query":%q}`, query); w.Body.String() != want { + t.Errorf("search %q: body = %s, want %s", query, w.Body.String(), want) + } + } + if requests != 3 { + t.Errorf("upstream requests = %d (%q), want 3: searches must not be cached", requests, gotPaths) + } + for _, key := range []string{"-/v1/search", "-", "-/v1"} { + if entry, _ := db.GetMetadataCache("npm", key); entry != nil { + t.Errorf("search response cached under %q", key) + } + } +} + +// `npm ping` reads /-/ping, which used to be looked up as a package. +func TestNPMPingRelaysUpstream(t *testing.T) { + var gotPath, gotQuery string + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + gotPath, gotQuery = r.URL.EscapedPath(), r.URL.RawQuery + w.Header().Set("Content-Type", "application/json") + _, _ = io.WriteString(w, "{}") + })) + defer upstream.Close() + + proxy, _, _, _ := setupTestProxy(t) + proxy.HTTPClient = upstream.Client() + h := NewNPMHandler(proxy, "http://proxy.test", upstream.URL) + + w := serveNPM(t, h, http.MethodGet, "/-/ping?write=true", nil, nil) + if w.Code != http.StatusOK || w.Body.String() != "{}" { + t.Fatalf("ping = %d %q, want 200 {}", w.Code, w.Body.String()) + } + if gotPath != "/-/ping" || gotQuery != "write=true" { + t.Errorf("upstream request = %q?%q, want /-/ping?write=true", gotPath, gotQuery) + } +} + +// TestNPMHeadPackument checks that packuments answer HEAD, which pnpm 12 +// sends before fetching each one, while tarballs and registry endpoints +// still only answer GET. +func TestNPMHeadPackument(t *testing.T) { + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/testpkg" { + w.WriteHeader(http.StatusNotFound) + return + } + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"name":"testpkg","versions":{"1.0.0":{"name":"testpkg","version":"1.0.0","dist":{"tarball":"https://registry.npmjs.org/testpkg/-/testpkg-1.0.0.tgz"}}}}`)) + })) + defer upstream.Close() + h := &NPMHandler{proxy: testProxy(), upstreamURL: upstream.URL, proxyURL: "http://proxy.local"} + + get := serveNPM(t, h, http.MethodGet, "/testpkg", nil, nil) + head := serveNPM(t, h, http.MethodHead, "/testpkg", nil, nil) + if head.Code != http.StatusOK || head.Header().Get("ETag") == "" || head.Header().Get("ETag") != get.Header().Get("ETag") { + t.Errorf("HEAD /testpkg = %d, ETag %q; want 200 with GET's ETag %q", head.Code, head.Header().Get("ETag"), get.Header().Get("ETag")) + } + + for _, path := range []string{"/testpkg/-/testpkg-1.0.0.tgz", "/-/ping", "/-/v1/search", "/-/package/testpkg/dist-tags"} { + if w := serveNPM(t, h, http.MethodHead, path, nil, nil); w.Code != http.StatusMethodNotAllowed { + t.Errorf("HEAD %s = %d, want %d", path, w.Code, http.StatusMethodNotAllowed) + } + } +} diff --git a/internal/handler/nuget.go b/internal/handler/nuget.go index 3d9f727..7a5b1b2 100644 --- a/internal/handler/nuget.go +++ b/internal/handler/nuget.go @@ -18,7 +18,8 @@ const ( // Packages are stored under pkg:nuget/{id} with the id lowercased, since // NuGet ids are case-insensitive. purl keeps nuget names as written, so -// package rules are lowercased the same way before the default mapping. +// package rules go through its comparison form, which lowercases them the +// same way, before the default mapping. func init() { retention.Default.Register(retention.Spec{Key: "nuget", CanonicalPackage: nugetRetentionKey}) } @@ -29,7 +30,8 @@ func nugetRetentionKey(p *purl.PURL) (string, bool) { if p == nil { return "", false } - return retention.DefaultCanonical("nuget")(purl.New(p.Type, p.Namespace, strings.ToLower(p.Name), "", nil)) + c := p.ComparisonForm() + return retention.DefaultCanonical("nuget")(purl.New(c.Type, c.Namespace, c.Name, "", nil)) } // NuGetHandler handles NuGet V3 API protocol requests. @@ -86,7 +88,7 @@ func (h *NuGetHandler) Routes() http.Handler { // handleServiceIndex serves the NuGet V3 service index with rewritten URLs. func (h *NuGetHandler) handleServiceIndex(w http.ResponseWriter, r *http.Request) { - h.proxy.Logger.Info("nuget service index request") + h.proxy.Logger.Debug("nuget service index request") upstreamURL := h.upstreamURL + "/v3/index.json" @@ -201,7 +203,7 @@ func (h *NuGetHandler) handleDownload(w http.ResponseWriter, r *http.Request) { return } - h.proxy.Logger.Info("nuget download request", + h.proxy.Logger.Debug("nuget download request", "id", id, "version", version, "filename", filename) // NuGet package IDs are case-insensitive, lowercase for storage diff --git a/internal/handler/nuget_cooldown.go b/internal/handler/nuget_cooldown.go index afb147d..7a0a17a 100644 --- a/internal/handler/nuget_cooldown.go +++ b/internal/handler/nuget_cooldown.go @@ -44,7 +44,7 @@ func (h *NuGetHandler) nugetMetadata(ctx context.Context, path string) (map[stri document, err = h.decodeNuGetMetadata(body) return err } - _, _, _, err := h.proxy.fetchOrCacheMetadata(ctx, "nuget", key, target, "", validate) + _, _, err := h.proxy.fetchOrCacheMetadata(ctx, "nuget", key, target, "", validate) if err != nil { return nil, err } @@ -204,7 +204,7 @@ func (h *NuGetHandler) nugetLeafAllowed(leaf map[string]any, id string) bool { if err != nil { return true } - return h.proxy.Cooldown.IsAllowed("nuget", canonicalPackagePURL("nuget", strings.ToLower(id)), when) + return h.proxy.cooldown().IsAllowed("nuget", canonicalPackagePURL("nuget", strings.ToLower(id)), when) } func nugetCatalogEntry(leaf map[string]any) map[string]any { diff --git a/internal/handler/os_package_identity.go b/internal/handler/os_package_identity.go new file mode 100644 index 0000000..0e0400b --- /dev/null +++ b/internal/handler/os_package_identity.go @@ -0,0 +1,17 @@ +package handler + +// OSPackageIdentity returns the name, version and architecture the deb, +// alpine and rpm download handlers cache a package file under, read from its +// path below the repository the way they read it. It returns empty strings +// for other ecosystems and for paths they would not cache. +func OSPackageIdentity(ecosystem, path string) (name, version, arch string) { + switch ecosystem { + case "deb": + return (*DebianHandler)(nil).parsePoolPath("/" + path) + case apkEcosystem: + return (*APKHandler)(nil).parseAPKPath(path) + case "rpm": + return (*RPMHandler)(nil).parseRPMPath(path) + } + return "", "", "" +} diff --git a/internal/handler/os_package_identity_test.go b/internal/handler/os_package_identity_test.go new file mode 100644 index 0000000..3d487be --- /dev/null +++ b/internal/handler/os_package_identity_test.go @@ -0,0 +1,23 @@ +package handler + +import "testing" + +func TestOSPackageIdentity(t *testing.T) { + tests := []struct { + ecosystem, path string + name, version, arch string + }{ + {"deb", "pool/main/c/curl/curl_7.88.1-10+deb12u8_amd64.deb", "curl", "7.88.1-10+deb12u8", "amd64"}, + {"alpine", "v3.20/main/aarch64/curl-8.9.1-r0.apk", "curl", "8.9.1-r0", "aarch64"}, + {"rpm", "Packages/c/curl-8.6.0-10.fc40.x86_64.rpm", "curl", "8.6.0-10.fc40", "x86_64"}, + {"deb", "pool/main/c/curl/README", "", "", ""}, + {"npm", "lodash-4.17.21.tgz", "", "", ""}, + } + for _, tt := range tests { + name, version, arch := OSPackageIdentity(tt.ecosystem, tt.path) + if name != tt.name || version != tt.version || arch != tt.arch { + t.Errorf("OSPackageIdentity(%s, %s) = %q %q %q, want %q %q %q", + tt.ecosystem, tt.path, name, version, arch, tt.name, tt.version, tt.arch) + } + } +} diff --git a/internal/handler/package_routes.go b/internal/handler/package_routes.go index 8af7099..c56c3fb 100644 --- a/internal/handler/package_routes.go +++ b/internal/handler/package_routes.go @@ -30,11 +30,10 @@ func newPackageRoutes(patterns map[string]string) packageRoutes { routes := make([]packageRoute, 0, len(patterns)) for pattern, upstreamURL := range patterns { upstreamURL = strings.TrimSuffix(upstreamURL, "/") - digest := sha256.Sum256([]byte(upstreamURL)) routes = append(routes, packageRoute{ pattern: strings.ToLower(pattern), url: upstreamURL, - id: hex.EncodeToString(digest[:])[:routeIDLength], + id: routeID(upstreamURL), }) } sort.Slice(routes, func(i, j int) bool { @@ -46,6 +45,18 @@ func newPackageRoutes(patterns map[string]string) packageRoutes { return packageRoutes{routes: routes} } +// routeID identifies a route's upstream in cache keys and filenames. +func routeID(upstreamURL string) string { + digest := sha256.Sum256([]byte(strings.TrimSuffix(upstreamURL, "/"))) + return hex.EncodeToString(digest[:])[:routeIDLength] +} + +// RoutedFilenamePrefix returns what the npm and Composer handlers put in +// front of the artifact filenames of a package routed to routeURL. +func RoutedFilenamePrefix(routeURL string) string { + return routeID(routeURL) + "/" +} + // match returns the route for a package name, if any pattern matches it. func (r packageRoutes) match(packageName string) (packageRoute, bool) { name := strings.ToLower(packageName) @@ -72,3 +83,10 @@ func (r packageRoutes) cacheFilename(packageName, filename string) string { } return filename } + +// RoutedPackageURL returns the upstream URL a route in routes sends +// packageName to, as the npm and Composer handlers pick it. +func RoutedPackageURL(routes map[string]string, packageName string) (string, bool) { + route, ok := newPackageRoutes(routes).match(packageName) + return route.url, ok +} diff --git a/internal/handler/profile.go b/internal/handler/profile.go new file mode 100644 index 0000000..ceff0a3 --- /dev/null +++ b/internal/handler/profile.go @@ -0,0 +1,42 @@ +package handler + +import "time" + +// WithCooldown creates a policy view sharing storage, fetches and rewrite space. +// Configure the original proxy before constructing its views. +func (p *Proxy) WithCooldown(policy CooldownPolicy, shortest time.Duration) *Proxy { + view := &Proxy{ + DB: p.DB, Storage: p.Storage, Fetcher: p.Fetcher, Resolver: p.Resolver, + RouteFor: p.RouteFor, Logger: p.Logger, + Cooldown: policy, ShortestCooldown: shortest, Denylist: p.Denylist, + CacheMetadata: p.CacheMetadata, MetadataTTL: p.MetadataTTL, + MetadataMaxSize: p.MetadataMaxSize, MetadataStreamMaxSize: p.MetadataStreamMaxSize, + GradleReadOnly: p.GradleReadOnly, HostedEnabled: p.HostedEnabled, + GradleMaxUploadSize: p.GradleMaxUploadSize, NPMFullMetadata: p.NPMFullMetadata, + DirectServe: p.DirectServe, DirectServeTTL: p.DirectServeTTL, + DirectServeBaseURL: p.DirectServeBaseURL, HTTPClient: p.HTTPClient, + RateLimits: p.RateLimits, HostedNPMScopes: p.HostedNPMScopes, + HostedComposerVendors: p.HostedComposerVendors, StreamArtifacts: p.StreamArtifacts, + Scanners: p.Scanners, ScanSigningKey: p.ScanSigningKey, ScanFetchBaseURL: p.ScanFetchBaseURL, + rewrites: p.rewrites, now: p.now, started: p.started, shared: p.sharedProxy(), + } + if view.cooldownEnabled() { + view.shared.viewCooldown.Store(true) + } + return view +} + +func (p *Proxy) sharedProxy() *Proxy { + if p.shared != nil { + return p.shared + } + return p +} + +// anyCooldownEnabled reports whether cooldown is on for this proxy, the one +// it is a view of, or another view of that one. What they keep in one cache +// row has to suit all of them. +func (p *Proxy) anyCooldownEnabled() bool { + shared := p.sharedProxy() + return p.cooldownEnabled() || shared.cooldownEnabled() || shared.viewCooldown.Load() +} diff --git a/internal/handler/profile_test.go b/internal/handler/profile_test.go new file mode 100644 index 0000000..ca163ee --- /dev/null +++ b/internal/handler/profile_test.go @@ -0,0 +1,234 @@ +package handler + +import ( + "context" + "errors" + "net/http" + "net/http/httptest" + "reflect" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/git-pkgs/cooldown" + "github.com/git-pkgs/proxy/internal/denylist" + "github.com/git-pkgs/proxy/internal/scanner" + registryclient "github.com/git-pkgs/registries/client" +) + +func TestWithCooldownCopiesProxyFields(t *testing.T) { + p, _, _, _ := setupTestProxy(t) + p.RouteFor = func(string, string) *ArtifactRoute { return nil } + p.Cooldown = profilePolicy(t, "1d") + p.ShortestCooldown = 24 * time.Hour + p.Denylist = &denylist.Policy{} + p.CacheMetadata = true + p.MetadataTTL = time.Hour + p.MetadataMaxSize = 1024 + p.MetadataStreamMaxSize = 2048 + p.GradleReadOnly = true + p.HostedEnabled = true + p.GradleMaxUploadSize = 4096 + p.NPMFullMetadata = true + p.DirectServe = true + p.DirectServeTTL = time.Minute + p.DirectServeBaseURL = "https://storage.example.com" + p.RateLimits = registryclient.NewRateLimitGate(http.DefaultTransport) + p.HostedNPMScopes = []string{"@example"} + p.HostedComposerVendors = []string{"example"} + p.StreamArtifacts = true + p.Scanners = &scanner.Group{} + p.ScanSigningKey = []byte("signing-key") + p.ScanFetchBaseURL = "http://scanner.example.com" + p.SetMetadataRewriteCacheSize(1024) + p.inFlight = map[string]*inflightFetch{"artifact": {}} + p.detachSlots = make(chan struct{}, 1) + p.inFlightMeta = map[string]*inflightMetadata{"metadata": {}} + p.publishIndexes.entries = map[string]publishIndexEntry{"document": {}} + p.cooldownWatch.active = map[*cooldownRecorder]struct{}{{}: {}} + + policy := profilePolicy(t, "3d") + view := p.WithCooldown(policy, 72*time.Hour) + if view.Cooldown != policy || view.ShortestCooldown != 72*time.Hour || view.shared != p { + t.Fatal("view did not select its policy and shared proxy") + } + original, copied := reflect.ValueOf(p).Elem(), reflect.ValueOf(view).Elem() + for i := range original.NumField() { + name := original.Type().Field(i).Name + before, after := original.Field(i), copied.Field(i) + switch name { + case "Cooldown", "ShortestCooldown", "shared": + continue + case "fetchMu", "inFlight", "detachSlots", "metaMu", "inFlightMeta", "publishIndexes", "cooldownWatch", "viewCooldown": + if !after.IsZero() { + t.Errorf("view field %s is not empty", name) + } + continue + } + if before.IsZero() { + t.Errorf("populate Proxy.%s to check whether WithCooldown copies it", name) + continue + } + switch before.Kind() { + case reflect.Func, reflect.Slice: + if before.Pointer() != after.Pointer() { + t.Errorf("WithCooldown did not copy %s", name) + } + if before.Kind() == reflect.Slice && (before.Len() != after.Len() || before.Cap() != after.Cap()) { + t.Errorf("WithCooldown changed slice bounds for %s", name) + } + default: + if !before.Equal(after) { + t.Errorf("WithCooldown did not copy %s", name) + } + } + } +} + +func TestProfilesShareDownloadPublishIndexes(t *testing.T) { + for _, c := range downloadCooldownCases() { + if c.ecosystem != "conda" && c.ecosystem != "helm" { + continue + } + t.Run(c.ecosystem, func(t *testing.T) { + var calls atomic.Int64 + times := map[string]time.Time{cooldownRecentVersion: time.Now().Add(-4 * 24 * time.Hour)} + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + calls.Add(1) + c.metadata(w, r, times) + })) + t.Cleanup(upstream.Close) + p, _, _, fetcher := setupTestProxy(t) + p.HTTPClient = upstream.Client() + p.Cooldown = profilePolicy(t, "1d") + fetcher.fetchErr = errors.New("artifact must be served from the cache") + c.seedCachedArtifact(t, p, cooldownRecentVersion) + permissive := p.WithCooldown(profilePolicy(t, "3d"), 72*time.Hour) + strict := p.WithCooldown(profilePolicy(t, "7d"), 168*time.Hour) + nested := permissive.WithCooldown(profilePolicy(t, "5d"), 120*time.Hour) + for _, request := range []struct { + proxy *Proxy + want int + }{ + {permissive, http.StatusOK}, + {strict, http.StatusNotFound}, + {p, http.StatusOK}, + {nested, http.StatusNotFound}, + } { + w := serveGet(t, c.handler(request.proxy, upstream.URL), c.path(cooldownRecentVersion)) + wantStatus(t, w, request.want, "") + } + if n := calls.Load(); n != 1 { + t.Errorf("index downloads across profiles = %d, want 1", n) + } + if n := len(p.publishIndexes.entries); n != 1 { + t.Errorf("shared publish indexes = %d, want 1", n) + } + if fetcher.fetchCalled { + t.Error("cached artifact was fetched again") + } + }) + } +} + +func profilePolicy(t *testing.T, duration string) *cooldown.Policy { + t.Helper() + policy, err := cooldown.NewPolicy(&cooldown.Config{Default: duration}, nil) + if err != nil { + t.Fatal(err) + } + return policy +} + +func TestProfilesCoalesceUncachedMetadata(t *testing.T) { + u := newMetadataUpstream(t, http.StatusOK) + p := metadataTestProxy(t, u) + views := []*Proxy{p.WithCooldown(profilePolicy(t, "3d"), 72*time.Hour), p.WithCooldown(profilePolicy(t, "7d"), 168*time.Hour)} + first := startMetadataCalls(views[0], context.Background(), 1, u.URL, contentTypeJSON) + <-u.entered + second := startMetadataCalls(views[1], context.Background(), 1, u.URL, contentTypeJSON) + key := metadataCoalesceKey("npm", "left-pad", u.URL, contentTypeJSON, "", false) + var release sync.Once + t.Cleanup(func() { release.Do(func() { close(u.release) }) }) + waitForMetadataWaiters(t, p, key, 1) + release.Do(func() { close(u.release) }) + for _, calls := range [][]chan metadataCall{first, second} { + result := <-calls[0] + if result.err != nil || !strings.Contains(string(result.body), "accept") { + t.Fatalf("metadata = %s, error %v", result.body, result.err) + } + } + if n := u.calls.Load(); n != 1 { + t.Fatalf("upstream requests = %d, want 1", n) + } +} + +func TestProfilesCoalesceArtifactRequests(t *testing.T) { + proxy, db, _, _ := setupTestProxy(t) + if err := db.SetVersionPublishedAt("pkg:cargo/demo@1.0.0", "pkg:cargo/demo", time.Now().Add(-10*24*time.Hour)); err != nil { + t.Fatal(err) + } + fetcher := &countingFetcher{content: "crate bytes", delay: fetchHoldTime} + proxy.Fetcher = fetcher + views := []*Proxy{proxy.WithCooldown(profilePolicy(t, "3d"), 72*time.Hour), proxy.WithCooldown(profilePolicy(t, "7d"), 168*time.Hour)} + var wg sync.WaitGroup + start := make(chan struct{}) + for range 4 { + for _, view := range views { + wg.Go(func() { + <-start + h := NewCargoHandler(view, "http://proxy.test", "https://index.crates.io", "https://static.crates.io/crates") + w := httptest.NewRecorder() + h.Routes().ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/crates/demo/1.0.0/download", nil)) + if w.Code != http.StatusOK || w.Body.String() != "crate bytes" { + t.Errorf("artifact response %d: %s", w.Code, w.Body) + } + }) + } + } + close(start) + wg.Wait() + if n := fetcher.calls.Load(); n != 1 { + t.Fatalf("upstream fetches = %d, want 1", n) + } +} + +type profileClockPolicy struct { + *cooldown.Policy + now func() time.Time +} + +func (p profileClockPolicy) IsAllowed(ecosystem, packagePURL string, publishedAt time.Time) bool { + return p.Evaluate(ecosystem, packagePURL, publishedAt, p.now()).Allowed +} + +func TestProfileExpiryReleasesVersionsIndependently(t *testing.T) { + u, proxy, _ := gemCacheSetup(t) + clock := &testClock{t: time.Now()} + proxy.now = clock.now + proxy.SetMetadataRewriteCacheSize(1 << 20) + view := proxy.WithCooldown(profileClockPolicy{profilePolicy(t, "3d"), clock.now}, 72*time.Hour) + h := NewGemHandlerWithUpstream(view, "http://proxy.test/cooldown/3d", u.URL).Routes() + strictView := proxy.WithCooldown(profileClockPolicy{profilePolicy(t, "7d"), clock.now}, 168*time.Hour) + strict := NewGemHandlerWithUpstream(strictView, "http://proxy.test/cooldown/7d", u.URL).Routes() + first := getWith(t, h, gemInfoPath, nil) + if first.Code != http.StatusOK || first.Body.String() != gemFiltered { + t.Fatalf("initial response %d: %s", first.Code, first.Body) + } + if first := getWith(t, strict, gemInfoPath, nil); first.Code != http.StatusOK || first.Body.String() != gemFiltered { + t.Fatalf("initial strict response %d: %s", first.Code, first.Body) + } + clock.advance(4 * 24 * time.Hour) + second := getWith(t, h, gemInfoPath, nil) + if second.Code != http.StatusOK || !strings.Contains(second.Body.String(), "2.0.0 |") { + t.Fatalf("version did not leave cooldown: %d %s", second.Code, second.Body) + } + if second := getWith(t, strict, gemInfoPath, nil); second.Code != http.StatusOK || second.Body.String() != gemFiltered { + t.Fatalf("strict profile released version early: %d %s", second.Code, second.Body) + } + if n, _ := u.counts(gemInfoPath); n != 1 { + t.Errorf("expiry refetched raw metadata %d times", n) + } +} diff --git a/internal/handler/proxy_cached_encoding_test.go b/internal/handler/proxy_cached_encoding_test.go index 35c8793..45eaef3 100644 --- a/internal/handler/proxy_cached_encoding_test.go +++ b/internal/handler/proxy_cached_encoding_test.go @@ -56,7 +56,7 @@ func (u *gzipWhenAskedUpstream) sawAcceptEncoding() string { func serveGzip(proxy *Proxy, upstreamURL string) *httptest.ResponseRecorder { w := httptest.NewRecorder() r := httptest.NewRequest(http.MethodGet, "/index.json", nil) - proxy.proxyCachedWithEncoding(w, r, upstreamURL, "gzip-test", "index", "gzip", "*/*") + proxy.proxyCachedWithEncoding(w, r, upstreamURL, "gzip-test", "index", "gzip", nil, "*/*") return w } @@ -187,7 +187,7 @@ func TestProxyCachedWithEncoding_UpsertFailureDiscardsBlob(t *testing.T) { // Seed an identity row + plain blob, as every key has before the gzip rollout. w := httptest.NewRecorder() proxy.proxyCachedWithEncoding(w, httptest.NewRequest(http.MethodGet, "/index.json", nil), - upstream.URL+"/index.json", "gzip-test", "index", "identity", "*/*") + upstream.URL+"/index.json", "gzip-test", "index", "identity", nil, "*/*") if w.Code != http.StatusOK { t.Fatalf("seed status = %d, want 200", w.Code) } @@ -250,7 +250,7 @@ func TestProxyCachedWithEncoding_StaleFallbackRereadsRow(t *testing.T) { w := httptest.NewRecorder() proxy.proxyCachedWithEncoding(w, httptest.NewRequest(http.MethodGet, "/index.json", nil), - upstream.URL+"/index.json", "gzip-test", "index", "identity", "*/*") + upstream.URL+"/index.json", "gzip-test", "index", "identity", nil, "*/*") if w.Code != http.StatusOK { t.Fatalf("seed status = %d, want 200", w.Code) } diff --git a/internal/handler/pub.go b/internal/handler/pub.go index 12ff6d9..5a6d426 100644 --- a/internal/handler/pub.go +++ b/internal/handler/pub.go @@ -5,17 +5,25 @@ import ( "errors" "fmt" "net/http" + "net/url" + "regexp" "strings" "time" + "github.com/Masterminds/semver/v3" + "github.com/git-pkgs/proxy/internal/database" "github.com/git-pkgs/proxy/internal/retention" ) const ( - pubUpstream = "https://pub.dev" - pubPathParts = 2 // name + version in path split by /versions/ + pubUpstream = "https://pub.dev" + pubPathParts = 2 // name + version in path split by /versions/ + pubArchiveExt = ".tar.gz" ) +// pubPackageName matches pub package names, which have to be Dart identifiers. +var pubPackageName = regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_]*$`) + // Packages are stored under pkg:pub/{name} with the name from the download // path, and purl keeps pub names as they are, so package rules use the // default key mapping. @@ -69,19 +77,37 @@ func (h *PubHandler) handleDownload(w http.ResponseWriter, r *http.Request) { return } name := parts[0] - version := strings.TrimSuffix(parts[1], ".tar.gz") + // Only the archive is cached. Without the suffix the upstream path is the + // HTML version page on pub.dev, which must not land under the archive key. + version, ok := strings.CutSuffix(parts[1], pubArchiveExt) + if !ok { + http.Error(w, "not found", http.StatusNotFound) + return + } - if name == "" || version == "" { + if !pubPackageName.MatchString(name) || version == "" || strings.Contains(version, "/") { http.Error(w, "invalid request", http.StatusBadRequest) return } - filename := fmt.Sprintf("%s-%s.tar.gz", name, version) + filename := name + "-" + version + pubArchiveExt - h.proxy.Logger.Info("pub download request", + h.proxy.Logger.Debug("pub download request", "name", name, "version", version) - downloadURL := h.upstreamURL + r.URL.Path + h.discardVersionPage(name, version, filename) + if h.proxy.withholdInCooldown(w, r, downloadVersion{ + ecosystem: "pub", policyName: name, storedName: name, version: version, cacheName: name, filename: filename, + lookup: func() (time.Time, bool, bool, error) { + published, ok, err := h.publishTime(r, name, version) + return published, ok, false, err + }, + }) { + return + } + + downloadURL := fmt.Sprintf("%s/packages/%s/versions/%s%s", + h.upstreamURL, url.PathEscape(name), url.PathEscape(version), pubArchiveExt) result, err := h.proxy.GetOrFetchArtifactFromURL( r.Context(), "pub", name, version, filename, downloadURL, ) @@ -93,6 +119,59 @@ func (h *PubHandler) handleDownload(w http.ResponseWriter, r *http.Request) { ServeArtifactRequest(w, r, result) } +// discardVersionPage clears a cached archive that was fetched from a path +// without the archive suffix. Proxy versions before the suffix check cached +// pub.dev's HTML version page under the archive's name that way. +func (h *PubHandler) discardVersionPage(name, version, filename string) { + _, versionPURL, err := packagePURLStrings("pub", name, version) + if err != nil { + return + } + record, err := h.proxy.DB.GetArtifact(versionPURL, filename) + if err != nil { + h.proxy.Logger.Warn("failed to read pub cache record", + "purl", versionPURL, "filename", filename, "error", err) + return + } + if record == nil || !record.StoragePath.Valid || record.Source == database.SourceLocal || + strings.HasSuffix(record.UpstreamURL, pubArchiveExt) { + return + } + h.proxy.Logger.Warn("cached pub archive was fetched without the archive suffix, discarding", + "purl", versionPURL, "filename", filename, "upstream_url", record.UpstreamURL) + if err := h.proxy.DB.DiscardArtifact(versionPURL, filename, record.StoragePath.String); err != nil { + h.proxy.Logger.Warn("failed to discard pub cache record", + "purl", versionPURL, "filename", filename, "error", err) + } +} + +// publishTime reads a version's published time from the package metadata, +// sharing the metadata cache with handlePackageMetadata. +func (h *PubHandler) publishTime(r *http.Request, name, version string) (time.Time, bool, error) { + upstreamURL := fmt.Sprintf("%s/api/packages/%s", h.upstreamURL, name) + body, _, err := h.proxy.FetchOrCacheMetadata(r.Context(), "pub", name, upstreamURL) + if err != nil { + return time.Time{}, false, err + } + var metadata struct { + Versions []struct { + Version string `json:"version"` + Published string `json:"published"` + } `json:"versions"` + } + if err := json.Unmarshal(body, &metadata); err != nil { + return time.Time{}, false, err + } + for _, v := range metadata.Versions { + if v.Version != version { + continue + } + published, err := time.Parse(time.RFC3339, v.Published) + return published, err == nil, nil + } + return time.Time{}, false, nil +} + // handlePackageMetadata proxies package metadata and rewrites archive URLs. func (h *PubHandler) handlePackageMetadata(w http.ResponseWriter, r *http.Request) { name := r.PathValue("name") @@ -101,7 +180,7 @@ func (h *PubHandler) handlePackageMetadata(w http.ResponseWriter, r *http.Reques return } - h.proxy.Logger.Info("pub metadata request", "package", name) + h.proxy.Logger.Debug("pub metadata request", "package", name) upstreamURL := fmt.Sprintf("%s/api/packages/%s", h.upstreamURL, name) @@ -121,6 +200,11 @@ func (h *PubHandler) handlePackageMetadata(w http.ResponseWriter, r *http.Reques rewritten, err := h.rewriteMetadata(name, body) if err != nil { + if h.proxy.mustFilterMetadata("pub", name) { + h.proxy.Logger.Error("failed to filter pub metadata", "package", name, "error", err) + http.Error(w, "failed to filter package metadata", http.StatusBadGateway) + return + } h.proxy.Logger.Warn("failed to rewrite metadata, proxying original", "error", err) w.Header().Set(headerContentType, "application/json") w.WriteHeader(http.StatusOK) @@ -201,7 +285,7 @@ func (h *PubHandler) shouldFilterVersion(packagePURL, name, version string, vmap return false } - if !h.proxy.Cooldown.IsAllowed("pub", packagePURL, publishedAt) { + if !h.proxy.cooldown().IsAllowed("pub", packagePURL, publishedAt) { h.proxy.Logger.Info("cooldown: filtering pub version", "package", name, "version", version) return true @@ -210,32 +294,47 @@ func (h *PubHandler) shouldFilterVersion(packagePURL, name, version string, vmap return false } -// updateLatestVersion updates the latest field if the current latest version -// was removed by cooldown filtering. +// updateLatestVersion points latest at the kept entry for its version, so +// its archive_url is the proxy's too. When cooldown removed that version, +// latest becomes the newest stable version left, or the newest version left +// if all are prereleases, and is dropped when none is left. func (h *PubHandler) updateLatestVersion(metadata map[string]any, filtered []any) { - if h.proxy.Cooldown == nil || !h.proxy.Cooldown.Enabled() { - return - } - latest, ok := metadata["latest"].(map[string]any) if !ok { return } + latestVer, _ := latest["version"].(string) - latestVer, ok := latest["version"].(string) - if !ok { - return - } - + var newest, newestStable *semver.Version + var newestEntry, newestStableEntry any for _, vdata := range filtered { - if vmap, ok := vdata.(map[string]any); ok { - if vmap["version"] == latestVer { - return - } + vmap, ok := vdata.(map[string]any) + if !ok { + continue + } + version, _ := vmap["version"].(string) + if version == latestVer { + latest["archive_url"] = vmap["archive_url"] + return + } + parsed, err := semver.NewVersion(version) + if err != nil { + continue + } + if newest == nil || parsed.GreaterThan(newest) { + newest, newestEntry = parsed, vdata + } + if parsed.Prerelease() == "" && (newestStable == nil || parsed.GreaterThan(newestStable)) { + newestStable, newestStableEntry = parsed, vdata } } - if len(filtered) > 0 { - metadata["latest"] = filtered[len(filtered)-1] + switch { + case newestStableEntry != nil: + metadata["latest"] = newestStableEntry + case newestEntry != nil: + metadata["latest"] = newestEntry + default: + delete(metadata, "latest") } } diff --git a/internal/handler/pub_test.go b/internal/handler/pub_test.go index 8a4c098..5311e25 100644 --- a/internal/handler/pub_test.go +++ b/internal/handler/pub_test.go @@ -2,11 +2,16 @@ package handler import ( "encoding/json" + "io" "log/slog" + "net/http" + "net/http/httptest" + "strings" "testing" "time" "github.com/git-pkgs/cooldown" + "github.com/git-pkgs/registries/fetch" ) func TestPubRewriteMetadata(t *testing.T) { @@ -92,3 +97,167 @@ func TestPubRewriteMetadataCooldown(t *testing.T) { t.Errorf("latest version = %v, want 1.0.0", latest["version"]) } } + +// Without the .tar.gz suffix pub.dev answers with the HTML version page, which +// would otherwise be cached under the archive's key. +func TestPubDownloadRequiresArchiveSuffix(t *testing.T) { + proxy, db, _, fetcher := setupTestProxy(t) + fetcher.artifact = &fetch.Artifact{ + Body: io.NopCloser(strings.NewReader("version page")), + ContentType: "text/html", + } + h := NewPubHandlerWithUpstream(proxy, "http://localhost", "https://pub.example.com") + + req := httptest.NewRequest(http.MethodGet, "/packages/http/versions/1.2.0", nil) + w := httptest.NewRecorder() + h.Routes().ServeHTTP(w, req) + + if w.Code != http.StatusNotFound { + t.Errorf("status = %d, want %d", w.Code, http.StatusNotFound) + } + if fetcher.fetchCalled { + t.Errorf("upstream fetched %q", fetcher.fetchedURL) + } + art, err := db.GetArtifact("pkg:pub/http@1.2.0", "http-1.2.0.tar.gz") + if err != nil { + t.Fatalf("GetArtifact: %v", err) + } + if art != nil { + t.Errorf("artifact cached from %q", art.UpstreamURL) + } +} + +func TestPubDownloadRejectsEncodedQueryInName(t *testing.T) { + proxy, _, _, fetcher := setupTestProxy(t) + fetcher.artifact = &fetch.Artifact{ + Body: io.NopCloser(strings.NewReader("archive")), + ContentType: "application/octet-stream", + } + h := NewPubHandlerWithUpstream(proxy, "http://localhost", "https://pub.example.com") + + for _, path := range []string{ + "/packages/http%3Fx/versions/1.2.0.tar.gz", + "/packages/http%23x/versions/1.2.0.tar.gz", + "/packages/http/versions/1.2.0%3Fx.tar.gz", + } { + fetcher.fetchCalled = false + fetcher.fetchedURL = "" + req := httptest.NewRequest(http.MethodGet, path, nil) + w := httptest.NewRecorder() + h.Routes().ServeHTTP(w, req) + + if strings.ContainsAny(fetcher.fetchedURL, "?#") { + t.Errorf("%s: upstream URL %q carries a query or fragment", path, fetcher.fetchedURL) + } + if strings.Contains(path, "/http%") && fetcher.fetchCalled { + t.Errorf("%s: invalid package name reached upstream as %q", path, fetcher.fetchedURL) + } + } +} + +// Older versions cached the HTML version page as the archive. Such an entry +// is fetched again instead of being served. +func TestPubDownloadRefetchesCachedVersionPage(t *testing.T) { + proxy, db, store, fetcher := setupTestProxy(t) + seedPackage(t, db, store, "pub", "http", "1.2.0", "http-1.2.0.tar.gz", "version page") + art, err := db.GetArtifact("pkg:pub/http@1.2.0", "http-1.2.0.tar.gz") + if err != nil || art == nil { + t.Fatalf("GetArtifact: %v", err) + } + art.UpstreamURL = "https://pub.dev/packages/http/versions/1.2.0" + if err := db.UpsertArtifact(art); err != nil { + t.Fatalf("UpsertArtifact: %v", err) + } + fetcher.artifact = &fetch.Artifact{ + Body: io.NopCloser(strings.NewReader("archive")), + ContentType: "application/octet-stream", + } + h := NewPubHandlerWithUpstream(proxy, "http://localhost", "https://pub.example.com") + + req := httptest.NewRequest(http.MethodGet, "/packages/http/versions/1.2.0.tar.gz", nil) + w := httptest.NewRecorder() + h.Routes().ServeHTTP(w, req) + + if !fetcher.fetchCalled { + t.Fatal("cached version page was served without fetching upstream") + } + if got := w.Body.String(); got != "archive" { + t.Errorf("body = %q, want %q", got, "archive") + } +} + +func TestPubDownloadServesCachedArchive(t *testing.T) { + proxy, db, store, fetcher := setupTestProxy(t) + seedPackage(t, db, store, "pub", "http", "1.2.0", "http-1.2.0.tar.gz", "cached archive") + fetcher.artifact = &fetch.Artifact{ + Body: io.NopCloser(strings.NewReader("refetched")), + ContentType: "application/octet-stream", + } + h := NewPubHandlerWithUpstream(proxy, "http://localhost", "https://pub.example.com") + + req := httptest.NewRequest(http.MethodGet, "/packages/http/versions/1.2.0.tar.gz", nil) + w := httptest.NewRecorder() + h.Routes().ServeHTTP(w, req) + + if fetcher.fetchCalled { + t.Errorf("cached archive fetched again from %q", fetcher.fetchedURL) + } + if got := w.Body.String(); got != "cached archive" { + t.Errorf("body = %q, want %q", got, "cached archive") + } +} + +// TestPubRewriteMetadataLatest checks that latest points at the proxy and +// never names a version cooldown holds back, and that a held back latest is +// replaced with the newest stable version left. +func TestPubRewriteMetadataLatest(t *testing.T) { + old := time.Now().Add(-10 * 24 * time.Hour).Format(time.RFC3339) + recent := time.Now().Add(-time.Hour).Format(time.RFC3339) + entry := func(version, published string) string { + return `{"version":"` + version + `","published":"` + published + `","archive_url":"https://pub.dev/packages/demo/versions/` + version + `.tar.gz"}` + } + for _, tc := range []struct { + name, latest, versions string + cooldown bool + want, wantURL string + }{ + {"kept", entry("1.0.0", old), entry("1.0.0", old), false, "1.0.0", + "http://localhost:8080/pub/packages/demo/versions/1.0.0.tar.gz"}, + {"stable over prerelease", entry("2.0.0", recent), + entry("1.0.0", old) + "," + entry("1.1.0", old) + "," + entry("2.0.0-dev.1", old) + "," + entry("2.0.0", recent), true, "1.1.0", + "http://localhost:8080/pub/packages/demo/versions/1.1.0.tar.gz"}, + {"only prereleases", entry("2.0.0", recent), entry("2.0.0-dev.1", old) + "," + entry("2.0.0", recent), true, "2.0.0-dev.1", + "http://localhost:8080/pub/packages/demo/versions/2.0.0-dev.1.tar.gz"}, + {"all held back", entry("2.0.0", recent), entry("2.0.0", recent), true, "", ""}, + } { + t.Run(tc.name, func(t *testing.T) { + proxy := &Proxy{Logger: slog.Default()} + if tc.cooldown { + proxy.Cooldown = &cooldown.Config{Default: "3d"} + } + h := &PubHandler{proxy: proxy, proxyURL: "http://localhost:8080"} + output, err := h.rewriteMetadata("demo", []byte(`{"name":"demo","latest":`+tc.latest+`,"versions":[`+tc.versions+`]}`)) + if err != nil { + t.Fatal(err) + } + var result struct { + Latest *struct { + Version string `json:"version"` + ArchiveURL string `json:"archive_url"` + } `json:"latest"` + } + if err := json.Unmarshal(output, &result); err != nil { + t.Fatal(err) + } + if tc.want == "" { + if result.Latest != nil { + t.Errorf("latest = %+v, want none", *result.Latest) + } + return + } + if result.Latest == nil || result.Latest.Version != tc.want || result.Latest.ArchiveURL != tc.wantURL { + t.Errorf("latest = %+v, want %s at %s", result.Latest, tc.want, tc.wantURL) + } + }) + } +} diff --git a/internal/handler/pypi.go b/internal/handler/pypi.go index 513f507..21e4374 100644 --- a/internal/handler/pypi.go +++ b/internal/handler/pypi.go @@ -1,14 +1,19 @@ package handler import ( + "bytes" "crypto/sha256" "encoding/hex" "encoding/json" "errors" "fmt" + "io" + "maps" "mime" "net/http" + "net/url" "regexp" + "slices" "strconv" "strings" "time" @@ -40,11 +45,10 @@ const ( // PyPIHandler handles PyPI registry protocol requests. type PyPIHandler struct { - proxy *Proxy - upstreamURL string - downloadURL string - downloadHrefRe *regexp.Regexp - proxyURL string + proxy *Proxy + upstreamURL string + downloadURL string + proxyURL string } // PyPI files are stored under pkg:pypi/{name}, the name taken from the @@ -56,11 +60,6 @@ func init() { retention.Default.Register(retention.Spec{Key: "pypi", CanonicalPackage: retention.DefaultCanonical("pypi")}) } -// NewPyPIHandler creates a new PyPI protocol handler. -func NewPyPIHandler(proxy *Proxy, proxyURL string) *PyPIHandler { - return NewPyPIHandlerWithUpstreams(proxy, proxyURL, "", "") -} - // NewPyPIHandlerWithUpstreams creates a PyPI handler with custom API and // package download upstreams. func NewPyPIHandlerWithUpstreams(proxy *Proxy, proxyURL, upstreamURL, downloadURL string) *PyPIHandler { @@ -70,7 +69,6 @@ func NewPyPIHandlerWithUpstreams(proxy *Proxy, proxyURL, upstreamURL, downloadUR downloadURL: configuredUpstreamURL(downloadURL, pypiDownloadUpstream), proxyURL: strings.TrimSuffix(proxyURL, "/"), } - h.downloadHrefRe = regexp.MustCompile(`href="(` + regexp.QuoteMeta(h.downloadURL) + `/packages/[^"]+)"`) return h } @@ -89,7 +87,7 @@ func (h *PyPIHandler) Routes() http.Handler { // Package downloads (cache these) mux.HandleFunc("GET /packages/{path...}", h.handleDownload) - return mux + return rejectQueryChars(mux) } // handleSimpleIndex serves the simple API index. @@ -106,14 +104,30 @@ func (h *PyPIHandler) handleSimplePackage(w http.ResponseWriter, r *http.Request return } - h.proxy.Logger.Info("pypi simple request", "package", name) + h.proxy.Logger.Debug("pypi simple request", "package", name) upstreamURL := fmt.Sprintf("%s/simple/%s/", h.upstreamURL, name) accept := selectPyPISimpleRepresentation(r.Header.Get("Accept")) cacheKey := pypiSimpleCacheKey(name, accept) - body, contentType, err := h.proxy.FetchOrCacheMetadata(r.Context(), "pypi", cacheKey, upstreamURL, accept) - if err != nil { + // Rewritten pages go through the rewrite cache, keyed by the upstream + // page, its content type and the versions filtered out. Without cooldown + // the filtered versions are known up front, so a repeat request can be + // answered without reading the stored page. + cooldown := h.proxy.cooldownApplies("pypi", name) + if !cooldown { + denied := h.addDeniedVersions(name, nil) + if stored, contentType, ok := h.proxy.storedRewriteVariant("pypi", cacheKey, h.proxyURL, cacheKey, func(contentType string) []string { + return simpleRewriteVariant(contentType, denied) + }); ok { + ensureVaryAccept(w.Header()) + serveRewrittenMetadataAs(w, r, stored, contentType) + return + } + } + + upstream := h.proxy.fetchMetadataDocument(r.Context(), "pypi", cacheKey, upstreamURL, accept, nil) + if err := upstream.err; err != nil { if errors.Is(err, ErrUpstreamNotFound) { http.Error(w, "not found", http.StatusNotFound) return @@ -125,39 +139,70 @@ func (h *PyPIHandler) handleSimplePackage(w http.ResponseWriter, r *http.Request http.Error(w, "upstream request failed", http.StatusBadGateway) return } + contentType := upstream.contentType - // When cooldown is enabled, fetch JSON metadata to get version timestamps + // When cooldown applies, fetch JSON metadata to get version timestamps var filteredVersions map[string]bool - if h.proxy.Cooldown != nil && h.proxy.Cooldown.Enabled() { - filteredVersions = h.fetchFilteredVersions(r, name) - } - for version := range h.proxy.Denylist.Versions(canonicalPackagePURL("pypi", name)) { - if filteredVersions == nil { - filteredVersions = make(map[string]bool) - } - filteredVersions[version] = true - } - - var rewritten []byte - if isJSONMediaType(contentType) { - rewritten, err = h.rewriteSimpleJSON(body, filteredVersions) + if cooldown { + var err error + filteredVersions, err = h.fetchFilteredVersions(r, name) if err != nil { - if len(h.proxy.Denylist.Versions(canonicalPackagePURL("pypi", name))) != 0 { - http.Error(w, "failed to filter package metadata", http.StatusBadGateway) - return - } - h.proxy.Logger.Warn("failed to rewrite pypi simple json, proxying original", "error", err) - rewritten = body + h.proxy.writeCooldownLookupError(w, "pypi", name, err) + return + } + } + filteredVersions = h.addDeniedVersions(name, filteredVersions) + + isJSON := isJSONMediaType(contentType) + digest := variantDigest(upstream.digest, upstream.body, simpleRewriteVariant(contentType, filteredVersions)...) + rewritten, err := h.proxy.cachedRewrite(r.Context(), "pypi", h.proxyURL, cacheKey, upstream.body, digest, func(body []byte) ([]byte, []string, error) { + if isJSON { + out, err := h.rewriteSimpleJSON(body, filteredVersions) + return out, nil, err } - } else { body = h.filterSimpleHTMLLinks(body, filteredVersions) - rewritten = h.rewriteSimpleHTML(body, filteredVersions) + return h.rewriteSimpleHTML(body, filteredVersions), nil, nil + }) + if err != nil { + if r.Context().Err() != nil { + return // the client left while waiting on a shared rewrite + } + if len(filteredVersions) != 0 { + h.proxy.Logger.Error("failed to filter pypi simple json", "package", name, "error", err) + http.Error(w, "failed to filter package metadata", http.StatusBadGateway) + return + } + h.proxy.Logger.Warn("failed to rewrite pypi simple json, proxying original", "error", err) + w.Header().Set(headerContentType, contentType) + ensureVaryAccept(w.Header()) + markStale(w, upstream.stale) + w.WriteHeader(http.StatusOK) + _, _ = w.Write(upstream.body) + return } - w.Header().Set(headerContentType, contentType) ensureVaryAccept(w.Header()) - w.WriteHeader(http.StatusOK) - _, _ = w.Write(rewritten) + markStale(w, upstream.stale) + serveRewrittenMetadataAs(w, r, rewritten, contentType) +} + +// addDeniedVersions adds the package's denylisted versions to filtered, +// allocating it when there are any and it is nil. +func (h *PyPIHandler) addDeniedVersions(name string, filtered map[string]bool) map[string]bool { + for version := range h.proxy.Denylist.Versions(canonicalPackagePURL("pypi", name)) { + if filtered == nil { + filtered = make(map[string]bool) + } + filtered[version] = true + } + return filtered +} + +// simpleRewriteVariant returns what a simple page rewrite depends on besides +// the upstream page: its content type, which picks the HTML or JSON rewrite, +// and the versions filtered out. +func simpleRewriteVariant(contentType string, filtered map[string]bool) []string { + return append([]string{contentType}, slices.Sorted(maps.Keys(filtered))...) } func selectPyPISimpleRepresentation(accept string) string { @@ -258,67 +303,102 @@ func isJSONMediaType(contentType string) bool { } func ensureVaryAccept(header http.Header) { - for _, value := range header.Values("Vary") { - for field := range strings.SplitSeq(value, ",") { - if strings.EqualFold(strings.TrimSpace(field), "Accept") { - return - } - } - } - header.Add("Vary", "Accept") + ensureVary(header, "Accept") } -// fetchFilteredVersions fetches JSON metadata and returns a set of version strings -// that should be filtered out due to cooldown. -func (h *PyPIHandler) fetchFilteredVersions(r *http.Request, name string) map[string]bool { - jsonURL := fmt.Sprintf("%s/pypi/%s/json", h.upstreamURL, name) - - body, _, err := h.proxy.FetchOrCacheMetadata(r.Context(), "pypi", name+"/json", jsonURL) +// fetchFilteredVersions fetches JSON metadata and returns a set of version +// strings that should be filtered out due to cooldown. A package the JSON API +// doesn't know has no publish times to go by and gets an empty set; any other +// failure to read them is an error. +func (h *PyPIHandler) fetchFilteredVersions(r *http.Request, name string) (map[string]bool, error) { + times, err := h.fetchReleaseTimes(r, name) if err != nil { - return nil - } - - var metadata map[string]any - if err := json.Unmarshal(body, &metadata); err != nil { - return nil - } - - releases, ok := metadata["releases"].(map[string]any) - if !ok { - return nil + return nil, err } packagePURL := canonicalPackagePURL("pypi", name) filtered := make(map[string]bool) - for version, files := range releases { - filesArr, ok := files.([]any) - if !ok { - continue - } - publishedAt := h.newestUploadTime(filesArr) - if !publishedAt.IsZero() && !h.proxy.Cooldown.IsAllowed("pypi", packagePURL, publishedAt) { + for version, publishedAt := range times { + if !publishedAt.IsZero() && !h.proxy.cooldown().IsAllowed("pypi", packagePURL, publishedAt) { filtered[version] = true } } if len(filtered) == 0 { - return nil + return nil, nil } - return filtered + return filtered, nil } +// fetchReleaseTimes reads the JSON API and returns each release's newest +// upload time, zero for a release without one. A package the JSON API +// doesn't know gets nil; any other failure is an error. +func (h *PyPIHandler) fetchReleaseTimes(r *http.Request, name string) (map[string]time.Time, error) { + jsonURL := fmt.Sprintf("%s/pypi/%s/json", h.upstreamURL, name) + + body, _, err := h.proxy.FetchOrCacheMetadata(r.Context(), "pypi", name+"/json", jsonURL) + if errors.Is(err, ErrUpstreamNotFound) { + return nil, nil + } + if err != nil { + return nil, err + } + + return h.parseReleaseTimes(body) +} + +// pypiReleaseFiles is the part of a JSON API document the release times are +// read from. Decoding into it skips every other field, where a generic +// map would hold the whole document, several times its size, in memory. +type pypiReleaseFiles struct { + Releases map[string][]struct { + UploadTime string `json:"upload_time_iso_8601"` + } `json:"releases"` +} + +// parseReleaseTimes returns each release's newest upload time from a JSON +// API document, zero for a release without one. +func (h *PyPIHandler) parseReleaseTimes(body []byte) (map[string]time.Time, error) { + var metadata pypiReleaseFiles + // A value of another type than expected is skipped and the rest is + // still decoded, so a file entry without a usable time doesn't count. + var mismatch *json.UnmarshalTypeError + if err := json.Unmarshal(body, &metadata); err != nil && !errors.As(err, &mismatch) { + return nil, fmt.Errorf("parsing pypi json metadata: %w", err) + } + if metadata.Releases == nil { + return nil, errors.New("pypi json metadata has no releases") + } + + times := make(map[string]time.Time, len(metadata.Releases)) + for version, files := range metadata.Releases { + var newest time.Time + for _, file := range files { + if t, err := time.Parse(time.RFC3339, file.UploadTime); err == nil && t.After(newest) { + newest = t + } + } + times[version] = newest + } + return times, nil +} + +var ( + // simpleLinkRe matches a whole anchor tag: filename. + simpleLinkRe = regexp.MustCompile(`]+href="[^"]*"[^>]*>[^<]+`) + // simpleLinkTextRe captures an anchor's text. + simpleLinkTextRe = regexp.MustCompile(`>([^<]+)`) +) + // rewriteSimpleHTML rewrites package URLs in simple API HTML to point at this proxy. // If filteredVersions is non-nil, links for those versions are removed entirely. func (h *PyPIHandler) rewriteSimpleHTML(body []byte, filteredVersions map[string]bool) []byte { // If cooldown filtering is active, remove entire tags for filtered versions if len(filteredVersions) > 0 { - // Match full anchor tags: filename - linkRe := regexp.MustCompile(`]+href="[^"]*"[^>]*>[^<]+`) - body = linkRe.ReplaceAllFunc(body, func(match []byte) []byte { + body = simpleLinkRe.ReplaceAllFunc(body, func(match []byte) []byte { // Extract filename from between tags - innerRe := regexp.MustCompile(`>([^<]+)`) - innerMatch := innerRe.FindSubmatch(match) + innerMatch := simpleLinkTextRe.FindSubmatch(match) if len(innerMatch) < minSubmatchParts { return match } @@ -331,18 +411,49 @@ func (h *PyPIHandler) rewriteSimpleHTML(body []byte, filteredVersions map[string }) } - // Match href attributes pointing to packages on the configured download host. - return h.downloadHrefRe.ReplaceAllFunc(body, func(match []byte) []byte { - submatch := h.downloadHrefRe.FindSubmatch(match) - if len(submatch) < minSubmatchParts { - return match + return h.rewriteDownloadHrefs(body) +} + +// rewriteDownloadHrefs points href attributes for files on the configured +// download host at the proxy. It makes the same replacements as the regular +// expression `href="(/packages/[^"]+)"` would: an href +// whose URL starts with the download host's /packages/ and has at least one +// more character before the closing quote. Finding the literal prefix is many +// times faster than running the regular expression over every link. +func (h *PyPIHandler) rewriteDownloadHrefs(body []byte) []byte { + from := []byte(`href="` + h.downloadURL + `/packages/`) + // The download route is /pypi/packages/{path...} and keeps the path + // from the download host, /packages/ included. + to := []byte(`href="` + h.proxyURL + `/pypi/packages/packages/`) + + var out []byte + done := 0 // body[:done] is in out already + for search := 0; ; { + i := bytes.Index(body[search:], from) + if i < 0 { + break } - - origURL := string(submatch[1]) - - newURL := h.proxyURL + "/pypi/packages" + strings.TrimPrefix(origURL, h.downloadURL) - return []byte(fmt.Sprintf(`href="%s"`, newURL)) - }) + start := search + i + rest := start + len(from) + end := bytes.IndexByte(body[rest:], '"') + if end <= 0 { + // No closing quote, or nothing before it: not a match. The + // regular expression would go on looking from the next byte. + search = start + 1 + continue + } + if out == nil { + out = make([]byte, 0, len(body)+len(body)/8) + } + out = append(out, body[done:start]...) + out = append(out, to...) + done = rest + search = rest + end + 1 + } + if out == nil { + return body + } + return append(out, body[done:]...) } func (h *PyPIHandler) rewriteSimpleJSON(body []byte, filteredVersions map[string]bool) ([]byte, error) { @@ -376,6 +487,19 @@ func (h *PyPIHandler) rewriteSimpleJSON(body []byte, filteredVersions map[string } metadata["files"] = rewrittenFiles + + // The versions list (PEP 700) loses the filtered versions too, whose + // files were all left out above. + if versions, ok := metadata["versions"].([]any); ok && len(filteredVersions) > 0 { + keptVersions := make([]any, 0, len(versions)) + for _, v := range versions { + if version, ok := v.(string); ok && filteredVersions[version] { + continue + } + keptVersions = append(keptVersions, v) + } + metadata["versions"] = keptVersions + } return json.Marshal(metadata) } @@ -387,7 +511,7 @@ func (h *PyPIHandler) handleJSON(w http.ResponseWriter, r *http.Request) { return } - h.proxy.Logger.Info("pypi json request", "package", name) + h.proxy.Logger.Debug("pypi json request", "package", name) upstreamURL := fmt.Sprintf("%s/pypi/%s/json", h.upstreamURL, name) h.proxyAndRewriteJSON(w, r, upstreamURL, name+"/json") @@ -407,16 +531,22 @@ func (h *PyPIHandler) handleVersionJSON(w http.ResponseWriter, r *http.Request) return } - h.proxy.Logger.Info("pypi version json request", "package", name, "version", version) + h.proxy.Logger.Debug("pypi version json request", "package", name, "version", version) upstreamURL := fmt.Sprintf("%s/pypi/%s/%s/json", h.upstreamURL, name, version) h.proxyAndRewriteJSON(w, r, upstreamURL, name+"/"+version) } // proxyAndRewriteJSON fetches JSON metadata and rewrites download URLs. +// Rewrites go through the rewrite cache, as for npm. func (h *PyPIHandler) proxyAndRewriteJSON(w http.ResponseWriter, r *http.Request, upstreamURL, cacheKey string) { - body, _, err := h.proxy.FetchOrCacheMetadata(r.Context(), "pypi", cacheKey, upstreamURL) - if err != nil { + if stored, ok := h.proxy.storedRewrite("pypi", cacheKey, h.proxyURL, cacheKey); ok { + serveRewrittenMetadata(w, r, stored) + return + } + + upstream := h.proxy.fetchMetadataDocument(r.Context(), "pypi", cacheKey, upstreamURL, contentTypeJSON, nil) + if err := upstream.err; err != nil { if errors.Is(err, ErrUpstreamNotFound) { http.Error(w, "not found", http.StatusNotFound) return @@ -429,28 +559,35 @@ func (h *PyPIHandler) proxyAndRewriteJSON(w http.ResponseWriter, r *http.Request return } - rewritten, err := h.rewriteJSONMetadata(body) + rewritten, err := h.proxy.cachedRewrite(r.Context(), "pypi", h.proxyURL, cacheKey, upstream.body, upstream.digest, h.rewriteJSONMetadata) if err != nil { - if len(h.proxy.Denylist.Versions(canonicalPackagePURL("pypi", r.PathValue("name")))) != 0 { + if r.Context().Err() != nil { + return // the client left while waiting on a shared rewrite + } + if h.proxy.mustFilterMetadata("pypi", r.PathValue("name")) { + h.proxy.Logger.Error("failed to filter pypi metadata", "url", upstreamURL, "error", err) http.Error(w, "failed to filter package metadata", http.StatusBadGateway) return } h.proxy.Logger.Warn("failed to rewrite metadata, proxying original", "error", err) + markStale(w, upstream.stale) w.Header().Set(headerContentType, "application/json") - _, _ = w.Write(body) + _, _ = w.Write(upstream.body) return } - w.Header().Set(headerContentType, "application/json") - _, _ = w.Write(rewritten) + markStale(w, upstream.stale) + serveRewrittenMetadata(w, r, rewritten) } // rewriteJSONMetadata rewrites download URLs in PyPI JSON metadata. // If cooldown is enabled, versions published too recently are filtered out. -func (h *PyPIHandler) rewriteJSONMetadata(body []byte) ([]byte, error) { +// It also returns what it kept: the releases, and the current version's files +// unless they were dropped. +func (h *PyPIHandler) rewriteJSONMetadata(body []byte) ([]byte, []string, error) { var metadata map[string]any if err := json.Unmarshal(body, &metadata); err != nil { - return nil, err + return nil, nil, err } packageName, _ := extractPyPIName(metadata) @@ -462,7 +599,17 @@ func (h *PyPIHandler) rewriteJSONMetadata(body []byte) ([]byte, error) { h.filterAndRewriteReleases(metadata, packageName, packagePURL) h.filterAndRewriteURLs(metadata, packagePURL) - return json.Marshal(metadata) + var kept []string + if releases, ok := metadata["releases"].(map[string]any); ok { + kept = slices.Collect(maps.Keys(releases)) + } + if urls, ok := metadata["urls"].([]any); ok && len(urls) > 0 { + // Not a valid release key, so it can't be confused with one. + kept = append(kept, "\x00urls") + } + + out, err := json.Marshal(metadata) + return out, kept, err } // filterAndRewriteReleases applies cooldown filtering and URL rewriting to the @@ -497,7 +644,7 @@ func (h *PyPIHandler) shouldFilterRelease(packagePURL string, files any) bool { } publishedAt := h.newestUploadTime(filesArr) - return !publishedAt.IsZero() && !h.proxy.Cooldown.IsAllowed("pypi", packagePURL, publishedAt) + return !publishedAt.IsZero() && !h.proxy.cooldown().IsAllowed("pypi", packagePURL, publishedAt) } // versionInCooldown reports whether a version is still inside the cooldown @@ -506,13 +653,66 @@ func (h *PyPIHandler) shouldFilterRelease(packagePURL string, files any) bool { // path without ever reading the index. // // A release whose upload time cannot be determined is allowed through, matching -// how fetchFilteredVersions treats it. -func (h *PyPIHandler) versionInCooldown(r *http.Request, name, version string) bool { - if h.proxy.Cooldown == nil || !h.proxy.Cooldown.Enabled() { - return false +// how fetchFilteredVersions treats it. Failing to read the times is an error. +// The time read is stored for storedCooldown. +func (h *PyPIHandler) versionInCooldown(r *http.Request, name, version string) (bool, error) { + if !h.proxy.cooldownApplies("pypi", name) { + return false, nil } - return h.fetchFilteredVersions(r, name)[version] + times, err := h.fetchReleaseTimes(r, name) + if err != nil { + return false, err + } + publishedAt := times[version] + if publishedAt.IsZero() { + return false, nil + } + h.storeUploadTime(name, version, publishedAt) + return !h.proxy.cooldown().IsAllowed("pypi", canonicalPackagePURL("pypi", name), publishedAt), nil +} + +// storeUploadTime records a release's newest upload time under the version +// PURL the file is cached under, so storedCooldown finds it. +func (h *PyPIHandler) storeUploadTime(name, version string, publishedAt time.Time) { + if h.proxy.DB == nil { + return + } + packagePURL, versionPURL, err := packagePURLStrings("pypi", name, version) + if err != nil { + return + } + if err := h.proxy.DB.SetVersionPublishedAt(versionPURL, packagePURL, publishedAt); err != nil { + h.proxy.Logger.Warn("cooldown: could not store pypi upload time", + "package", name, "version", version, "error", err) + } +} + +// storedCooldown answers the cooldown check for a download from the upload +// time stored for its release, without reading the JSON API, and reports +// whether it could. A release's time is its newest file's, and files can be +// added to a release later, so the stored time only ever moves forward: +// - a stored time inside the window withholds every file of the release; +// - a stored time outside it only lets through a file that is already +// cached. A file that is not cached may be one uploaded since, so it goes +// to the JSON API, which also stores the release's current time. +func (h *PyPIHandler) storedCooldown(r *http.Request, name, version, filename string) (inCooldown, answered bool) { + if h.proxy.DB == nil || !h.proxy.cooldownApplies("pypi", name) { + return false, false + } + packagePURL, versionPURL, err := packagePURLStrings("pypi", name, version) + if err != nil { + return false, false + } + ver, err := h.proxy.DB.GetVersionByPURL(versionPURL) + if err != nil || ver == nil || !ver.PublishedAt.Valid { + return false, false + } + if !h.proxy.cooldown().IsAllowed("pypi", packagePURL, ver.PublishedAt.Time) { + return true, true + } + cached, err := h.proxy.HasCachedArtifact(r.Context(), "pypi", name, version, filename) + return false, err == nil && cached } // rewriteFileEntries rewrites URLs in a list of file entries. @@ -617,11 +817,24 @@ func (h *PyPIHandler) handleDownload(w http.ResponseWriter, r *http.Request) { filename := parts[len(parts)-1] name, version := h.parseFilename(filename) - if name != "" && h.versionInCooldown(r, name, version) { - h.proxy.Logger.Info("cooldown: withholding pypi file", - "name", name, "version", version, "filename", filename) - http.Error(w, "not found", http.StatusNotFound) - return + if name != "" { + inCooldown, answered := h.storedCooldown(r, name, version, filename) + var err error + if !answered { + inCooldown, err = h.versionInCooldown(r, name, version) + } + if err != nil { + if !h.proxy.serveCachedDespiteCooldownError(w, r, "pypi", name, version, filename, err) { + h.proxy.writeCooldownLookupError(w, "pypi", name, err) + } + return + } + if inCooldown { + h.proxy.Logger.Info("cooldown: withholding pypi file", + "name", name, "version", version, "filename", filename) + http.Error(w, "not found", http.StatusNotFound) + return + } } if name == "" { @@ -630,7 +843,7 @@ func (h *PyPIHandler) handleDownload(w http.ResponseWriter, r *http.Request) { version = "0" } - h.proxy.Logger.Info("pypi download request", + h.proxy.Logger.Debug("pypi download request", "name", name, "version", version, "filename", filename) // The path value starts with 'packages/' (no leading slash), so add @@ -654,13 +867,19 @@ var archiveExtensions = []string{".tar.gz", ".tar.bz2", ".tar.xz", ".tar.Z", ".t // bdist_msi formats, which share a filename layout. var windowsInstallerExtensions = []string{".exe", ".msi"} -// parseFilename extracts package name and version from a PyPI filename. -// Handles wheels, sdists and legacy bdist formats: +func (h *PyPIHandler) parseFilename(filename string) (name, version string) { + return PyPIFilenameIdentity(filename) +} + +// PyPIFilenameIdentity extracts the package name and version a PyPI file is +// cached under from its filename, so proxy mirror stores files where the +// download handler looks for them. Handles wheels, sdists and legacy bdist +// formats: // - requests-2.31.0-py3-none-any.whl // - requests-2.31.0.tar.gz // - numpy-1.8.0-py2.7-macosx-10.9-x86_64.egg // - numpy-1.8.0.win32-py2.7.exe -func (h *PyPIHandler) parseFilename(filename string) (name, version string) { +func PyPIFilenameIdentity(filename string) (name, version string) { // PEP 658/714 core-metadata sidecars are the distribution filename plus // ".metadata"; they describe the same name and version. Without this, pip's // metadata-only fetches fall back to a hash-derived package identifier. @@ -836,8 +1055,119 @@ func (h *PyPIHandler) proxySimple(w http.ResponseWriter, r *http.Request, path s } defer func() { _ = resp.Body.Close() }() + // The HTML root index links projects by absolute path, such as + // /simple//, which must point at the proxy's /pypi mount instead. + // It is large, so it is rewritten as it streams. + if resp.StatusCode == http.StatusOK && resp.Header.Get("Content-Encoding") == "" && + !strings.Contains(resp.Header.Get(headerContentType), "json") { + prefix := "/simple/" + if u, err := url.Parse(h.upstreamURL); err == nil { + prefix = strings.TrimSuffix(u.Path, "/") + prefix + } + to := h.proxyURL + "/pypi/simple/" + resp.Body = &replacingReader{ + src: resp.Body, + replacements: []replacement{ + {from: []byte(`href="` + prefix), to: []byte(`href="` + to)}, + {from: []byte(`href='` + prefix), to: []byte(`href='` + to)}, + }, + } + resp.Header.Del(headerContentLength) + resp.Header.Del("ETag") // it names the upstream body + resp.ContentLength = -1 + } + h.proxy.relayResponse(w, r, resp, func(dst, src http.Header) { copyRelayHeaders(dst, src) ensureVaryAccept(dst) }) } + +const replacingReaderBufferSize = 32 << 10 + +// replacingReader makes each replacement in src as it is read. +type replacingReader struct { + src io.ReadCloser + replacements []replacement + in []byte // read from src, not yet scanned + out []byte // scanned, not yet returned + buf []byte + err error +} + +type replacement struct{ from, to []byte } + +func (r *replacingReader) Read(p []byte) (int, error) { + for len(r.out) == 0 { + if r.err != nil { + return 0, r.err + } + if r.buf == nil { + r.buf = make([]byte, replacingReaderBufferSize) + } + n, err := r.src.Read(r.buf) + r.in = append(r.in, r.buf[:n]...) + r.err = err + // Keep a tail that could be the start of a match split across reads. + keep := 0 + if err == nil { + for _, rep := range r.replacements { + keep = max(keep, len(rep.from)-1) + } + } + scan := max(len(r.in)-keep, 0) + out, done := r.replace(scan) + if done < scan { + out = append(out, r.in[done:scan]...) + done = scan + } + r.out = out + r.in = append([]byte(nil), r.in[done:]...) + } + n := copy(p, r.out) + r.out = r.out[n:] + return n, nil +} + +// replace makes the replacements that start before scan in r.in, returning +// the output and how much of r.in it covers. +func (r *replacingReader) replace(scan int) (out []byte, done int) { + // at holds each replacement's next match at or after done, or -1. + // Only a match the last replacement consumed is searched for again, + // so each pass over r.in stays linear. + at := make([]int, len(r.replacements)) + for i := range at { + at[i] = indexFrom(r.in, r.replacements[i].from, 0) + } + for { + k := -1 + for i, j := range at { + if j >= 0 && (k < 0 || j < at[k]) { + k = i + } + } + if k < 0 || at[k] >= scan { + break + } + rep := &r.replacements[k] + out = append(out, r.in[done:at[k]]...) + out = append(out, rep.to...) + done = at[k] + len(rep.from) + for i, j := range at { + if j >= 0 && j < done { + at[i] = indexFrom(r.in, r.replacements[i].from, done) + } + } + } + return out, done +} + +func (r *replacingReader) Close() error { return r.src.Close() } + +// indexFrom returns the index of the first sep in b at or after from, or -1. +func indexFrom(b, sep []byte, from int) int { + if i := bytes.Index(b[from:], sep); i >= 0 { + return from + i + } + return -1 +} diff --git a/internal/handler/pypi_release_times_test.go b/internal/handler/pypi_release_times_test.go new file mode 100644 index 0000000..37e8447 --- /dev/null +++ b/internal/handler/pypi_release_times_test.go @@ -0,0 +1,125 @@ +package handler + +import ( + "fmt" + "runtime" + "strings" + "testing" + "time" +) + +func TestPyPIParseReleaseTimes(t *testing.T) { + h := &PyPIHandler{} + body := `{ + "info": {"name": "pkg", "version": "3.0.0"}, + "releases": { + "1.0.0": [ + {"filename": "pkg-1.0.0.tar.gz", "upload_time_iso_8601": "2024-01-01T10:00:00Z"}, + {"filename": "pkg-1.0.0-py3-none-any.whl", "upload_time_iso_8601": "2024-01-02T10:00:00.123456Z"} + ], + "2.0.0": [], + "3.0.0": [ + 42, + {"upload_time_iso_8601": 5}, + {"upload_time_iso_8601": null}, + {"upload_time_iso_8601": "not a time"}, + {"upload_time": "2024-06-01T00:00:00"}, + {"upload_time_iso_8601": "2024-03-01T00:00:00Z"} + ], + "4.0.0": "not a list" + }, + "urls": [{"upload_time_iso_8601": "2030-01-01T00:00:00Z"}] + }` + + times, err := h.parseReleaseTimes([]byte(body)) + if err != nil { + t.Fatalf("parseReleaseTimes failed: %v", err) + } + want := map[string]time.Time{ + "1.0.0": time.Date(2024, 1, 2, 10, 0, 0, 123456000, time.UTC), + "2.0.0": {}, + "3.0.0": time.Date(2024, 3, 1, 0, 0, 0, 0, time.UTC), + "4.0.0": {}, + } + for version, wantTime := range want { + if got := times[version]; !got.Equal(wantTime) { + t.Errorf("times[%q] = %v, want %v", version, got, wantTime) + } + } + for version := range times { + if _, ok := want[version]; !ok { + t.Errorf("unexpected release %q", version) + } + } +} + +func TestPyPIParseReleaseTimesRejectsDocumentWithoutReleases(t *testing.T) { + h := &PyPIHandler{} + for _, body := range []string{ + `{"info": {"name": "pkg"}}`, + `{"releases": null}`, + `{"releases": []}`, + `[]`, + `{"releases": {"1.0.0": [`, + `not json`, + } { + if times, err := h.parseReleaseTimes([]byte(body)); err == nil { + t.Errorf("parseReleaseTimes(%s) = %v, want an error", body, times) + } + } + + times, err := h.parseReleaseTimes([]byte(`{"releases": {}}`)) + if err != nil || len(times) != 0 { + t.Errorf("parseReleaseTimes with no releases = %v, %v; want an empty result", times, err) + } +} + +// pypiJSONDocument builds a JSON API document shaped like PyPI's, with the +// file fields that make up most of a real one. +func pypiJSONDocument(releases, filesPerRelease int) []byte { + var b strings.Builder + b.WriteString(`{"info":{"name":"pkg","summary":"A package"},"releases":{`) + for r := range releases { + if r > 0 { + b.WriteByte(',') + } + fmt.Fprintf(&b, `"1.%d.0":[`, r) + for f := range filesPerRelease { + if f > 0 { + b.WriteByte(',') + } + fmt.Fprintf(&b, `{"comment_text":"","digests":{"blake2b_256":"%064x","md5":"%032x","sha256":"%064x"},`+ + `"downloads":-1,"filename":"pkg-1.%d.0-cp3%d-cp3%d-manylinux_2_17_x86_64.whl","has_sig":false,`+ + `"md5_digest":"%032x","packagetype":"bdist_wheel","python_version":"cp3%d","requires_python":">=3.8",`+ + `"size":123456,"upload_time":"2024-01-02T03:04:05","upload_time_iso_8601":"2024-01-02T03:04:05.123456Z",`+ + `"url":"https://files.pythonhosted.org/packages/ab/cd/%060x/pkg-1.%d.0-cp3%d-cp3%d-manylinux_2_17_x86_64.whl",`+ + `"yanked":false,"yanked_reason":null}`, r, f, r, r, f, f, f, f, r, r, f, f) + } + b.WriteByte(']') + } + b.WriteString(`},"urls":[],"vulnerabilities":[]}`) + return []byte(b.String()) +} + +// Reading the release times must not build the whole document in memory: it +// runs on every simple index request for a package under cooldown. +func TestPyPIParseReleaseTimesAllocatesLessThanDocument(t *testing.T) { + h := &PyPIHandler{} + body := pypiJSONDocument(300, 12) + + const runs = 5 + var before, after runtime.MemStats + runtime.ReadMemStats(&before) + for range runs { + times, err := h.parseReleaseTimes(body) + if err != nil || len(times) != 300 { + t.Fatalf("parseReleaseTimes = %d releases, %v", len(times), err) + } + } + runtime.ReadMemStats(&after) + + perRun := (after.TotalAlloc - before.TotalAlloc) / runs + if perRun > uint64(len(body)) { + t.Errorf("parseReleaseTimes allocated %d bytes for a %d byte document", perRun, len(body)) + } +} diff --git a/internal/handler/pypi_test.go b/internal/handler/pypi_test.go index c370719..a80e95b 100644 --- a/internal/handler/pypi_test.go +++ b/internal/handler/pypi_test.go @@ -2,13 +2,17 @@ package handler import ( "encoding/json" + "fmt" "io" "log/slog" + "math/rand/v2" "net/http" "net/http/httptest" + "strconv" "strings" "sync/atomic" "testing" + "testing/iotest" "time" "github.com/git-pkgs/cooldown" @@ -276,6 +280,32 @@ func TestPyPISimpleJSONCooldown(t *testing.T) { } } +// TestPyPISimpleJSONFiltersVersions checks that the PEP 700 versions list +// loses a version whose files were all filtered out, and keeps one that +// still has files. +func TestPyPISimpleJSONFiltersVersions(t *testing.T) { + h := &PyPIHandler{proxy: &Proxy{Logger: slog.Default()}, proxyURL: "http://proxy.test"} + body := `{"meta":{"api-version":"1.1"},"name":"ruff","versions":["1.0.0","2.0.0","3.0.0"],"files":[` + + `{"filename":"ruff-1.0.0.tar.gz","url":"https://files.pythonhosted.org/packages/ab/ruff-1.0.0.tar.gz"},` + + `{"filename":"ruff-2.0.0.tar.gz","url":"https://files.pythonhosted.org/packages/cd/ruff-2.0.0.tar.gz"},` + + `{"filename":"ruff-2.0.0-py3-none-any.whl","url":"https://files.pythonhosted.org/packages/ef/ruff-2.0.0-py3-none-any.whl"}` + + `]}` + out, err := h.rewriteSimpleJSON([]byte(body), map[string]bool{"2.0.0": true, "3.0.0": true}) + if err != nil { + t.Fatal(err) + } + var result struct { + Versions []string `json:"versions"` + } + if err := json.Unmarshal(out, &result); err != nil { + t.Fatal(err) + } + // 3.0.0 has no files to filter, but it is still held back. + if strings.Join(result.Versions, ",") != "1.0.0" { + t.Errorf("versions = %v, want [1.0.0]", result.Versions) + } +} + func TestPyPIParseFilename(t *testing.T) { h := &PyPIHandler{proxy: &Proxy{Logger: slog.Default()}} @@ -375,7 +405,7 @@ func TestPyPIRewriteJSONMetadataCooldown(t *testing.T) { "urls": [{"url": "https://files.pythonhosted.org/packages/ab/cd/requests-2.31.0.tar.gz", "upload_time_iso_8601": "` + recent + `"}] }` - output, err := h.rewriteJSONMetadata([]byte(input)) + output, _, err := h.rewriteJSONMetadata([]byte(input)) if err != nil { t.Fatalf("rewriteJSONMetadata failed: %v", err) } @@ -611,3 +641,129 @@ func TestPyPIDownloadCooldownMetadataCache(t *testing.T) { t.Errorf("upstream metadata JSON requests = %d, want 1 (repeated downloads should reuse the cached metadata)", got) } } + +func TestPyPISimpleIndexRewritesProjectLinks(t *testing.T) { + for _, tc := range []struct{ name, upstream, prefix string }{ + {"root", "https://pypi.test", "/simple/"}, + {"subpath", "https://nexus.test/repository/pypi", "/repository/pypi/simple/"}, + } { + t.Run(tc.name, func(t *testing.T) { + // Long enough that links cross the rewriter's read boundaries. + var upstream, want strings.Builder + upstream.WriteString(``) + want.WriteString(``) + for i := range 3000 { + fmt.Fprintf(&upstream, `pkg-%d`+"\n", tc.prefix, i, i) + fmt.Fprintf(&want, `pkg-%d`+"\n", i, i) + } + fmt.Fprintf(&upstream, `q`, tc.prefix) + want.WriteString(`q`) + upstream.WriteString(``) + want.WriteString(``) + + h, _ := setupPyPIHandler(t, func(r *http.Request) (*http.Response, error) { + resp := pypiHTTPResponse(r, "text/html", upstream.String()) + resp.Header.Set("Content-Length", strconv.Itoa(upstream.Len())) + resp.Header.Set("ETag", `"upstream"`) + return resp, nil + }) + h.upstreamURL = tc.upstream + + req := httptest.NewRequest(http.MethodGet, "/simple/", nil) + w := httptest.NewRecorder() + h.Routes().ServeHTTP(w, req) + + if w.Code != http.StatusOK { + t.Fatalf("status = %d, want 200", w.Code) + } + if got := w.Body.String(); got != want.String() { + t.Errorf("body not rewritten; starts %q", got[:min(len(got), 120)]) + } + if got := w.Header().Get("Content-Length"); got != "" && got != strconv.Itoa(want.Len()) { + t.Errorf("Content-Length = %q, want %d or unset", got, want.Len()) + } + // The upstream's ETag names the body before the rewrite. + if got := w.Header().Get("ETag"); got != "" { + t.Errorf("ETag = %q, want none on a rewritten body", got) + } + }) + } +} + +func TestReplacingReaderSplitReads(t *testing.T) { + const in = `abxhref="/simplehref="/simple/href='/simple/y/'` + const want = `abxhref="/simplehref="P/href='Q/y/'` + r := &replacingReader{ + src: io.NopCloser(iotest.OneByteReader(strings.NewReader(in))), + replacements: []replacement{ + {from: []byte(`href="/simple/`), to: []byte(`href="P/`)}, + {from: []byte(`href='/simple/`), to: []byte(`href='Q/`)}, + }, + } + got, err := io.ReadAll(r) + if err != nil || string(got) != want { + t.Errorf("got %q, %v; want %q", got, err, want) + } +} + +// replaceReference makes the replacements the way replacingReader should: +// left to right, the earliest match first, and the first listed on a tie. +func replaceReference(in string, reps []replacement) string { + var out strings.Builder + for len(in) > 0 { + at, found := -1, -1 + for i, rep := range reps { + if j := strings.Index(in, string(rep.from)); j >= 0 && (at < 0 || j < at) { + at, found = j, i + } + } + if at < 0 { + out.WriteString(in) + break + } + out.WriteString(in[:at]) + out.Write(reps[found].to) + in = in[at+len(reps[found].from):] + } + return out.String() +} + +func TestReplacingReaderMatchesReference(t *testing.T) { + reps := []replacement{ + {from: []byte(`href="/s/`), to: []byte(`href="P/`)}, + {from: []byte(`href='/s/`), to: []byte(`href='Q/`)}, + } + pieces := []string{`href="/s/`, `href='/s/`, `href="/s`, `href=`, `x`, `/s/`, `'`, `"`} + rng := rand.New(rand.NewPCG(1, 2)) + for range 500 { + var b strings.Builder + for range rng.IntN(40) { + b.WriteString(pieces[rng.IntN(len(pieces))]) + } + in := b.String() + for _, src := range []io.Reader{strings.NewReader(in), iotest.OneByteReader(strings.NewReader(in))} { + got, err := io.ReadAll(&replacingReader{src: io.NopCloser(src), replacements: reps}) + if want := replaceReference(in, reps); err != nil || string(got) != want { + t.Fatalf("in %q: got %q, %v; want %q", in, got, err, want) + } + } + } +} + +// BenchmarkReplacingReaderRootIndex reads a root index of double-quoted +// links, where the single-quote pattern never matches. +func BenchmarkReplacingReaderRootIndex(b *testing.B) { + var page strings.Builder + for i := range 50000 { + fmt.Fprintf(&page, "project-%d\n", i, i) + } + in := page.String() + reps := []replacement{ + {from: []byte(`href="/simple/`), to: []byte(`href="http://proxy/pypi/simple/`)}, + {from: []byte(`href='/simple/`), to: []byte(`href='http://proxy/pypi/simple/`)}, + } + b.SetBytes(int64(len(in))) + for b.Loop() { + _, _ = io.Copy(io.Discard, &replacingReader{src: io.NopCloser(strings.NewReader(in)), replacements: reps}) + } +} diff --git a/internal/handler/pypi_upload_time_test.go b/internal/handler/pypi_upload_time_test.go new file mode 100644 index 0000000..f61a5f0 --- /dev/null +++ b/internal/handler/pypi_upload_time_test.go @@ -0,0 +1,107 @@ +package handler + +import ( + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/git-pkgs/cooldown" + "github.com/git-pkgs/registries/fetch" +) + +// pypiUploadTimeSetup serves the JSON API for newpkg from releases, which the +// test may change, and counts its requests. cache_metadata is off, so every +// lookup reaches upstream. +func pypiUploadTimeSetup(t *testing.T) (h http.Handler, setReleases func(string), jsonRequests *atomic.Int64, fetcher *mockFetcher) { + t.Helper() + var mu sync.Mutex + releases := "" + jsonRequests = &atomic.Int64{} + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/pypi/newpkg/json" { + http.NotFound(w, r) + return + } + jsonRequests.Add(1) + mu.Lock() + defer mu.Unlock() + w.Header().Set("Content-Type", contentTypeJSON) + _, _ = io.WriteString(w, releases) + })) + t.Cleanup(upstream.Close) + + proxy, _, _, fetcher := setupTestProxy(t) + proxy.HTTPClient = upstream.Client() + proxy.Cooldown = &cooldown.Config{Default: "7d"} + setReleases = func(s string) { + mu.Lock() + defer mu.Unlock() + releases = s + } + return (&PyPIHandler{proxy: proxy, upstreamURL: upstream.URL, downloadURL: upstream.URL, proxyURL: "http://localhost"}).Routes(), + setReleases, jsonRequests, fetcher +} + +func uploaded(ago time.Duration) string { + return time.Now().Add(-ago).Format(time.RFC3339) +} + +// TestPyPICachedDownloadUsesStoredUploadTime checks that once a release's +// upload time is stored, downloads of its cached files don't read the JSON +// API again. +func TestPyPICachedDownloadUsesStoredUploadTime(t *testing.T) { + h, setReleases, jsonRequests, fetcher := pypiUploadTimeSetup(t) + setReleases(`{"releases": {"1.0.0": [{"upload_time_iso_8601": "` + uploaded(30*24*time.Hour) + `"}]}}`) + fetcher.artifact = &fetch.Artifact{Body: io.NopCloser(strings.NewReader("sdist")), ContentType: "application/octet-stream"} + + for range 3 { + w := serveGet(t, h, "/packages/packages/ab/cd/ef0123456789/newpkg-1.0.0.tar.gz") + wantStatus(t, w, http.StatusOK, "") + if w.Body.String() != "sdist" { + t.Fatalf("body = %q", w.Body.String()) + } + } + if got := jsonRequests.Load(); got != 1 { + t.Errorf("JSON API requests = %d, want 1", got) + } +} + +// TestPyPIFileAddedToReleaseIsChecked checks that a file uploaded to a +// release after its time was stored is not let through on the stored time: +// it isn't cached, so the JSON API is read, the newer time is stored, and +// from then on the whole release is withheld until it is out of cooldown. +func TestPyPIFileAddedToReleaseIsChecked(t *testing.T) { + h, setReleases, jsonRequests, fetcher := pypiUploadTimeSetup(t) + sdist := `{"upload_time_iso_8601": "` + uploaded(30*24*time.Hour) + `"}` + setReleases(`{"releases": {"1.0.0": [` + sdist + `]}}`) + fetcher.artifact = &fetch.Artifact{Body: io.NopCloser(strings.NewReader("sdist")), ContentType: "application/octet-stream"} + + const ( + sdistPath = "/packages/packages/ab/cd/ef0123456789/newpkg-1.0.0.tar.gz" + wheelPath = "/packages/packages/ab/cd/ef0123456789/newpkg-1.0.0-py3-none-any.whl" + ) + wantStatus(t, serveGet(t, h, sdistPath), http.StatusOK, "") + + // A wheel is added to the release an hour ago. + setReleases(`{"releases": {"1.0.0": [` + sdist + `, {"upload_time_iso_8601": "` + uploaded(time.Hour) + `"}]}}`) + fetcher.fetchCalled = false + wantStatus(t, serveGet(t, h, wheelPath), http.StatusNotFound, "") + if fetcher.fetchCalled { + t.Error("fetched a file that is inside the cooldown window") + } + if got := jsonRequests.Load(); got != 2 { + t.Errorf("JSON API requests = %d, want 2 (the new file is looked up)", got) + } + + // The stored time is now the wheel's, so the cached sdist is withheld + // too, as the JSON API lookup would do, without asking it. + wantStatus(t, serveGet(t, h, sdistPath), http.StatusNotFound, "") + if got := jsonRequests.Load(); got != 2 { + t.Errorf("JSON API requests = %d, want 2", got) + } +} diff --git a/internal/handler/query_in_path_test.go b/internal/handler/query_in_path_test.go new file mode 100644 index 0000000..d9f412f --- /dev/null +++ b/internal/handler/query_in_path_test.go @@ -0,0 +1,71 @@ +package handler + +import ( + "errors" + "net/http" + "net/http/httptest" + "sync/atomic" + "testing" +) + +// TestHandlersRejectQueryCharsInPath checks that handlers which build upstream +// URLs from the decoded path refuse an encoded '?' or '#' themselves, without +// relying on the server middleware, and never contact the upstream or fetch +// an artifact. +func TestHandlersRejectQueryCharsInPath(t *testing.T) { + var requests atomic.Int32 + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + requests.Add(1) + _, _ = w.Write([]byte("upstream")) + })) + defer upstream.Close() + + proxy, _, _, fetcher := setupTestProxy(t) + proxy.HTTPClient = upstream.Client() + fetcher.fetchErr = errors.New("artifact fetched") + + handlers := map[string]struct { + routes http.Handler + paths []string + }{ + "debian": {NewDebianHandler(proxy, testProxyURL, upstream.URL, nil).Routes(), []string{ + "/pool/main/h/hello/hello_2.10-3_amd64.deb%3F/foo_9.9_amd64.deb", + "/dists/trixie/InRelease%23x", + }}, + "rpm": {NewRPMHandlerWithUpstream(proxy, testProxyURL, upstream.URL).Routes(), []string{ + "/Packages/n/nginx-1.24.0-2.fc39.x86_64.rpm%3F/foo-9.9-1.fc39.x86_64.rpm", + "/repodata/repomd.xml%3Fx", + }}, + "apk": {NewAPKHandler(proxy, testProxyURL, map[string]string{"alpine": upstream.URL}).Routes(), []string{ + "/alpine/v3.20/main/x86_64/busybox-1.36.1-r29.apk%3F/foo-9.9-r0.apk", + "/alpine/v3.20/main/x86_64/APKINDEX.tar.gz%23x", + }}, + "pypi": {NewPyPIHandlerWithUpstreams(proxy, testProxyURL, upstream.URL, upstream.URL).Routes(), []string{ + "/packages/aa/bb/requests-2.31.0.tar.gz%3F/foo-9.9.tar.gz", + "/simple/requests%3Fx/", + }}, + "cran": {NewCRANHandlerWithUpstream(proxy, testProxyURL, upstream.URL).Routes(), []string{ + "/src/contrib/ggplot2_3.4.4.tar.gz%3Ffoo_9.9.tar.gz", + "/bin/macosx%23x/contrib/4.3/PACKAGES", + }}, + "maven": {NewMavenHandler(proxy, testProxyURL, upstream.URL, upstream.URL).Routes(), []string{ + "/com/example/lib/1.0/lib-1.0.jar%3F/com/example/foo/9.9/foo-9.9.jar", + "/com/example/lib/maven-metadata.xml%23x", + }}, + } + for name, tc := range handlers { + for _, target := range tc.paths { + w := httptest.NewRecorder() + tc.routes.ServeHTTP(w, httptest.NewRequest(http.MethodGet, target, nil)) + if w.Code != http.StatusBadRequest { + t.Errorf("%s: GET %s = %d, want %d", name, target, w.Code, http.StatusBadRequest) + } + } + } + if got := requests.Load(); got != 0 { + t.Errorf("upstream requests = %d, want 0", got) + } + if fetcher.fetchCalled { + t.Errorf("artifact fetched from %s", fetcher.fetchedURL) + } +} diff --git a/internal/handler/read_metadata_test.go b/internal/handler/read_metadata_test.go index b13bddb..d87d416 100644 --- a/internal/handler/read_metadata_test.go +++ b/internal/handler/read_metadata_test.go @@ -3,7 +3,12 @@ package handler import ( "bytes" "errors" + "fmt" + "io" + "runtime" + "strings" "testing" + "testing/iotest" ) func TestReadMetadata(t *testing.T) { @@ -58,3 +63,87 @@ func TestReadMetadata(t *testing.T) { } }) } + +func TestReadMetadataSized(t *testing.T) { + const limit = 1024 + p := &Proxy{MetadataMaxSize: limit} + body := bytes.Repeat([]byte("x"), 100) + + for _, tt := range []struct { + name string + body []byte + size int64 + }{ + {"exact size", body, 100}, + {"unknown size", body, -1}, + {"size too small", body, 10}, + {"size too large", body, 900}, + {"size above limit", body, limit * 4}, + {"empty body", nil, 0}, + {"empty body with size", nil, 50}, + {"body at limit", bytes.Repeat([]byte("x"), limit), limit}, + {"body at limit, size too small", bytes.Repeat([]byte("x"), limit), 1}, + } { + t.Run(tt.name, func(t *testing.T) { + // OneByteReader makes sure short reads are not taken for EOF. + got, err := p.ReadMetadataSized(iotest.OneByteReader(bytes.NewReader(tt.body)), tt.size) + if err != nil { + t.Fatalf("ReadMetadataSized: %v", err) + } + if !bytes.Equal(got, tt.body) { + t.Errorf("got %d bytes, want %d", len(got), len(tt.body)) + } + }) + } + + for _, size := range []int64{-1, 10, limit, limit + 1, limit * 4} { + t.Run(fmt.Sprintf("over limit with size %d", size), func(t *testing.T) { + _, err := p.ReadMetadataSized(bytes.NewReader(make([]byte, limit+1)), size) + if !errors.Is(err, ErrMetadataTooLarge) { + t.Errorf("got error %v, want ErrMetadataTooLarge", err) + } + }) + } + + t.Run("read error", func(t *testing.T) { + errRead := errors.New("read failed") + r := io.MultiReader(bytes.NewReader(body), iotest.ErrReader(errRead)) + if _, err := p.ReadMetadataSized(r, 100); !errors.Is(err, errRead) { + t.Errorf("got error %v, want %v", err, errRead) + } + }) +} + +// TestReadMetadataSizedAllocatesOnce checks that a correct size hint reads +// into a single buffer of that size rather than a growing one. +func TestReadMetadataSizedAllocatesOnce(t *testing.T) { + const size = 8 << 20 + p := &Proxy{MetadataMaxSize: 64 << 20} + payload := bytes.Repeat([]byte("x"), size) + + var before, after runtime.MemStats + runtime.ReadMemStats(&before) + data, err := p.ReadMetadataSized(bytes.NewReader(payload), size) + runtime.ReadMemStats(&after) + if err != nil || len(data) != size { + t.Fatalf("read %d bytes, %v", len(data), err) + } + if allocated := after.TotalAlloc - before.TotalAlloc; allocated > size*3/2 { + t.Errorf("allocated %d bytes reading %d", allocated, size) + } +} + +// TestReadMetadataSizedTruncatedUpstream checks that an upstream body cut +// off before its Content-Length fails, while a body shorter than a size +// hint is still read. +func TestReadMetadataSizedTruncatedUpstream(t *testing.T) { + p := &Proxy{} + cut := io.MultiReader(strings.NewReader(`{"name":`), iotest.ErrReader(io.ErrUnexpectedEOF)) + if _, err := p.ReadMetadataSized(upstreamBodyReader{cut}, 100); !errors.Is(err, io.ErrUnexpectedEOF) { + t.Errorf("cut off body: error %v, want io.ErrUnexpectedEOF", err) + } + got, err := p.ReadMetadataSized(strings.NewReader(`{"name":"x"}`), 100) + if err != nil || string(got) != `{"name":"x"}` { + t.Errorf("short body = %q, %v", got, err) + } +} diff --git a/internal/handler/relay_test.go b/internal/handler/relay_test.go index a7a8fb7..33db80b 100644 --- a/internal/handler/relay_test.go +++ b/internal/handler/relay_test.go @@ -52,8 +52,7 @@ func TestRelayRoutes(t *testing.T) { "/upstream", "/file", "/metadata", "/nuget/query", "/conan/v2/conans/demo/1.0/user/stable/revisions/rev/files/other.txt", "/composer/search.json", "/pypi/simple/", "/gem/api/v1/dependencies", - "/gem/info/demo", "/conda/conda-forge/noarch/repodata.json", - "/hex/packages/demo", "/swift/scope/demo/1.0.0/Package.swift", + "/conda/conda-forge/noarch/repodata.json", "/v2/library/demo/manifests/latest", "/v2/library/demo/tags/list", "/npm/-/npm/v1/keys", } { @@ -82,10 +81,9 @@ func testRelayRoute(t *testing.T, route string, truncated bool) { if !truncated { _, _ = fmt.Fprint(rw, "0\r\nX-Checksum: verified\r\nX-Late: discovered-at-eof\r\nX-Private: still-secret\r\n\r\n") } - // Two of these routes fan out a second upstream request for cooldown - // timestamps and abandon its body on a non-200, so this may be writing to - // a connection the proxy has already dropped. What the proxy made of the - // response under test is asserted downstream. + // The proxy may drop the connection before reading the whole + // response. What it made of the response under test is asserted + // downstream. _ = rw.Flush() })) defer upstream.Close() diff --git a/internal/handler/release_allowed.go b/internal/handler/release_allowed.go new file mode 100644 index 0000000..4c70214 --- /dev/null +++ b/internal/handler/release_allowed.go @@ -0,0 +1,19 @@ +package handler + +import ( + "time" +) + +// ReleaseAllowed reports whether clients would be served a version published +// at publishedAt: the denylist doesn't name it, and cooldown, where the +// ecosystem applies it, doesn't withhold it. Without a publish time a version +// counts as withheld wherever cooldown applies. +func (p *Proxy) ReleaseAllowed(ecosystem, name, version string, publishedAt time.Time) bool { + if p.versionDenied(ecosystem, name, version) { + return false + } + if !CooldownSupported(ecosystem) || !p.cooldownApplies(ecosystem, name) { + return true + } + return !publishedAt.IsZero() && p.cooldown().IsAllowed(ecosystem, canonicalPackagePURL(ecosystem, name), publishedAt) +} diff --git a/internal/handler/release_allowed_test.go b/internal/handler/release_allowed_test.go new file mode 100644 index 0000000..0d8dd88 --- /dev/null +++ b/internal/handler/release_allowed_test.go @@ -0,0 +1,44 @@ +package handler + +import ( + "testing" + "time" + + "github.com/git-pkgs/cooldown" + "github.com/git-pkgs/proxy/internal/denylist" +) + +func TestReleaseAllowed(t *testing.T) { + deny, err := denylist.New([]string{"pkg:npm/lodash@4.17.22"}) + if err != nil { + t.Fatal(err) + } + p := &Proxy{Cooldown: &cooldown.Config{Default: "3d"}, Denylist: deny} + old := time.Now().Add(-10 * 24 * time.Hour) + fresh := time.Now().Add(-time.Hour) + + tests := []struct { + name string + ecosystem, pkg, version string + published time.Time + want bool + }{ + {"old enough", "npm", "lodash", "4.17.21", old, true}, + {"within cooldown", "npm", "lodash", "4.17.23", fresh, false}, + {"denied", "npm", "lodash", "4.17.22", old, false}, + {"no publish time under cooldown", "npm", "lodash", "4.17.24", time.Time{}, false}, + // deb has no publish times, so cooldown never applies to it. + {"ecosystem without cooldown", "deb", "curl", "8.5.0-2", time.Time{}, true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := p.ReleaseAllowed(tt.ecosystem, tt.pkg, tt.version, tt.published); got != tt.want { + t.Errorf("ReleaseAllowed = %v, want %v", got, tt.want) + } + }) + } + + if !(&Proxy{}).ReleaseAllowed("npm", "lodash", "4.17.23", fresh) { + t.Error("a proxy without cooldown or denylist refused a release") + } +} diff --git a/internal/handler/release_index.go b/internal/handler/release_index.go new file mode 100644 index 0000000..626792a --- /dev/null +++ b/internal/handler/release_index.go @@ -0,0 +1,133 @@ +package handler + +import ( + "bufio" + "bytes" + "context" + "crypto/sha256" + "encoding/hex" + "encoding/xml" + "net/http" + "strings" + "time" +) + +// APT and RPM repositories have a release file (InRelease, Release, +// repomd.xml) that lists the sha256 of each index file. Clients fetch the +// release file first and reject an index that doesn't match it. Each file +// has its own metadata cache entry and TTL, so without care a client could +// get a cached release file and a freshly fetched index, or the reverse. +// +// An index the cached release file lists is therefore served by that +// listing rather than by its own TTL: the cached copy when it matches, +// whatever its age, and otherwise a copy fetched from upstream. If upstream +// only has an index the cached release file doesn't list, upstream has moved +// on; that index is served and the release file is expired, so the next +// update gets a matching pair. + +// cachedRelease is a release file in the metadata cache. +type cachedRelease struct { + ecosystem string + cacheKey string + body []byte + fetchedAt time.Time +} + +// readCachedRelease returns the cached release file stored under cacheKey, +// or nil. +func (p *Proxy) readCachedRelease(ctx context.Context, ecosystem, cacheKey string) *cachedRelease { + if !p.CacheMetadata || p.DB == nil || p.Storage == nil { + return nil + } + entry, err := p.DB.GetMetadataCache(ecosystem, cacheKey) + if err != nil || entry == nil || entry.ContentEncoding.String != "" { + return nil + } + body, _, err := p.readCachedMetadata(ctx, entry, nil) + // Bytes another instance replaced since the row was read don't describe + // the release the row records. + if err != nil || !matchesEntryDigest(entry, body) { + return nil + } + return &cachedRelease{ecosystem: ecosystem, cacheKey: cacheKey, body: body, fetchedAt: entry.FetchedAt.Time} +} + +// proxyListedIndex serves an index file that release lists with the sha256 +// hex want. Without a listing it is served as other metadata. +func (p *Proxy) proxyListedIndex(w http.ResponseWriter, r *http.Request, upstreamURL, ecosystem, cacheKey string, release *cachedRelease, want string) { + if release == nil || want == "" { + p.ProxyCached(w, r, upstreamURL, ecosystem, cacheKey, "*/*") + return + } + if entry, _ := p.DB.GetMetadataCache(ecosystem, cacheKey); entry != nil && p.streamableMetadata(entry) && + entry.ContentDigest.String == "sha256:"+want && entry.ContentEncoding.String == "" { + if p.serveMetadataEntry(w, r, ecosystem, cacheKey, entry, true) { + return + } + } + p.recordMetadataCacheMiss(ecosystem) + res := p.refreshMetadata(r.Context(), ecosystem, cacheKey, upstreamURL, "*/*", "identity", nil) + if res.err != nil { + p.writeMetadataFetchError(w, res.err) + return + } + if sum := sha256.Sum256(res.body); !res.stale && hex.EncodeToString(sum[:]) != want { + p.Logger.Info("index does not match the cached release file, expiring it", + "ecosystem", ecosystem, "url", upstreamURL) + if _, err := p.DB.ExpireMetadataCache(ecosystem, []string{release.cacheKey}, time.Now()); err != nil { + p.Logger.Warn("failed to expire cached release file", "ecosystem", ecosystem, "error", err) + } + } + writeMetadataResult(w, r, res) +} + +// releaseLineMax bounds a line of a Release file. +const releaseLineMax = 1 << 20 + +// debianReleaseSHA256 returns the sha256 an APT Release or InRelease file +// lists for rel, a path relative to the release file's directory, or "". +func debianReleaseSHA256(release []byte, rel string) string { + inSection := false + scanner := bufio.NewScanner(bytes.NewReader(release)) + scanner.Buffer(nil, releaseLineMax) + for scanner.Scan() { + line := strings.TrimRight(scanner.Text(), "\r") + if !strings.HasPrefix(line, " ") { + inSection = line == "SHA256:" + continue + } + if !inSection { + continue + } + if f := strings.Fields(line); len(f) == 3 && f[2] == rel { + return strings.ToLower(f[0]) + } + } + return "" +} + +// repomdSHA256 returns the sha256 an RPM repomd.xml lists for href, a path +// relative to the repository root, or "" when it lists none or another +// checksum type. +func repomdSHA256(repomd []byte, href string) string { + var doc struct { + Data []struct { + Checksum struct { + Type string `xml:"type,attr"` + Value string `xml:",chardata"` + } `xml:"checksum"` + Location struct { + Href string `xml:"href,attr"` + } `xml:"location"` + } `xml:"data"` + } + if xml.Unmarshal(repomd, &doc) != nil { + return "" + } + for _, d := range doc.Data { + if d.Location.Href == href && d.Checksum.Type == "sha256" { + return strings.ToLower(strings.TrimSpace(d.Checksum.Value)) + } + } + return "" +} diff --git a/internal/handler/release_index_test.go b/internal/handler/release_index_test.go new file mode 100644 index 0000000..b69f4ed --- /dev/null +++ b/internal/handler/release_index_test.go @@ -0,0 +1,265 @@ +package handler + +import ( + "context" + "fmt" + "net/http" + "net/http/httptest" + "sync/atomic" + "testing" + "time" +) + +// releaseArchive is an upstream repository whose release file and index +// change together, one generation at a time. +type releaseArchive struct { + gen atomic.Int32 + // releasePath and indexPath are the request paths, release renders the + // release file listing index's sha256 for a generation. + releasePath, indexPath string + release func(indexSHA256 string, size int) string +} + +func indexBody(gen int32) string { return fmt.Sprintf("index generation %d\n", gen) } + +func (a *releaseArchive) serve(w http.ResponseWriter, r *http.Request) { + gen := a.gen.Load() + index := indexBody(gen) + switch r.URL.Path { + case "/" + a.releasePath: + _, _ = w.Write([]byte(a.release(sha256Hex(index), len(index)))) + case "/" + a.indexPath: + _, _ = w.Write([]byte(index)) + default: + http.NotFound(w, r) + } +} + +type releaseIndexCase struct { + name string + ecosystem string + archive *releaseArchive + handler func(p *Proxy, upstreamURL string) (http.Handler, func(path string) string) +} + +func releaseIndexCases() []releaseIndexCase { + return []releaseIndexCase{ + { + name: "debian InRelease", + ecosystem: "debian", + archive: &releaseArchive{ + releasePath: "dists/stable/InRelease", + indexPath: "dists/stable/main/binary-amd64/Packages", + release: func(sum string, size int) string { + return "-----BEGIN PGP SIGNED MESSAGE-----\nHash: SHA512\n\nSuite: stable\nMD5Sum:\n 00000000000000000000000000000000 1 main/binary-amd64/Packages\nSHA256:\n" + + fmt.Sprintf(" %s %d main/binary-amd64/Packages\n", sum, size) + + "-----BEGIN PGP SIGNATURE-----\n\nxx\n-----END PGP SIGNATURE-----\n" + }, + }, + handler: func(p *Proxy, upstreamURL string) (http.Handler, func(string) string) { + h := NewDebianHandler(p, "http://proxy.test", upstreamURL, nil) + return h.Routes(), func(path string) string { return h.metadataCacheKeyFor("", h.upstreamURL, path) } + }, + }, + { + name: "rpm repomd.xml", + ecosystem: "rpm", + archive: &releaseArchive{ + releasePath: "f/39/os/repodata/repomd.xml", + indexPath: "f/39/os/repodata/primary.xml.gz", + release: func(sum string, _ int) string { + return ` +1 +` + sum + ` +` + }, + }, + handler: func(p *Proxy, upstreamURL string) (http.Handler, func(string) string) { + h := NewRPMHandlerWithUpstream(p, "http://proxy.test", upstreamURL) + return h.Routes(), h.metadataCacheKey + }, + }, + } +} + +func getBody(t *testing.T, h http.Handler, path string) string { + t.Helper() + w := httptest.NewRecorder() + h.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/"+path, nil)) + if w.Code != http.StatusOK { + t.Fatalf("GET %s = %d %s", path, w.Code, w.Body) + } + return w.Body.String() +} + +// TestIndexFollowsCachedRelease checks that the index files a release file +// lists are served as that release file lists them, whatever the index's own +// cache entry says. +func TestIndexFollowsCachedRelease(t *testing.T) { + for _, tc := range releaseIndexCases() { + t.Run(tc.name, func(t *testing.T) { + a := tc.archive + upstream := httptest.NewServer(http.HandlerFunc(a.serve)) + t.Cleanup(upstream.Close) + proxy, db, _, _ := setupTestProxy(t) + proxy.CacheMetadata = true + proxy.MetadataTTL = time.Hour + proxy.HTTPClient = upstream.Client() + h, key := tc.handler(proxy, upstream.URL) + expire := func(path string) { + t.Helper() + if _, err := db.ExpireMetadataCache(tc.ecosystem, []string{key(path)}, time.Now().Add(time.Second)); err != nil { + t.Fatal(err) + } + } + + getBody(t, h, a.releasePath) + if got := getBody(t, h, a.indexPath); got != indexBody(0) { + t.Fatalf("index = %q", got) + } + + // The index entry expires before the release file's while + // upstream moves on: the cached release still lists generation 0. + a.gen.Store(1) + expire(a.indexPath) + if got := getBody(t, h, a.indexPath); got != indexBody(0) { + t.Errorf("index after its entry expired = %q, want the one the cached release lists", got) + } + + // The release file is refetched while the index is still cached: + // the index must follow it. + expire(a.releasePath) + getBody(t, h, a.releasePath) + if got := getBody(t, h, a.indexPath); got != indexBody(1) { + t.Errorf("index after release refetch = %q, want %q", got, indexBody(1)) + } + }) + } +} + +// TestIndexMismatchExpiresRelease checks that when upstream only has an +// index newer than the cached release file, the release file is refetched +// on its next request, so the next update gets a matching pair. +func TestIndexMismatchExpiresRelease(t *testing.T) { + for _, tc := range releaseIndexCases() { + t.Run(tc.name, func(t *testing.T) { + a := tc.archive + upstream := httptest.NewServer(http.HandlerFunc(a.serve)) + t.Cleanup(upstream.Close) + proxy, _, _, _ := setupTestProxy(t) + proxy.CacheMetadata = true + proxy.MetadataTTL = time.Hour + proxy.HTTPClient = upstream.Client() + h, _ := tc.handler(proxy, upstream.URL) + + first := getBody(t, h, a.releasePath) + a.gen.Store(1) + if got := getBody(t, h, a.indexPath); got != indexBody(1) { + t.Fatalf("index = %q", got) + } + if got := getBody(t, h, a.releasePath); got == first { + t.Errorf("release file still the cached one, which does not list the index served") + } + }) + } +} + +// debianSuite serves an APT suite with both InRelease and Release, and the +// legacy per-component Release that lists no checksums. +func debianSuite(t *testing.T) (*atomic.Int32, http.Handler, func(path string)) { + t.Helper() + const index = "main/binary-amd64/Packages" + var gen atomic.Int32 + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + body := indexBody(gen.Load()) + release := fmt.Sprintf("Suite: stable\nSHA256:\n %s %d %s\n", sha256Hex(body), len(body), index) + switch r.URL.Path { + case "/dists/stable/InRelease": + _, _ = w.Write([]byte("-----BEGIN PGP SIGNED MESSAGE-----\n\n" + release + "-----BEGIN PGP SIGNATURE-----\n")) + case "/dists/stable/Release": + _, _ = w.Write([]byte(release)) + case "/dists/stable/main/binary-amd64/Release": + _, _ = w.Write([]byte("Archive: stable\nComponent: main\nArchitecture: amd64\n")) + case "/dists/stable/" + index: + _, _ = w.Write([]byte(body)) + default: + http.NotFound(w, r) + } + })) + t.Cleanup(upstream.Close) + proxy, db, _, _ := setupTestProxy(t) + proxy.CacheMetadata = true + proxy.MetadataTTL = time.Hour + proxy.HTTPClient = upstream.Client() + h := NewDebianHandler(proxy, "http://proxy.test", upstream.URL, nil) + expire := func(path string) { + t.Helper() + key := h.metadataCacheKeyFor("", h.upstreamURL, path) + if _, err := db.ExpireMetadataCache("debian", []string{key}, time.Now().Add(time.Second)); err != nil { + t.Fatal(err) + } + } + return &gen, h.Routes(), expire +} + +// TestDebianIndexFollowsLatestReleaseFile checks that with both InRelease +// and Release cached, the index follows the one fetched last, which is what +// the client asking for the index just read. +func TestDebianIndexFollowsLatestReleaseFile(t *testing.T) { + const index = "dists/stable/main/binary-amd64/Packages" + gen, h, expire := debianSuite(t) + + getBody(t, h, "dists/stable/InRelease") + getBody(t, h, index) + gen.Store(1) + time.Sleep(time.Millisecond) + getBody(t, h, "dists/stable/Release") + if got := getBody(t, h, index); got != indexBody(1) { + t.Errorf("index after a fresh Release = %q, want %q", got, indexBody(1)) + } + + // And back: a fresh InRelease wins over the older Release. + gen.Store(2) + expire("dists/stable/InRelease") + time.Sleep(time.Millisecond) + getBody(t, h, "dists/stable/InRelease") + if got := getBody(t, h, index); got != indexBody(2) { + t.Errorf("index after a fresh InRelease = %q, want %q", got, indexBody(2)) + } +} + +// TestDebianIndexSkipsReleaseWithoutListing checks that a cached release +// file that lists nothing for the index, such as the legacy per-component +// Release, does not stop the lookup at the suite's release file. +func TestDebianIndexSkipsReleaseWithoutListing(t *testing.T) { + const index = "dists/stable/main/binary-amd64/Packages" + gen, h, expire := debianSuite(t) + + getBody(t, h, "dists/stable/InRelease") + getBody(t, h, "dists/stable/main/binary-amd64/Release") + getBody(t, h, index) + gen.Store(1) + expire("dists/stable/InRelease") + getBody(t, h, "dists/stable/InRelease") + if got := getBody(t, h, index); got != indexBody(1) { + t.Errorf("index after InRelease refetch = %q, want %q", got, indexBody(1)) + } +} + +// TestCachedReleaseChecksStoredBytes checks that a release file whose stored +// bytes no longer match its row, because another instance replaced them, is +// not used to decide which index to serve. +func TestCachedReleaseChecksStoredBytes(t *testing.T) { + proxy, db, store, _ := setupTestProxy(t) + proxy.CacheMetadata = true + path := seedMetadataRow(t, db, store) + if proxy.readCachedRelease(context.Background(), "test", "pkg") == nil { + t.Fatal("matching release file not read") + } + store.mu.Lock() + store.files[path] = []byte(`{"v":2}`) + store.mu.Unlock() + if release := proxy.readCachedRelease(context.Background(), "test", "pkg"); release != nil { + t.Errorf("read a release file whose bytes don't match its row: %q", release.body) + } +} diff --git a/internal/handler/rewrite_cache.go b/internal/handler/rewrite_cache.go index fb3114a..a624dba 100644 --- a/internal/handler/rewrite_cache.go +++ b/internal/handler/rewrite_cache.go @@ -18,6 +18,7 @@ import ( "sync" "time" + "github.com/git-pkgs/proxy/internal/database" "github.com/git-pkgs/proxy/internal/metrics" ) @@ -33,7 +34,10 @@ import ( // Entries are keyed by a hash of the raw document, so new bytes from upstream // are rewritten again rather than served stale. Everything else a rewrite // depends on is fixed for the life of the process: the proxy URL is part of -// the key, and the denylist is loaded at startup. +// the key, and the denylist is loaded at startup. The exception is cooldown, +// which depends on the time of the request: with cooldown on, entries expire +// when the first version they held back leaves cooldown (see +// cooldown_expiry.go). // // Each entry keeps the ETag of its output, so clients can revalidate their // copy without the output being hashed again on every request. Dates are not @@ -45,6 +49,8 @@ import ( // on every request, by the proxy or by a reverse proxy in front of it. type rewriteCache struct { maxBytes int64 + // now reads the time entries expire by; nil means time.Now. + now func() time.Time mu sync.Mutex size int64 @@ -56,11 +62,13 @@ type rewriteCache struct { type rewriteEntry struct { key string rewrittenMetadata + // expires is when the entry stops being served, or zero for never. + expires time.Time } // size is how much of the cache's room the entry takes. func (e *rewriteEntry) size() int64 { - return int64(len(e.body) + len(e.gzipped)) + return int64(len(e.plain) + len(e.gzipped)) } // inflightRewrite is one rewrite that concurrent callers share. m and err are @@ -81,11 +89,50 @@ type metadataValidators struct { // rewrittenMetadata is a rewritten metadata document with its validators. // gzipped is the document gzip-compressed, or nil when there is no -// compressed copy to serve. +// compressed copy to serve. The cache keeps only gzipped when there is one, +// so plain is nil then; content returns the document either way. type rewrittenMetadata struct { - body []byte + plain []byte metadataValidators gzipped []byte + // size is the length of the uncompressed document. + size int +} + +// content returns the document uncompressed. A cached document is kept +// only gzip-compressed, and is decompressed for each caller that needs the +// plain bytes: clients not accepting gzip, and handlers reading the document. +// The compressed copy was made in memory by gzipIfSmaller, so reading it back +// fails only on a bug; content returns nil then. +func (m rewrittenMetadata) content() []byte { + if m.plain != nil || m.gzipped == nil { + return m.plain + } + zr, err := gzip.NewReader(bytes.NewReader(m.gzipped)) + if err != nil { + return nil + } + out := bytes.NewBuffer(make([]byte, 0, m.size)) + if _, err := io.Copy(out, zr); err != nil { + return nil + } + return out.Bytes() +} + +// identity returns m to be served without its gzip copy. +func (m rewrittenMetadata) identity() rewrittenMetadata { + m.plain = m.content() + m.gzipped = nil + return m +} + +// compact returns m as the cache keeps it: only the gzip copy when there is +// one. +func (m rewrittenMetadata) compact() rewrittenMetadata { + if m.gzipped != nil { + m.plain = nil + } + return m } // metadataETag returns the strong ETag of a rewritten document. @@ -159,29 +206,71 @@ func (c *rewriteCache) get(key string) (rewrittenMetadata, bool) { } c.mu.Lock() defer c.mu.Unlock() - el, ok := c.entries[key] + e, ok := c.lookup(key, c.clock()) if !ok { return rewrittenMetadata{}, false } + return e.rewrittenMetadata, true +} + +// lookup returns the live entry for key and marks it recently used. An +// expired entry is dropped. Called with mu held. +func (c *rewriteCache) lookup(key string, now time.Time) (*rewriteEntry, bool) { + el, ok := c.entries[key] + if !ok { + return nil, false + } + e := el.Value.(*rewriteEntry) + if !e.expires.IsZero() && !now.Before(e.expires) { + c.remove(el) + return nil, false + } c.order.MoveToFront(el) - return el.Value.(*rewriteEntry).rewrittenMetadata, true + return e, true +} + +func (c *rewriteCache) clock() time.Time { + if c.now == nil { + return time.Now() + } + return c.now() +} + +// remove drops an entry. Called with mu held. +func (c *rewriteCache) remove(el *list.Element) { + e := el.Value.(*rewriteEntry) + c.order.Remove(el) + delete(c.entries, e.key) + c.size -= e.size() } // rewrite returns rewrite(in) with its ETag and gzip copy, from the cache -// when it can. Callers must treat the returned bytes as read-only: a cached -// result is shared. A caller waiting on another's rewrite leaves when ctx -// ends; the rewrite itself always runs to completion, so the result is cached -// for the next request. -func (c *rewriteCache) rewrite(ctx context.Context, key string, in []byte, rewrite func([]byte) ([]byte, error)) (rewrittenMetadata, error) { +// when it can. A ttl above zero makes the result expire after that long. +// Callers must treat the returned bytes as read-only: a cached result is +// shared. A caller waiting on another's rewrite leaves when ctx ends; the +// rewrite itself always runs to completion, so the result is cached for the +// next request. +func (c *rewriteCache) rewrite(ctx context.Context, key string, in []byte, expiry func(start time.Time) time.Time, rewrite func([]byte) ([]byte, error)) (rewrittenMetadata, error) { if c == nil { return rewriteWithETag(in, rewrite) } + return c.produce(ctx, key, expiry, func() (rewrittenMetadata, error) { + m, err := rewriteWithETag(in, rewrite) + if err == nil { + m.gzipped = gzipIfSmaller(m.plain) + } + return m, err + }) +} + +// produce is rewrite for a document that build makes with its validators +// and gzip copy. +func (c *rewriteCache) produce(ctx context.Context, key string, expiry func(start time.Time) time.Time, build func() (rewrittenMetadata, error)) (rewrittenMetadata, error) { c.mu.Lock() - if el, ok := c.entries[key]; ok { - c.order.MoveToFront(el) + if e, ok := c.lookup(key, c.clock()); ok { c.mu.Unlock() - return el.Value.(*rewriteEntry).rewrittenMetadata, nil + return e.rewrittenMetadata, nil } if f, ok := c.inFlight[key]; ok { c.mu.Unlock() @@ -196,19 +285,23 @@ func (c *rewriteCache) rewrite(ctx context.Context, key string, in []byte, rewri c.inFlight[key] = f c.mu.Unlock() + // expiry is given the time from before the rewrite, so an entry never + // outlives the time its cooldown decisions were made at. + start := c.clock() defer func() { c.mu.Lock() delete(c.inFlight, key) if f.err == nil { - c.add(&rewriteEntry{key: key, rewrittenMetadata: f.m}) + var expires time.Time + if expiry != nil { + expires = expiry(start) + } + c.add(&rewriteEntry{key: key, rewrittenMetadata: f.m.compact(), expires: expires}) } c.mu.Unlock() close(f.done) }() - f.m, f.err = rewriteWithETag(in, rewrite) - if f.err == nil { - f.m.gzipped = gzipIfSmaller(f.m.body) - } + f.m, f.err = build() return f.m, f.err } @@ -218,7 +311,7 @@ func rewriteWithETag(in []byte, rewrite func([]byte) ([]byte, error)) (rewritten if err != nil { return rewrittenMetadata{}, err } - return rewrittenMetadata{body: out, metadataValidators: metadataValidators{etag: metadataETag(out)}}, nil + return rewrittenMetadata{plain: out, metadataValidators: metadataValidators{etag: metadataETag(out)}, size: len(out)}, nil } // gzipIfSmaller returns body gzip-compressed, or nil when compressing does @@ -243,60 +336,125 @@ func (c *rewriteCache) add(e *rewriteEntry) { if n > c.maxBytes { return } + if old, ok := c.entries[e.key]; ok { + c.remove(old) + } c.entries[e.key] = c.order.PushFront(e) c.size += n for c.size > c.maxBytes { - oldest := c.order.Back() - e := oldest.Value.(*rewriteEntry) - c.order.Remove(oldest) - delete(c.entries, e.key) - c.size -= e.size() + c.remove(c.order.Back()) } } -// len reports how many rewrites are cached. -func (c *rewriteCache) len() int { - if c == nil { - return 0 - } - c.mu.Lock() - defer c.mu.Unlock() - return len(c.entries) -} - // cachedRewrite rewrites a metadata document through the proxy's rewrite // cache and returns it with its validators. digest identifies in when the -// metadata cache stored it, and is empty otherwise. Cooldown filtering depends -// on the current time, so with cooldown on a cached rewrite could keep hiding -// a version past its cooldown; those rewrites always run, with no -// Last-Modified, and when digest is known their ETag comes from their inputs -// rather than from hashing each output again. Their ETag also changes with -// every restart, so replicas would never agree on a date for them. +// metadata cache stored it, and is empty otherwise; when known it keys the +// cache, so the document isn't hashed again. +// +// With cooldown on, the cached rewrite expires when the first version it +// held back leaves cooldown, and after p.cooldownRewriteTTL at the latest. Its +// ETag is the hash of its output, and it is dated like any other, so clients +// revalidate with either validator and get the gzip copy. +// +// Without the rewrite cache, cooldown rewrites run on every request and go +// undated: when digest is known their ETag comes from their inputs rather +// than from hashing each output again, and that ETag changes with every +// restart, so replicas would never agree on a date for it. func (p *Proxy) cachedRewrite(ctx context.Context, ecosystem, proxyURL, name string, in []byte, digest string, rewrite keepingRewrite) (rewrittenMetadata, error) { - if p.cooldownEnabled() && digest != "" { - out, kept, err := rewrite(in) - if err != nil { - return rewrittenMetadata{}, err - } - return rewrittenMetadata{body: out, metadataValidators: metadataValidators{etag: keptVersionsETag(digest, proxyURL, name, kept)}}, nil - } rewriteOnly := func(b []byte) ([]byte, error) { out, _, err := rewrite(b) return out, err } - var m rewrittenMetadata - var err error - if p.rewrites == nil || p.cooldownEnabled() { - m, err = rewriteWithETag(in, rewriteOnly) - } else { - m, err = p.rewrites.rewrite(ctx, rewriteCacheKey(ecosystem, proxyURL, name, in), in, rewriteOnly) + cooldown := p.cooldownEnabled() + + if p.rewrites != nil { + key := rewriteCacheKeyForDigest(ecosystem, proxyURL, name, digest) + if digest == "" { + key = rewriteCacheKey(ecosystem, proxyURL, name, in) + } + var expiry func(time.Time) time.Time + if cooldown { + // Recording runs from before the rewrite until after it, so it + // hears of every version the rewrite holds back. + rec := p.watchCooldown() + defer p.unwatchCooldown(rec) + expiry = func(start time.Time) time.Time { return p.cooldownExpiry(rec, start) } + } + m, err := p.rewrites.rewrite(ctx, key, in, expiry, rewriteOnly) + if err == nil { + m.lastModified = p.metadataDate(ecosystem, proxyURL, name, m.etag) + } + return m, err } - if err == nil && !p.cooldownEnabled() { + + if cooldown && digest != "" { + out, kept, err := rewrite(in) + if err != nil { + return rewrittenMetadata{}, err + } + return rewrittenMetadata{plain: out, metadataValidators: metadataValidators{etag: keptVersionsETag(digest, proxyURL, name, kept)}, size: len(out)}, nil + } + m, err := rewriteWithETag(in, rewriteOnly) + if err == nil && !cooldown { m.lastModified = p.metadataDate(ecosystem, proxyURL, name, m.etag) } return m, err } +// streamedRewrite rewrites a document stored in storage, through the +// proxy's rewrite cache, without holding the document or its rewrite in +// memory uncompressed. rewrite is given a way to open the stored document, +// as often as it needs to read it, and writes the rewritten document to w. +// The result is cached under the same key cachedRewrite uses for the +// document, and expires the same way with cooldown on. +// +// It returns errMetadataNotStored without the rewrite cache, which the +// result has to be kept in. +func (p *Proxy) streamedRewrite(ctx context.Context, ecosystem, proxyURL, name string, entry *database.MetadataCacheEntry, rewrite func(open func() (io.ReadCloser, error), w io.Writer) error) (rewrittenMetadata, error) { + if p.rewrites == nil { + return rewrittenMetadata{}, errMetadataNotStored + } + var expiry func(time.Time) time.Time + if p.cooldownEnabled() { + rec := p.watchCooldown() + defer p.unwatchCooldown(rec) + expiry = func(start time.Time) time.Time { return p.cooldownExpiry(rec, start) } + } + key := rewriteCacheKeyForDigest(ecosystem, proxyURL, name, entry.ContentDigest.String) + m, err := p.rewrites.produce(ctx, key, expiry, func() (rewrittenMetadata, error) { + // The rewrite runs to completion for the cache even when the + // caller leaves. + readCtx := context.WithoutCancel(ctx) + return gzipRewrite(func(w io.Writer) error { + return rewrite(func() (io.ReadCloser, error) { return p.openStoredMetadata(readCtx, entry) }, w) + }) + }) + if err == nil { + m.lastModified = p.metadataDate(ecosystem, proxyURL, name, m.etag) + } + return m, err +} + +// gzipRewrite runs write and keeps what it writes gzip-compressed only, with +// the ETag and length of the uncompressed output. +func gzipRewrite(write func(w io.Writer) error) (rewrittenMetadata, error) { + var buf bytes.Buffer + zw := gzip.NewWriter(&buf) + sum := sha256.New() + n := &countingWriter{w: io.Discard} + if err := write(io.MultiWriter(zw, sum, n)); err != nil { + return rewrittenMetadata{}, err + } + if err := zw.Close(); err != nil { + return rewrittenMetadata{}, err + } + return rewrittenMetadata{ + metadataValidators: metadataValidators{etag: `"` + hex.EncodeToString(sum.Sum(nil)) + `"`}, + gzipped: buf.Bytes(), + size: int(n.n), + }, nil +} + // uncachedRewrite gives a rewrite made outside the cache its validators: an // ETag of the output itself and, as cachedRewrite does, a date that replicas // agree on. @@ -305,7 +463,7 @@ func (p *Proxy) uncachedRewrite(ecosystem, proxyURL, name string, out []byte) re if !p.cooldownEnabled() { v.lastModified = p.metadataDate(ecosystem, proxyURL, name, v.etag) } - return rewrittenMetadata{body: out, metadataValidators: v} + return rewrittenMetadata{plain: out, metadataValidators: v, size: len(out)} } func (p *Proxy) cooldownEnabled() bool { @@ -314,31 +472,72 @@ func (p *Proxy) cooldownEnabled() bool { // storedRewrite returns the cached rewrite of the metadata stored for // ecosystem and cacheKey, when that metadata is still within its TTL and a -// rewrite of it is cached. It reads only the cache row, never the stored -// document, so a repeated request for a large packument costs a database -// lookup instead of reading and hashing the whole document again. When it -// reports false the caller takes the usual fetch and rewrite path. +// rewrite of it is cached and has not expired. It reads only the cache row, +// never the stored document, so a repeated request for a large packument +// costs a database lookup instead of reading and hashing the whole document +// again. When it reports false the caller takes the usual fetch and rewrite +// path. func (p *Proxy) storedRewrite(ecosystem, cacheKey, proxyURL, name string) (rewrittenMetadata, bool) { - if p.rewrites == nil || p.cooldownEnabled() { - return rewrittenMetadata{}, false + m, _, ok := p.storedRewriteVariant(ecosystem, cacheKey, proxyURL, name, nil) + return m, ok +} + +// storedRewriteVariant is storedRewrite for a rewrite whose output depends on +// more than the stored document. variant is given the stored content type +// and returns the rest of what the rewrite depends on, as passed to +// variantDigest; nil means nothing else. It also returns the stored content +// type, as a fetch of the document would. +func (p *Proxy) storedRewriteVariant(ecosystem, cacheKey, proxyURL, name string, variant func(contentType string) []string) (rewrittenMetadata, string, bool) { + if p.rewrites == nil { + return rewrittenMetadata{}, "", false } if !p.CacheMetadata || p.DB == nil || p.MetadataTTL <= 0 { - return rewrittenMetadata{}, false + return rewrittenMetadata{}, "", false } entry, err := p.DB.GetMetadataCache(ecosystem, cacheKey) if err != nil || entry == nil || !entry.ContentDigest.Valid || entry.ContentEncoding.String != "" { - return rewrittenMetadata{}, false + return rewrittenMetadata{}, "", false } if !entry.FetchedAt.Valid || time.Since(entry.FetchedAt.Time) >= p.MetadataTTL { - return rewrittenMetadata{}, false + return rewrittenMetadata{}, "", false } - m, ok := p.rewrites.get(rewriteCacheKeyForDigest(ecosystem, proxyURL, name, entry.ContentDigest.String)) + contentType := contentTypeJSON + if entry.ContentType.Valid { + contentType = entry.ContentType.String + } + digest := entry.ContentDigest.String + if variant != nil { + digest = variantDigest(digest, nil, variant(contentType)...) + } + m, ok := p.rewrites.get(rewriteCacheKeyForDigest(ecosystem, proxyURL, name, digest)) if !ok { - return rewrittenMetadata{}, false + return rewrittenMetadata{}, "", false } m.lastModified = p.metadataDate(ecosystem, proxyURL, name, m.etag) - metrics.RecordCacheHit(ecosystem) - return m, true + metrics.RecordMetadataCacheHit(ecosystem, m.size) + p.recordMetadataRead(entry) + return m, contentType, true +} + +// variantDigest returns a digest for a rewrite of in that also depends on +// parts, such as the content type or the versions a filter removes, so that +// rewrites differing in them are cached apart. digest is in's digest as the +// metadata cache records it, or empty to hash in. Passed to cachedRewrite in +// place of the document's digest, it keeps the metadata date keyed by the +// package alone. +func variantDigest(digest string, in []byte, parts ...string) string { + if digest == "" { + sum := sha256.Sum256(in) + digest = "sha256:" + hex.EncodeToString(sum[:]) + } + h := sha256.New() + var length []byte + for _, part := range parts { + length = binary.AppendUvarint(length[:0], uint64(len(part))) + _, _ = h.Write(length) + _, _ = io.WriteString(h, part) + } + return digest + "+" + hex.EncodeToString(h.Sum(nil)) } // serveRewrittenMetadata writes rewritten metadata with its validators, or @@ -346,12 +545,18 @@ func (p *Proxy) storedRewrite(ecosystem, cacheKey, proxyURL, name string) (rewri // accepting gzip gets the compressed copy when there is one. Being another // representation, it has an ETag of its own. func serveRewrittenMetadata(w http.ResponseWriter, r *http.Request, m rewrittenMetadata) { - body, etag := m.body, m.etag + serveRewrittenMetadataAs(w, r, m, contentTypeJSON) +} + +// serveRewrittenMetadataAs is serveRewrittenMetadata for a document of +// another content type. +func serveRewrittenMetadataAs(w http.ResponseWriter, r *http.Request, m rewrittenMetadata, contentType string) { + etag := m.etag compressed := m.gzipped != nil && acceptsGzip(r) if compressed { - body, etag = m.gzipped, gzipETag(m.etag) + etag = gzipETag(m.etag) } - w.Header().Set("Vary", headerAcceptEncoding) + ensureVary(w.Header(), headerAcceptEncoding) w.Header().Set(headerETag, etag) if !m.lastModified.IsZero() { w.Header().Set(headerLastModified, m.lastModified.UTC().Format(http.TimeFormat)) @@ -360,12 +565,40 @@ func serveRewrittenMetadata(w http.ResponseWriter, r *http.Request, m rewrittenM w.WriteHeader(http.StatusNotModified) return } - w.Header().Set(headerContentType, contentTypeJSON) + w.Header().Set(headerContentType, contentType) if compressed { w.Header().Set(headerContentEncoding, "gzip") + w.WriteHeader(http.StatusOK) + _, _ = w.Write(m.gzipped) + return + } + if m.plain == nil && m.gzipped != nil { + // Decompressed as it is sent, rather than into a copy of the + // whole document. + zr, err := gzip.NewReader(bytes.NewReader(m.gzipped)) + if err != nil { + http.Error(w, "failed to read cached metadata", http.StatusInternalServerError) + return + } + w.Header().Set(headerContentLength, strconv.Itoa(m.size)) + w.WriteHeader(http.StatusOK) + _, _ = io.Copy(w, zr) + return } w.WriteHeader(http.StatusOK) - _, _ = w.Write(body) + _, _ = w.Write(m.plain) +} + +// ensureVary adds field to the Vary header unless it is listed already. +func ensureVary(header http.Header, field string) { + for _, value := range header.Values("Vary") { + for listed := range strings.SplitSeq(value, ",") { + if strings.EqualFold(strings.TrimSpace(listed), field) { + return + } + } + } + header.Add("Vary", field) } // gzipETag returns the ETag of the gzip representation of the document @@ -423,4 +656,7 @@ func notModified(r *http.Request, etag string, lastModified time.Time) bool { // room for maxBytes of output. Zero or less disables it. func (p *Proxy) SetMetadataRewriteCacheSize(maxBytes int64) { p.rewrites = newRewriteCache(maxBytes) + if p.rewrites != nil { + p.rewrites.now = p.clock + } } diff --git a/internal/handler/rewrite_cache_test.go b/internal/handler/rewrite_cache_test.go index 8584312..3f4c062 100644 --- a/internal/handler/rewrite_cache_test.go +++ b/internal/handler/rewrite_cache_test.go @@ -1,6 +1,7 @@ package handler import ( + "bytes" "context" "errors" "net/http" @@ -9,6 +10,7 @@ import ( "sync" "sync/atomic" "testing" + "time" "github.com/git-pkgs/cooldown" ) @@ -42,9 +44,9 @@ func TestRewriteCache_RepeatServesCachedRewrite(t *testing.T) { key := rewriteCacheKey("npm", "http://proxy", "left-pad", []byte("doc")) for range 3 { - m, err := c.rewrite(context.Background(), key, []byte("doc"), r.fn) - if err != nil || string(m.body) != "DOC" { - t.Fatalf("rewrite = %q, %v", m.body, err) + m, err := c.rewrite(context.Background(), key, []byte("doc"), nil, r.fn) + if err != nil || string(m.content()) != "DOC" { + t.Fatalf("rewrite = %q, %v", m.content(), err) } } if got := r.calls.Load(); got != 1 { @@ -58,9 +60,9 @@ func TestRewriteCache_NewUpstreamBytesRewriteAgain(t *testing.T) { for _, doc := range []string{"v1", "v2"} { key := rewriteCacheKey("npm", "http://proxy", "left-pad", []byte(doc)) - m, err := c.rewrite(context.Background(), key, []byte(doc), r.fn) - if err != nil || string(m.body) != strings.ToUpper(doc) { - t.Fatalf("rewrite(%s) = %q, %v", doc, m.body, err) + m, err := c.rewrite(context.Background(), key, []byte(doc), nil, r.fn) + if err != nil || string(m.content()) != strings.ToUpper(doc) { + t.Fatalf("rewrite(%s) = %q, %v", doc, m.content(), err) } } if got := r.calls.Load(); got != 2 { @@ -80,11 +82,11 @@ func TestRewriteCache_ConcurrentRequestsShareRewrite(t *testing.T) { outs := make(chan string, n) run := func() { - m, err := c.rewrite(context.Background(), key, []byte("doc"), r.fn) + m, err := c.rewrite(context.Background(), key, []byte("doc"), nil, r.fn) if err != nil { t.Error(err) } - outs <- string(m.body) + outs <- string(m.content()) } go run() <-r.entered @@ -113,21 +115,21 @@ func TestRewriteCache_WaiterLeavingKeepsRewrite(t *testing.T) { first := make(chan error, 1) go func() { - _, err := c.rewrite(context.Background(), key, []byte("doc"), r.fn) + _, err := c.rewrite(context.Background(), key, []byte("doc"), nil, r.fn) first <- err }() <-r.entered ctx, cancel := context.WithCancel(context.Background()) cancel() - if _, err := c.rewrite(ctx, key, []byte("doc"), r.fn); !errors.Is(err, context.Canceled) { + if _, err := c.rewrite(ctx, key, []byte("doc"), nil, r.fn); !errors.Is(err, context.Canceled) { t.Errorf("waiter err = %v, want context.Canceled", err) } close(r.release) if err := <-first; err != nil { t.Fatal(err) } - if m, err := c.rewrite(context.Background(), key, []byte("doc"), r.fn); err != nil || string(m.body) != "DOC" { - t.Errorf("cached rewrite = %q, %v", m.body, err) + if m, err := c.rewrite(context.Background(), key, []byte("doc"), nil, r.fn); err != nil || string(m.content()) != "DOC" { + t.Errorf("cached rewrite = %q, %v", m.content(), err) } if got := r.calls.Load(); got != 1 { t.Errorf("rewrites = %d, want 1", got) @@ -140,18 +142,18 @@ func TestRewriteCache_EvictsLeastRecentlyUsed(t *testing.T) { keyFor := func(doc string) string { return rewriteCacheKey("npm", "http://proxy", doc, []byte(doc)) } for _, doc := range []string{"aaa", "bbb"} { - _, _ = c.rewrite(context.Background(), keyFor(doc), []byte(doc), r.fn) + _, _ = c.rewrite(context.Background(), keyFor(doc), []byte(doc), nil, r.fn) } - _, _ = c.rewrite(context.Background(), keyFor("aaa"), []byte("aaa"), r.fn) // aaa is now the most recent - _, _ = c.rewrite(context.Background(), keyFor("ccc"), []byte("ccc"), r.fn) // evicts bbb + _, _ = c.rewrite(context.Background(), keyFor("aaa"), []byte("aaa"), nil, r.fn) // aaa is now the most recent + _, _ = c.rewrite(context.Background(), keyFor("ccc"), []byte("ccc"), nil, r.fn) // evicts bbb before := r.calls.Load() - _, _ = c.rewrite(context.Background(), keyFor("aaa"), []byte("aaa"), r.fn) - _, _ = c.rewrite(context.Background(), keyFor("ccc"), []byte("ccc"), r.fn) + _, _ = c.rewrite(context.Background(), keyFor("aaa"), []byte("aaa"), nil, r.fn) + _, _ = c.rewrite(context.Background(), keyFor("ccc"), []byte("ccc"), nil, r.fn) if got := r.calls.Load() - before; got != 0 { t.Errorf("aaa and ccc rewritten %d times, want both still cached", got) } - _, _ = c.rewrite(context.Background(), keyFor("bbb"), []byte("bbb"), r.fn) + _, _ = c.rewrite(context.Background(), keyFor("bbb"), []byte("bbb"), nil, r.fn) if got := r.calls.Load() - before; got != 1 { t.Errorf("bbb should have been evicted and rewritten") } @@ -162,7 +164,7 @@ func TestRewriteCache_OutputLargerThanCacheIsNotStored(t *testing.T) { var r countingRewrite key := rewriteCacheKey("npm", "http://proxy", "big", []byte("big")) - _, _ = c.rewrite(context.Background(), key, []byte("big"), r.fn) + _, _ = c.rewrite(context.Background(), key, []byte("big"), nil, r.fn) if c.len() != 0 { t.Errorf("cached %d entries, want 0", c.len()) } @@ -175,7 +177,7 @@ func TestRewriteCache_ErrorsAreNotCached(t *testing.T) { key := rewriteCacheKey("npm", "http://proxy", "broken", []byte("doc")) for range 2 { - if _, err := c.rewrite(context.Background(), key, []byte("doc"), failing); err == nil { + if _, err := c.rewrite(context.Background(), key, []byte("doc"), nil, failing); err == nil { t.Fatal("expected the rewrite error") } } @@ -197,11 +199,14 @@ func TestCachedRewrite_DisabledRewritesEveryTime(t *testing.T) { } } -// TestCachedRewrite_CooldownBypassesCache asserts that with cooldown on every -// request is rewritten: cooldown filtering depends on the current time, so a -// cached rewrite could keep hiding a version after its cooldown ends. -func TestCachedRewrite_CooldownBypassesCache(t *testing.T) { +// TestCachedRewrite_CooldownExpires asserts that with cooldown on a rewrite +// is cached for maxCooldownRewriteTTL only: cooldown filtering depends on the +// current time, so a cached rewrite would otherwise keep hiding a version +// after its cooldown ends. +func TestCachedRewrite_CooldownExpires(t *testing.T) { proxy, _, _, _ := setupTestProxy(t) + clock := &testClock{t: time.Date(2026, 10, 10, 12, 0, 0, 0, time.UTC)} + proxy.now = clock.now proxy.SetMetadataRewriteCacheSize(1 << 20) proxy.Cooldown = &cooldown.Config{Default: "3d"} var r countingRewrite @@ -209,8 +214,33 @@ func TestCachedRewrite_CooldownBypassesCache(t *testing.T) { for range 2 { _, _ = proxy.cachedRewrite(context.Background(), "npm", "http://proxy", "left-pad", []byte("doc"), "", r.keeping) } + if got := r.calls.Load(); got != 1 { + t.Errorf("rewrites within the TTL = %d, want 1", got) + } + + clock.advance(maxCooldownRewriteTTL) + _, _ = proxy.cachedRewrite(context.Background(), "npm", "http://proxy", "left-pad", []byte("doc"), "", r.keeping) if got := r.calls.Load(); got != 2 { - t.Errorf("rewrites = %d, want 2", got) + t.Errorf("rewrites after the TTL = %d, want 2", got) + } +} + +// TestRewriteCacheExpiredEntryFreesRoom asserts that an expired entry is +// dropped when looked up, so its size no longer counts. +func TestRewriteCacheExpiredEntryFreesRoom(t *testing.T) { + c := newRewriteCache(1 << 20) + clock := &testClock{t: time.Date(2026, 10, 10, 12, 0, 0, 0, time.UTC)} + c.now = clock.now + upper := func(b []byte) ([]byte, error) { return bytes.ToUpper(b), nil } + if _, err := c.rewrite(context.Background(), "k", []byte("doc"), func(start time.Time) time.Time { return start.Add(time.Minute) }, upper); err != nil { + t.Fatal(err) + } + clock.advance(time.Minute) + if _, ok := c.get("k"); ok { + t.Fatal("expired entry was served") + } + if c.size != 0 || c.order.Len() != 0 { + t.Errorf("size %d, entries %d after expiry; want 0", c.size, c.order.Len()) } } @@ -261,3 +291,31 @@ func TestMetadataHandlers_ServeCachedRewrite(t *testing.T) { } } } + +// len reports how many rewrites are cached. +func (c *rewriteCache) len() int { + if c == nil { + return 0 + } + c.mu.Lock() + defer c.mu.Unlock() + return len(c.entries) +} + +// TestCooldownRewriteTTL checks that the cap on a rewrite filtered by +// cooldown is the shortest cooldown, between a minute and a day. +func TestCooldownRewriteTTL(t *testing.T) { + for _, tc := range []struct { + shortest, want time.Duration + }{ + {0, 24 * time.Hour}, + {72 * time.Hour, 24 * time.Hour}, + {2 * time.Hour, 2 * time.Hour}, + {10 * time.Second, time.Minute}, + } { + p := &Proxy{ShortestCooldown: tc.shortest} + if got := p.cooldownRewriteTTL(); got != tc.want { + t.Errorf("shortest cooldown %v: TTL = %v, want %v", tc.shortest, got, tc.want) + } + } +} diff --git a/internal/handler/rpm.go b/internal/handler/rpm.go index 3321ccc..7363cca 100644 --- a/internal/handler/rpm.go +++ b/internal/handler/rpm.go @@ -3,6 +3,7 @@ package handler import ( "fmt" "net/http" + pathpkg "path" "regexp" "strings" @@ -61,7 +62,7 @@ func NewRPMHandlerWithUpstream(proxy *Proxy, proxyURL, upstreamURL string) *RPMH // Routes returns the HTTP handler for RPM requests. // Mount this at /rpm on your router. func (h *RPMHandler) Routes() http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + return rejectQueryChars(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.Method != http.MethodGet && r.Method != http.MethodHead { http.Error(w, "method not allowed", http.StatusMethodNotAllowed) return @@ -78,21 +79,31 @@ func (h *RPMHandler) Routes() http.Handler { switch { case strings.HasSuffix(path, ".rpm"): // Package downloads - cache these - h.handlePackageDownload(w, r, path) + h.handlePackageDownload(w, r, cleanRPMPath(path)) case strings.Contains(path, "/repodata/"): - // Repository metadata - proxy without caching (changes frequently) + // Repository metadata h.handleMetadata(w, r, path) default: // Other files - proxy directly h.proxyFile(w, r, path) } - }) + })) +} + +// cleanRPMPath drops empty and "." segments from a relative path, so each +// package has one cache key. ".." segments are rejected before this. +func cleanRPMPath(p string) string { + return strings.TrimPrefix(pathpkg.Clean("/"+p), "/") } // handlePackageDownload fetches and caches .rpm packages. // Path format varies by repo structure, e.g.: // - releases/39/Everything/x86_64/os/Packages/n/nginx-1.24.0-1.fc39.x86_64.rpm // - updates/39/Everything/x86_64/Packages/n/nginx-1.24.0-2.fc39.x86_64.rpm +// +// The cache key is the full path, since repositories under one upstream +// (Rocky and Alma on one mirror, say) can ship different bytes under one +// filename. func (h *RPMHandler) handlePackageDownload(w http.ResponseWriter, r *http.Request, path string) { // Parse the path to extract package info name, version, arch := h.parseRPMPath(path) @@ -102,14 +113,13 @@ func (h *RPMHandler) handlePackageDownload(w http.ResponseWriter, r *http.Reques return } - filename := path[strings.LastIndex(path, "/")+1:] downloadURL := fmt.Sprintf("%s/%s", h.upstreamURL, path) h.proxy.Logger.Info("rpm package download", - "name", name, "version", version, "arch", arch, "filename", filename) + "name", name, "version", version, "arch", arch, "path", path) result, err := h.proxy.GetOrFetchArtifactFromURL( - r.Context(), "rpm", name, version, filename, downloadURL) + r.Context(), "rpm", name, version, path, downloadURL) if err != nil { h.proxy.serveArtifactError(w, err, "failed to fetch package") return @@ -119,11 +129,48 @@ func (h *RPMHandler) handlePackageDownload(w http.ResponseWriter, r *http.Reques ServeArtifactRequest(w, r, result) } -// handleMetadata proxies repository metadata files (repomd.xml, primary.xml.gz, etc.). -// These change frequently so we don't cache them. +// handleMetadata proxies repository metadata files (repomd.xml, +// primary.xml.gz, etc.). repomd.xml changes with every repository update and +// follows the metadata TTL. The files it points at are usually named after +// their own checksum and so never change; those are kept for good. Plainly +// named ones follow the cached repomd.xml (see proxyListedIndex). func (h *RPMHandler) handleMetadata(w http.ResponseWriter, r *http.Request, path string) { - cacheKey := strings.ReplaceAll(path, "/", "_") - h.proxy.ProxyCached(w, r, fmt.Sprintf("%s/%s", h.upstreamURL, path), "rpm", cacheKey, "*/*") + upstreamURL := fmt.Sprintf("%s/%s", h.upstreamURL, path) + if rpmContentAddressed(path) { + h.proxy.proxyImmutable(w, r, upstreamURL, "rpm", h.metadataCacheKey(path), "*/*") + return + } + i := strings.LastIndex(path, "/repodata/") + if strings.HasPrefix(path[i:], "/repodata/repomd.xml") { + h.proxy.ProxyCached(w, r, upstreamURL, "rpm", h.metadataCacheKey(path), "*/*") + return + } + // Plainly named files (createrepo --simple-md-filenames) follow the + // cached repomd.xml that lists them. + repomd := h.proxy.readCachedRelease(r.Context(), "rpm", h.metadataCacheKey(path[:i]+"/repodata/repomd.xml")) + var want string + if repomd != nil { + want = repomdSHA256(repomd.body, path[i+1:]) + } + h.proxy.proxyListedIndex(w, r, upstreamURL, "rpm", h.metadataCacheKey(path), repomd, want) +} + +// rpmChecksumPrefix matches a repodata filename that createrepo prefixed +// with the file's checksum: -primary.xml.gz. The hex lengths are those +// of the checksum types createrepo_c offers: SHA-1, SHA-224, SHA-256, +// SHA-384 and SHA-512. Repositories built with --simple-md-filenames use +// plain names, which can be replaced in place and follow the TTL. +var rpmChecksumPrefix = regexp.MustCompile(`^(?:[0-9a-f]{40}|[0-9a-f]{56}|[0-9a-f]{64}|[0-9a-f]{96}|[0-9a-f]{128})-[^/]+$`) + +// rpmContentAddressed reports whether a repodata path names a file after +// its checksum, so its content never changes. +func rpmContentAddressed(path string) bool { + return rpmChecksumPrefix.MatchString(path[strings.LastIndex(path, "/")+1:]) +} + +// metadataCacheKey is the metadata cache key of a repository path. +func (h *RPMHandler) metadataCacheKey(path string) string { + return hashedCacheKey(h.upstreamURL, path) } // proxyFile proxies any file directly without caching. diff --git a/internal/handler/rpm_test.go b/internal/handler/rpm_test.go index 3526dbd..d9561e3 100644 --- a/internal/handler/rpm_test.go +++ b/internal/handler/rpm_test.go @@ -1,9 +1,14 @@ package handler import ( + "io" + "net/http" + "net/http/httptest" + "sync/atomic" "testing" "github.com/git-pkgs/purl" + "github.com/git-pkgs/registries/fetch" ) func TestRPMHandler_parseRPMPath(t *testing.T) { @@ -52,3 +57,90 @@ func TestRPMRetentionKey(t *testing.T) { t.Error("rpmRetentionKey(nil) accepted") } } + +// TestRPMHandler_PackageDownloadCachesPerRepository checks that two +// repositories under one upstream that ship the same filename with different +// bytes are cached apart, as on a mirror root serving several distributions. +func TestRPMHandler_PackageDownloadCachesPerRepository(t *testing.T) { + packages := map[string]string{ + "/rocky/9/BaseOS/x86_64/os/Packages/b/bash-5.1.8-9.el9.x86_64.rpm": "rocky bash", + "/almalinux/9/BaseOS/x86_64/os/Packages/b/bash-5.1.8-9.el9.x86_64.rpm": "alma bash", + } + + var available atomic.Bool + available.Store(true) + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + data, ok := packages[r.URL.Path] + if !available.Load() || !ok { + http.NotFound(w, r) + return + } + _, _ = w.Write([]byte(data)) + })) + defer upstream.Close() + + proxy, _, _, _ := setupTestProxy(t) + fetcher := fetch.NewFetcher(fetch.WithHTTPClient(upstream.Client()), fetch.WithMaxRetries(0)) + proxy.Fetcher = fetcher + t.Cleanup(func() { _ = fetcher.Close() }) + srv := httptest.NewServer(NewRPMHandlerWithUpstream(proxy, testProxyURL, upstream.URL).Routes()) + defer srv.Close() + + for round := range 2 { + for path, want := range packages { + resp, err := http.Get(srv.URL + path) + if err != nil { + t.Fatal(err) + } + body, _ := io.ReadAll(resp.Body) + _ = resp.Body.Close() + if resp.StatusCode != http.StatusOK || string(body) != want { + t.Errorf("round %d %s: %d %q, want 200 %q", round, path, resp.StatusCode, body, want) + } + } + // The second round must come from the cache. + available.Store(false) + } +} + +// TestRPMHandler_PackageDownloadCleansPath checks that spellings of one +// path with empty or "." segments share one cache entry. +func TestRPMHandler_PackageDownloadCleansPath(t *testing.T) { + const want = "bash" + var hits atomic.Int32 + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/rocky/9/BaseOS/x86_64/os/Packages/b/bash-5.1.8-9.el9.x86_64.rpm" { + http.NotFound(w, r) + return + } + hits.Add(1) + _, _ = w.Write([]byte(want)) + })) + defer upstream.Close() + + proxy, _, _, _ := setupTestProxy(t) + fetcher := fetch.NewFetcher(fetch.WithHTTPClient(upstream.Client()), fetch.WithMaxRetries(0)) + proxy.Fetcher = fetcher + t.Cleanup(func() { _ = fetcher.Close() }) + srv := httptest.NewServer(NewRPMHandlerWithUpstream(proxy, testProxyURL, upstream.URL).Routes()) + defer srv.Close() + + for _, path := range []string{ + "/rocky/9/BaseOS/x86_64/os/Packages/b/bash-5.1.8-9.el9.x86_64.rpm", + "/rocky//9/BaseOS/x86_64/os/Packages/b/bash-5.1.8-9.el9.x86_64.rpm", + "/rocky/./9/BaseOS/x86_64/os/Packages/b/bash-5.1.8-9.el9.x86_64.rpm", + } { + resp, err := http.Get(srv.URL + path) + if err != nil { + t.Fatal(err) + } + body, _ := io.ReadAll(resp.Body) + _ = resp.Body.Close() + if resp.StatusCode != http.StatusOK || string(body) != want { + t.Errorf("%s: %d %q, want 200 %q", path, resp.StatusCode, body, want) + } + } + if n := hits.Load(); n != 1 { + t.Errorf("upstream fetched %d times, want 1", n) + } +} diff --git a/internal/handler/shared_holds_test.go b/internal/handler/shared_holds_test.go new file mode 100644 index 0000000..5536c00 --- /dev/null +++ b/internal/handler/shared_holds_test.go @@ -0,0 +1,170 @@ +package handler + +import ( + "context" + "errors" + "io" + "log/slog" + "net/http" + "net/http/httptest" + "path/filepath" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/git-pkgs/proxy/internal/database" + upstreamhttp "github.com/git-pkgs/proxy/internal/httpclient" + "github.com/git-pkgs/proxy/internal/metrics" + registryclient "github.com/git-pkgs/registries/client" + "github.com/git-pkgs/registries/fetch" + "github.com/prometheus/client_golang/prometheus/testutil" +) + +// limitedUpstream answers every request with 429 and a Retry-After of ten +// minutes. Requests wait for release, which is open unless a test closes it +// later. +type limitedUpstream struct { + server *httptest.Server + calls atomic.Int32 + entered chan struct{} + release chan struct{} + released sync.Once +} + +func newLimitedUpstream(t *testing.T, blocked bool) *limitedUpstream { + u := &limitedUpstream{entered: make(chan struct{}, 8), release: make(chan struct{})} + if !blocked { + u.open() + } + t.Cleanup(u.open) + u.server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + u.calls.Add(1) + u.entered <- struct{}{} + <-u.release + w.Header().Set("Retry-After", "600") + w.WriteHeader(http.StatusTooManyRequests) + })) + t.Cleanup(u.server.Close) + return u +} + +func (u *limitedUpstream) open() { u.released.Do(func() { close(u.release) }) } + +func (u *limitedUpstream) artifactURL() string { return u.server.URL + "/left-pad-1.3.0.tgz" } + +// useSharedGate routes p's upstream requests through its own rate limit gate, +// sharing holds through db as a replica does. +func useSharedGate(p *Proxy, db *database.DB, u *limitedUpstream) *upstreamhttp.SharedRateLimitGate { + gate := upstreamhttp.NewSharedRateLimitGate(registryclient.NewRateLimitGate(u.server.Client().Transport), db, nil) + client := &http.Client{Transport: gate} + p.HTTPClient = client + p.Fetcher = fetch.NewFetcher(fetch.WithHTTPClient(client), fetch.WithBaseDelay(time.Millisecond)) + p.RateLimits = gate + return gate +} + +func fetchLimited(ctx context.Context, p *Proxy, u *limitedUpstream) error { + res, err := p.GetOrFetchArtifactFromURL(ctx, "npm", "left-pad", "1.3.0", "left-pad-1.3.0.tgz", u.artifactURL()) + if err == nil { + _ = res.Reader.Close() + } + return err +} + +// requireHeld checks that err is answered like any held upstream request, +// with 503 and a Retry-After. +func requireHeld(t *testing.T, name string, err error) { + t.Helper() + w := httptest.NewRecorder() + if !writeUpstreamHeld(w, err) { + t.Fatalf("%s: err = %v, want a held upstream", name, err) + } + if w.Code != http.StatusServiceUnavailable || w.Header().Get("Retry-After") == "" { + t.Fatalf("%s: status %d, Retry-After %q; want 503 with Retry-After", name, w.Code, w.Header().Get("Retry-After")) + } +} + +// TestSharedHoldStopsOtherInstance checks that once one instance is rate +// limited, another sharing its database refuses requests to that host +// without sending them, until the hold ends. +func TestSharedHoldStopsOtherInstance(t *testing.T) { + path := filepath.Join(t.TempDir(), "shared.db") + dbA, err := database.Create(path) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = dbA.Close() }) + dbB, err := database.Open(path) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = dbB.Close() }) + logger := slog.New(slog.NewTextHandler(io.Discard, nil)) + store := newMockStorage() + a := NewProxy(dbA, store, &mockFetcher{}, fetch.NewResolver(), logger) + b := NewProxy(dbB, store, &mockFetcher{}, fetch.NewResolver(), logger) + + u := newLimitedUpstream(t, false) + useSharedGate(a, dbA, u) + gateB := useSharedGate(b, dbB, u) + gateB.Refresh = 0 + + if err := fetchLimited(context.Background(), a, u); err == nil { + t.Fatal("instance a: want the rate limit error") + } + if got := u.calls.Load(); got != 1 { + t.Fatalf("upstream requests after a = %d, want 1", got) + } + + requireHeld(t, "instance b artifact", fetchLimited(context.Background(), b, u)) + _, _, err = b.FetchOrCacheMetadata(context.Background(), "npm", "left-pad", u.server.URL+"/left-pad", "application/json") + if !errors.Is(err, registryclient.ErrUpstreamHeld) { + t.Errorf("instance b metadata: err = %v, want a held upstream", err) + } + if got := u.calls.Load(); got != 1 { + t.Errorf("upstream requests after b = %d, want 1", got) + } + + // The hold ends when the upstream said, and is then deleted. + holds, err := dbB.UpstreamHolds(time.Now().Add(11 * time.Minute)) + if err != nil || len(holds) != 0 { + t.Fatalf("holds after expiry = %v, %v; want none", holds, err) + } + if err := b.upstreamHeld(u.artifactURL()); err != nil { + t.Errorf("instance b after expiry: %v, want no hold", err) + } +} + +// TestFetchLeaseRateLimitedHolderStopsWaiters checks that instances waiting +// on a fetch that was rate limited answer with the holder's Retry-After +// instead of each sending one more request to the limited host. +func TestFetchLeaseRateLimitedHolderStopsWaiters(t *testing.T) { + a, b, db := sharedInstances(t) + u := newLimitedUpstream(t, true) + useSharedGate(a, db, u) + gateB := useSharedGate(b, db, u) + // b has read the shared holds just before, and would not read them + // again for an hour on its own. + gateB.Refresh = time.Hour + if err := b.upstreamHeld(u.artifactURL()); err != nil { + t.Fatal(err) + } + + waits := testutil.ToFloat64(metrics.FetchLeaseWaits.WithLabelValues(metrics.CacheKindArtifact)) + resA := make(chan error, 1) + go func() { resA <- fetchLimited(context.Background(), a, u) }() + <-u.entered + resB := make(chan error, 1) + go func() { resB <- fetchLimited(context.Background(), b, u) }() + waitForLeaseWaits(t, metrics.CacheKindArtifact, waits) + u.open() + + if err := <-resA; err == nil { + t.Fatal("instance a: want the rate limit error") + } + requireHeld(t, "instance b", <-resB) + if got := u.calls.Load(); got != 1 { + t.Errorf("upstream requests = %d, want 1", got) + } +} diff --git a/internal/handler/stale_metadata_test.go b/internal/handler/stale_metadata_test.go new file mode 100644 index 0000000..9cd8e75 --- /dev/null +++ b/internal/handler/stale_metadata_test.go @@ -0,0 +1,94 @@ +package handler + +import ( + "net/http" + "net/http/httptest" + "sync/atomic" + "testing" + "time" +) + +// upstreamThen serves body once and answers every later request with status. +func upstreamThen(t *testing.T, body string, status int) *httptest.Server { + t.Helper() + var requests atomic.Int32 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + if requests.Add(1) == 1 { + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(body)) + return + } + w.WriteHeader(status) + })) + t.Cleanup(srv.Close) + return srv +} + +// staleProxy returns a proxy whose cached metadata expires right away. +func staleProxy(t *testing.T, upstream *httptest.Server) *Proxy { + t.Helper() + proxy, _, _, _ := setupTestProxy(t) + proxy.CacheMetadata = true + proxy.MetadataTTL = time.Millisecond + proxy.HTTPClient = upstream.Client() + return proxy +} + +// requestTwice requests path, lets the cached copy expire, and requests it +// again. +func requestTwice(t *testing.T, h http.Handler, path string) *httptest.ResponseRecorder { + t.Helper() + first := httptest.NewRecorder() + h.ServeHTTP(first, httptest.NewRequest(http.MethodGet, path, nil)) + if first.Code != http.StatusOK { + t.Fatalf("first request: status = %d, body %s", first.Code, first.Body) + } + time.Sleep(5 * time.Millisecond) + w := httptest.NewRecorder() + h.ServeHTTP(w, httptest.NewRequest(http.MethodGet, path, nil)) + return w +} + +// staleStatuses are upstream answers the metadata cache falls back on. +var staleStatuses = []int{http.StatusBadGateway, http.StatusNotFound, http.StatusUnauthorized, http.StatusForbidden} + +const staleComposerDocument = `{"packages":{"acme/widget":[{"name":"acme/widget","version":"1.0.0",` + + `"dist":{"type":"zip","url":"https://repo.packagist.org/files/acme/widget/1.0.0/widget.zip"}}]},"minified":"composer/2.0"}` + +func TestComposerStaleMetadataIsMarked(t *testing.T) { + for _, status := range staleStatuses { + t.Run(http.StatusText(status), func(t *testing.T) { + upstream := upstreamThen(t, staleComposerDocument, status) + h := NewComposerHandlerWithUpstreams(staleProxy(t, upstream), "http://proxy.test", upstream.URL, upstream.URL).Routes() + + w := requestTwice(t, h, "/p2/acme/widget.json") + if w.Code != http.StatusOK { + t.Fatalf("status = %d, want 200 from the cache, body %s", w.Code, w.Body) + } + if got := w.Header().Get("Warning"); got != staleWarning { + t.Errorf("Warning = %q, want %q", got, staleWarning) + } + }) + } +} + +const staleChefUniverse = `{"apt":{"7.5.0":{"location_type":"supermarket",` + + `"location_path":"https://supermarket.chef.io/api/v1","download_url":` + + `"https://supermarket.chef.io/api/v1/cookbooks/apt/versions/7.5.0/download","dependencies":{}}}}` + +func TestChefStaleMetadataIsMarked(t *testing.T) { + for _, status := range staleStatuses { + t.Run(http.StatusText(status), func(t *testing.T) { + upstream := upstreamThen(t, staleChefUniverse, status) + h := NewChefHandler(staleProxy(t, upstream), chefTestProxyURL, upstream.URL).Routes() + + w := requestTwice(t, h, "/universe") + if w.Code != http.StatusOK { + t.Fatalf("status = %d, want 200 from the cache, body %s", w.Code, w.Body) + } + if got := w.Header().Get("Warning"); got != staleWarning { + t.Errorf("Warning = %q, want %q", got, staleWarning) + } + }) + } +} diff --git a/internal/handler/stream_artifacts_test.go b/internal/handler/stream_artifacts_test.go index 1c15a31..af0e3f1 100644 --- a/internal/handler/stream_artifacts_test.go +++ b/internal/handler/stream_artifacts_test.go @@ -303,7 +303,7 @@ func TestStreamArtifactsOCIBlobShorterThanContentLengthIsIncomplete(t *testing.T proxy, _, store, _ := setupTestProxy(t) proxy.StreamArtifacts = true useRealFetcher(t, proxy, upstream) - h := NewContainerHandler(proxy, "http://proxy.example", map[string]string{"ghcr": upstream.URL}) + h := NewContainerHandlerWithRegistry(proxy, "http://proxy.example", "", map[string]string{"ghcr": upstream.URL}) srv := httptest.NewServer(h.Routes()) defer srv.Close() @@ -317,7 +317,7 @@ func TestStreamArtifactsNPMTarballWithoutFinalChunkIsIncomplete(t *testing.T) { upstream := truncatingUpstream(t, func(r *http.Request) bool { return strings.HasSuffix(r.URL.Path, ".tgz") }, "HTTP/1.1 200 OK\r\nContent-Type: application/octet-stream\r\nTransfer-Encoding: chunked\r\n\r\n5\r\nshort\r\n", - http.NotFound) + func(w http.ResponseWriter, _ *http.Request) { _, _ = io.WriteString(w, `{"versions":{}}`) }) proxy, _, store, _ := setupTestProxy(t) proxy.StreamArtifacts = true diff --git a/internal/handler/stream_miss.go b/internal/handler/stream_miss.go new file mode 100644 index 0000000..fb8ae62 --- /dev/null +++ b/internal/handler/stream_miss.go @@ -0,0 +1,458 @@ +package handler + +import ( + "context" + "errors" + "fmt" + "io" + "strings" + "sync" + + "github.com/git-pkgs/artifacts" + "github.com/git-pkgs/proxy/internal/metrics" + "github.com/git-pkgs/registries/fetch" + "github.com/opencontainers/go-digest" +) + +// On a cache miss a marked request is sent the bytes as they arrive from +// upstream while they are stored, rather than after the whole artifact is +// stored. Clients with idle timeouts need this for large artifacts: git-lfs +// gives up after 30 seconds without data, pacman after 10. The caller that +// starts the shared fetch is handed the stream; callers joining it still wait +// for the stored artifact. + +type streamCacheMissKey struct{} + +// StreamCacheMiss marks ctx so that on an artifact cache miss the bytes are +// sent to the client while they are being stored. The server sets it on GET +// requests without a Range header; a range of a stream that is still +// arriving can't be served. +func StreamCacheMiss(ctx context.Context) context.Context { + return context.WithValue(ctx, streamCacheMissKey{}, true) +} + +func streamsCacheMiss(ctx context.Context) bool { + stream, _ := ctx.Value(streamCacheMissKey{}).(bool) + return stream && !servingHead(ctx) +} + +// missHandoff passes the client's stream from the shared fetch, which runs on +// its own goroutine, to the caller that started it. The caller can leave +// before a stream is offered, and the fetch must then not write to a stream +// nobody reads. +type missHandoff struct { + mu sync.Mutex + ready chan struct{} + stream *CacheResult + taken bool + abandoned bool + // feed is the stream's source. Set and read only on the fetch's + // goroutine. + feed *missFeed +} + +type missHandoffKey struct{} + +func handoffFrom(ctx context.Context) *missHandoff { + h, _ := ctx.Value(missHandoffKey{}).(*missHandoff) + return h +} + +// offer hands stream to the caller and reports whether it took it. +func (h *missHandoff) offer(stream *CacheResult) bool { + h.mu.Lock() + defer h.mu.Unlock() + if h.abandoned { + return false + } + h.stream, h.taken = stream, true + close(h.ready) + return true +} + +// holdUnrecorded gives a client that fell behind, and reads the stored copy +// of u, its own hold on u until it closes, so u isn't deleted under it. +func (h *missHandoff) holdUnrecorded(u *unrecordedObject) { + if h.feed != nil { + h.feed.holdUntilClose(u) + } +} + +// handedOver reports whether the caller took a stream. +func (h *missHandoff) handedOver() bool { + h.mu.Lock() + defer h.mu.Unlock() + return h.taken +} + +// runSharedFetchStreaming runs the shared fetch on its own goroutine and +// returns as soon as it offers a stream, or with its result if it finishes +// without one: on a recheck hit, an artifact another instance stored, an +// error, or an artifact a block-mode scanner has to see first. Waiters and +// the fetch lease still see the fetch end only once the artifact is stored. +func (p *Proxy) runSharedFetchStreaming(ctx context.Context, key string, f *inflightFetch, recheck func() (artifacts.Artifact, string, bool), commit func(context.Context) (artifacts.Artifact, string, error)) (*CacheResult, error) { + h := &missHandoff{ready: make(chan struct{})} + type outcome struct { + res *CacheResult + err error + } + done := make(chan outcome, 1) + go func() { + res, err := p.runSharedFetch(context.WithValue(ctx, missHandoffKey{}, h), key, f, recheck, commit) + h.mu.Lock() + defer h.mu.Unlock() + if h.taken || h.abandoned { + // The caller has the stream, or has gone; nobody reads this. + if res != nil && res.Reader != nil { + _ = res.Reader.Close() + } + return + } + done <- outcome{res, err} + }() + + select { + case <-h.ready: + return h.stream, nil + case o := <-done: + return o.res, o.err + case <-ctx.Done(): + h.mu.Lock() + defer h.mu.Unlock() + if h.taken { + return h.stream, nil + } + h.abandoned = true + select { + case o := <-done: + if o.res != nil && o.res.Reader != nil { + _ = o.res.Reader.Close() + } + default: + } + return nil, ctx.Err() + } +} + +// storeFetched stores an artifact fetched from upstream. When the caller +// that started the fetch is waiting for a stream, it is sent the bytes as +// they are stored; see storeWhileServing. +func (p *Proxy) storeFetched(ctx context.Context, ecosystem, name, version, filename, pkgPURL, versionPURL, upstreamURL, upstreamHash, declared string, artifact *fetch.Artifact) (artifacts.Artifact, string, error) { + h := handoffFrom(ctx) + if h == nil || p.Scanners.Blocks(ecosystem) { + return p.storeArtifact(ctx, ecosystem, name, version, filename, pkgPURL, versionPURL, upstreamURL, upstreamHash, declared, artifact) + } + return p.storeWhileServing(ctx, h, ecosystem, name, version, filename, pkgPURL, versionPURL, upstreamURL, upstreamHash, declared, artifact) +} + +// errNoReaderLeft stops reading upstream once neither storage nor the +// client takes the bytes any more. +var errNoReaderLeft = errors.New("neither storage nor the client is reading the artifact") + +// storeWhileServing copies the upstream body to storage and to the client at +// once, at the upstream's speed; see missFeed for a client that can't keep up. +// The client's copy is checked before its last bytes, so a mismatch aborts +// the response. A storage failure leaves the client's copy running. +func (p *Proxy) storeWhileServing(ctx context.Context, h *missHandoff, ecosystem, name, version, filename, pkgPURL, versionPURL, upstreamURL, upstreamHash, declared string, artifact *fetch.Artifact) (artifacts.Artifact, string, error) { + hash := strings.ToLower(upstreamHash) + checks, err := newIntegrityChecks(hash, declared) + if err != nil { + _ = artifact.Body.Close() + return artifacts.Artifact{}, "", err + } + + feed := newMissFeed(clientFeedLimit) + var client io.ReadCloser = feed + if hash != "" || declared != "" { + if client, err = checks.wrapFailOnMismatch(feed, func(reason string) { + p.Logger.Warn("artifact sent on a cache miss failed its integrity check; aborting the response", + "purl", versionPURL, "filename", filename, "reason", reason) + }); err != nil { + _ = artifact.Body.Close() + return artifacts.Artifact{}, "", err + } + } + stream := &CacheResult{ + Reader: client, + Artifact: artifacts.Artifact{ + PURL: versionPURL, + Filename: filename, + MediaType: artifact.ContentType, + // Unknown until stored, so the response goes out chunked and + // can still be aborted. + Size: -1, + }, + } + if hash != "" { + stream.Artifact.Digest = digest.Digest("sha256:" + hash) + } + if !h.offer(stream) { + _ = feed.Close() + return p.storeArtifact(ctx, ecosystem, name, version, filename, pkgPURL, versionPURL, upstreamURL, upstreamHash, declared, artifact) + } + h.feed = feed + + storeR, storeW := io.Pipe() + type stored struct { + artifact artifacts.Artifact + path string + err error + } + storeDone := make(chan stored, 1) + go func() { + // Not cancelled with ctx: the client's request ends once it has the + // last byte, while storage may still be finishing the upload and the + // database write. Reading the upstream still stops with ctx, which + // ends the copy to storage too. + a, path, err := p.storeArtifact(context.WithoutCancel(ctx), ecosystem, name, version, filename, pkgPURL, versionPURL, upstreamURL, upstreamHash, declared, + &fetch.Artifact{Body: storeR, Size: artifact.Size, ContentType: artifact.ContentType, ETag: artifact.ETag}) + // storeArtifact closes storeR; this covers a return before it read + // anything, so the copy below never blocks on it. + _ = storeR.Close() + storeDone <- stored{a, path, err} + }() + + readErr := copyToBoth(artifact.Body, storeW, feed) + _ = artifact.Body.Close() + _ = storeW.CloseWithError(readErr) + feed.end(readErr) + + out := <-storeDone + if feed.lagging() { + // Opened before returning, so an unrecorded object is still there; + // runSharedFetch then gives the client a hold on it. + feed.resolve(p.openStoredForFeed(ctx, out.artifact, out.path, out.err)) + } + if out.err != nil && readErr == nil && feed.fedFully() { + p.Logger.Error("artifact sent to the client but not cached", + "purl", versionPURL, "filename", filename, "url", upstreamURL, "error", out.err) + metrics.RecordArtifactServedUncached(ecosystem, metrics.FailureDetail{ + PURL: versionPURL, Filename: filename, URL: upstreamURL, Err: out.err}) + } + return out.artifact, out.path, out.err +} + +// openStoredForFeed opens the stored copy for a client that fell behind. An +// unrecorded object is opened too: it is deleted only after this returns, and +// the client holds it from then on (missHandoff.holdUnrecorded). +func (p *Proxy) openStoredForFeed(ctx context.Context, a artifacts.Artifact, path string, storeErr error) (io.ReadCloser, error) { + if storeErr != nil && !errors.Is(storeErr, errUnrecorded) { + return nil, storeErr + } + res, err := p.openStoredArtifact(ctx, a, path) + if err != nil { + return nil, err + } + return res.Reader, nil +} + +// copyToBoth copies src to store and to the client's feed until src ends, +// dropping the store once a write to it fails. It returns the error that +// ended the copy, nil at the end of src. Feeding the client never blocks. +func copyToBoth(src io.Reader, store io.Writer, client *missFeed) error { + buffer := artifactCopyBufferPool.Get().(*[]byte) + defer artifactCopyBufferPool.Put(buffer) + buf := *buffer + storeOK := true + for { + n, err := src.Read(buf) + if n > 0 { + if storeOK { + if _, werr := store.Write(buf[:n]); werr != nil { + storeOK = false + } + } + // A client that has gone, or that waits for the stored copy, + // has no use for the rest once storing has failed. + if !client.push(buf[:n]) && !storeOK { + return errNoReaderLeft + } + } + if errors.Is(err, io.EOF) { + return nil + } + if err != nil { + return err + } + } +} + +// clientFeedLimit bounds the bytes held for a client that reads a streamed +// miss slower than they arrive. A variable so tests can lower it. +var clientFeedLimit = 8 << 20 + +// missFeed is the client's side of a streamed miss. The upstream read pushes +// into it without blocking, so a slow client can't hold back the copy to +// storage, the fetch lease or the callers waiting on the fetch. Once the +// client is more than the limit behind, it stops being fed: it reads what +// is held, then continues from the stored copy where it left off. +type missFeed struct { + mu sync.Mutex + cond *sync.Cond + chunks [][]byte + held int + limit int + // fed counts the bytes pushed before the client fell behind, where it + // continues in the stored copy. + fed int64 + ended bool + endErr error + behind bool + closed bool + early bool // closed before reading everything it was fed + + stored io.ReadCloser + storedErr error + resolved bool + skipped bool + // release drops the client's hold on an unrecorded stored copy. + release func() +} + +func newMissFeed(limit int) *missFeed { + m := &missFeed{limit: limit} + m.cond = sync.NewCond(&m.mu) + return m +} + +// push queues a copy of b and reports whether the client is still fed. +func (m *missFeed) push(b []byte) bool { + m.mu.Lock() + defer m.mu.Unlock() + if m.closed || m.behind { + return false + } + if m.held+len(b) > m.limit { + m.behind = true + return false + } + m.chunks = append(m.chunks, append([]byte(nil), b...)) + m.held += len(b) + m.fed += int64(len(b)) + m.cond.Broadcast() + return true +} + +// end records how the upstream read ended. +func (m *missFeed) end(err error) { + m.mu.Lock() + defer m.mu.Unlock() + m.ended, m.endErr = true, err + m.cond.Broadcast() +} + +func (m *missFeed) lagging() bool { + m.mu.Lock() + defer m.mu.Unlock() + return m.behind && !m.closed +} + +// fedFully reports whether the client was sent every byte from upstream. +func (m *missFeed) fedFully() bool { + m.mu.Lock() + defer m.mu.Unlock() + return !m.behind && !m.early +} + +// resolve gives a client that fell behind the stored copy, or the error +// that left none. +func (m *missFeed) resolve(r io.ReadCloser, err error) { + m.mu.Lock() + defer m.mu.Unlock() + if m.closed { + if r != nil { + _ = r.Close() + } + return + } + m.stored, m.storedErr, m.resolved = r, err, true + m.cond.Broadcast() +} + +// holdUntilClose takes a hold on u for a client reading its stored copy and +// releases it when the client closes. +func (m *missFeed) holdUntilClose(u *unrecordedObject) { + m.mu.Lock() + defer m.mu.Unlock() + if m.closed || m.stored == nil { + return + } + u.refs.Add(1) + m.release = u.release +} + +func (m *missFeed) Read(p []byte) (int, error) { + m.mu.Lock() + for { + switch { + case m.closed: + m.mu.Unlock() + return 0, io.ErrClosedPipe + case len(m.chunks) > 0: + n := copy(p, m.chunks[0]) + if m.chunks[0] = m.chunks[0][n:]; len(m.chunks[0]) == 0 { + m.chunks[0] = nil + m.chunks = m.chunks[1:] + } + m.held -= n + m.mu.Unlock() + return n, nil + case m.behind && m.resolved: + r, err, skipped := m.stored, m.storedErr, m.skipped + m.skipped = true + m.mu.Unlock() + if err != nil { + return 0, err + } + if !skipped { + if err := skipTo(r, m.fed); err != nil { + return 0, err + } + } + return r.Read(p) + case !m.behind && m.ended: + err := m.endErr + m.mu.Unlock() + if err == nil { + err = io.EOF + } + return 0, err + } + m.cond.Wait() + } +} + +func (m *missFeed) Close() error { + m.mu.Lock() + if m.closed { + m.mu.Unlock() + return nil + } + m.closed = true + m.early = !m.ended || len(m.chunks) > 0 + m.chunks, m.held = nil, 0 + if m.stored != nil { + _ = m.stored.Close() + } + release := m.release + m.release = nil + m.cond.Broadcast() + m.mu.Unlock() + if release != nil { + // Outside the lock: the last release deletes the object. + release() + } + return nil +} + +// skipTo moves r past the first n bytes. +func skipTo(r io.Reader, n int64) error { + if s, ok := r.(io.Seeker); ok { + _, err := s.Seek(n, io.SeekStart) + return err + } + if _, err := io.CopyN(io.Discard, r, n); err != nil { + return fmt.Errorf("skipping to byte %d of the stored artifact: %w", n, err) + } + return nil +} diff --git a/internal/handler/stream_miss_test.go b/internal/handler/stream_miss_test.go new file mode 100644 index 0000000..2746588 --- /dev/null +++ b/internal/handler/stream_miss_test.go @@ -0,0 +1,583 @@ +package handler + +import ( + "bytes" + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "io" + "log/slog" + "net/http" + "net/http/httptest" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/git-pkgs/proxy/internal/config" + "github.com/git-pkgs/proxy/internal/metrics" + "github.com/git-pkgs/proxy/internal/scanner" + "github.com/git-pkgs/registries/fetch" + "github.com/prometheus/client_golang/prometheus/testutil" +) + +// lockedBuffer is a log destination safe for the goroutine that stores a +// streamed artifact to write to while a test reads it. +type lockedBuffer struct { + mu sync.Mutex + buf bytes.Buffer +} + +func (b *lockedBuffer) Write(p []byte) (int, error) { + b.mu.Lock() + defer b.mu.Unlock() + return b.buf.Write(p) +} + +func (b *lockedBuffer) String() string { + b.mu.Lock() + defer b.mu.Unlock() + return b.buf.String() +} + +// streamMissSetup is a Git LFS upstream whose object store sends the first +// half of an object, then waits for release before sending the rest, and a +// proxy serving it to clients the way the server marks their requests. +type streamMissSetup struct { + proxy *Proxy + store *mockStorage + client *httptest.Server + git *httptest.Server + objects *httptest.Server + release chan struct{} + content string // what the object store sends + oid string // the object ID clients ask for + path string + downloads atomic.Int32 + logs lockedBuffer +} + +// streamMissContent spans many copy buffers: a stream checked against its +// digest holds back its latest chunk until the next one arrives. +var streamMissContent = strings.Repeat("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\n", 400<<10/63) + +// streamMissPrefix is how much a client must get while the upstream still +// holds back the second half. +const streamMissPrefix = 64 << 10 + +func newStreamMiss(t *testing.T, served string) *streamMissSetup { + t.Helper() + return newStreamMissMarked(t, served, true) +} + +// newStreamMissMarked is newStreamMiss, with requests marked to detach +// their upstream fetch as the server does, or not, as when the server has +// no detached fetch to spare. +func newStreamMissMarked(t *testing.T, served string, detached bool) *streamMissSetup { + t.Helper() + sum := sha256.Sum256([]byte(streamMissContent)) + s := &streamMissSetup{content: served, oid: hex.EncodeToString(sum[:]), release: make(chan struct{})} + s.objects = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + s.downloads.Add(1) + half := len(s.content) / 2 + _, _ = io.WriteString(w, s.content[:half]) + w.(http.Flusher).Flush() + select { + case <-s.release: + case <-r.Context().Done(): + return + } + _, _ = io.WriteString(w, s.content[half:]) + })) + s.git = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var req lfsBatchRequest + _ = json.NewDecoder(r.Body).Decode(&req) + resp := lfsBatchResponse{Transfer: "basic"} + for _, o := range req.Objects { + resp.Objects = append(resp.Objects, lfsObjectResponse{OID: o.OID, Size: o.Size, + Actions: map[string]lfsAction{"download": {Href: s.objects.URL + "/objects/" + o.OID}}}) + } + w.Header().Set("Content-Type", gitLFSMediaType) + _ = json.NewEncoder(w).Encode(resp) + })) + + proxy, _, store, _ := setupTestProxy(t) + store.seekable = true + proxy.Logger = slog.New(slog.NewTextHandler(&s.logs, nil)) + proxy.HTTPClient = s.git.Client() + fetcher := fetch.NewFetcher(fetch.WithHTTPClient(s.objects.Client()), fetch.WithMaxRetries(0)) + proxy.Fetcher = fetcher + s.proxy, s.store = proxy, store + h := NewGitHandler(proxy, nil, config.UpstreamConfig{Git: map[string]config.GitUpstream{ + "up": {URL: s.git.URL}, + }}).WithBaseURL("http://proxy.test/") + routes := h.Routes() + // As the server marks client requests. + s.client = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + ctx := StreamCacheMiss(r.Context()) + if detached { + ctx = DetachUpstreamFetch(ctx) + } + routes.ServeHTTP(w, r.WithContext(ctx)) + })) + s.path = fmt.Sprintf("/up/acme/widget.git/info/lfs/objects/%s/%d", s.oid, len(streamMissContent)) + t.Cleanup(func() { + s.releaseUpstream() + s.client.Close() + s.git.Close() + s.objects.Close() + _ = fetcher.Close() + }) + return s +} + +func (s *streamMissSetup) releaseUpstream() { + select { + case <-s.release: + default: + close(s.release) + } +} + +// get requests the object. The response headers must arrive in time even +// while the upstream holds back the second half. +func (s *streamMissSetup) get(t *testing.T) *http.Response { + t.Helper() + type result struct { + resp *http.Response + err error + } + got := make(chan result, 1) + go func() { + resp, err := s.client.Client().Get(s.client.URL + s.path) + got <- result{resp, err} + }() + select { + case r := <-got: + if r.err != nil { + t.Fatal(r.err) + } + return r.resp + case <-time.After(5 * time.Second): + // Once the upstream is released the response arrives; close it. + t.Cleanup(func() { + s.releaseUpstream() + if r := <-got; r.resp != nil { + _ = r.resp.Body.Close() + } + }) + t.Fatal("no response while the upstream was still sending") + return nil + } +} + +// cached waits for the stored copy, which is written after the client's +// stream ends. +func (s *streamMissSetup) cached(t *testing.T) bool { + t.Helper() + deadline := time.Now().Add(5 * time.Second) + for { + res, err := s.proxy.GetCachedArtifact(t.Context(), gitEcosystem, "up/acme/widget", s.oid, s.oid) + if err == nil && res != nil { + _ = res.Reader.Close() + return true + } + if time.Now().After(deadline) { + return false + } + time.Sleep(10 * time.Millisecond) + } +} + +// readFirst reads the first streamMissPrefix bytes of body, failing if they +// don't arrive in time. +func readFirst(t *testing.T, body io.Reader) string { + t.Helper() + got := make(chan string, 1) + go func() { + buf := make([]byte, streamMissPrefix) + _, _ = io.ReadFull(body, buf) + got <- string(buf) + }() + select { + case s := <-got: + return s + case <-time.After(5 * time.Second): + t.Fatal("no bytes reached the client while the upstream was still sending") + return "" + } +} + +func TestCacheMissStreamsBeforeUpstreamFinishes(t *testing.T) { + s := newStreamMiss(t, streamMissContent) + resp := s.get(t) + defer func() { _ = resp.Body.Close() }() + if resp.StatusCode != http.StatusOK || resp.ContentLength != -1 { + t.Fatalf("status %d, Content-Length %d; want 200, chunked", resp.StatusCode, resp.ContentLength) + } + if first := readFirst(t, resp.Body); first != streamMissContent[:streamMissPrefix] { + t.Fatal("first bytes differ from the artifact's") + } + + s.releaseUpstream() + rest, err := io.ReadAll(resp.Body) + if err != nil || string(rest) != streamMissContent[streamMissPrefix:] { + t.Fatalf("rest: %d bytes, %v", len(rest), err) + } + if !s.cached(t) { + t.Fatal("streamed artifact was not cached") + } + + // Served from the cache now, with its size. + s.objects.Close() + again := s.get(t) + body, _ := io.ReadAll(again.Body) + _ = again.Body.Close() + if again.StatusCode != http.StatusOK || string(body) != streamMissContent || again.ContentLength != int64(len(streamMissContent)) { + t.Errorf("cached GET: status %d, length %d, %d bytes", again.StatusCode, again.ContentLength, len(body)) + } + if s.downloads.Load() != 1 { + t.Errorf("downloads = %d, want 1", s.downloads.Load()) + } +} + +func TestCacheMissStreamAbortedOnMismatch(t *testing.T) { + tampered := "X" + streamMissContent[1:] + s := newStreamMiss(t, tampered) + s.releaseUpstream() + resp := s.get(t) + body, err := io.ReadAll(resp.Body) + _ = resp.Body.Close() + if err == nil { + t.Fatalf("read %d bytes without error; want the response aborted", len(body)) + } + if string(body) == tampered { + t.Error("client got every byte of an artifact that doesn't match its object ID") + } + // Nothing to wait for: storeArtifact has refused it once the stream ends. + time.Sleep(100 * time.Millisecond) + if res, _ := s.proxy.GetCachedArtifact(t.Context(), gitEcosystem, "up/acme/widget", s.oid, s.oid); res != nil { + _ = res.Reader.Close() + t.Error("mismatching artifact was cached") + } +} + +func TestCacheMissStreamFinishesWhenStorageFails(t *testing.T) { + s := newStreamMiss(t, streamMissContent) + s.store.mu.Lock() + s.store.storeErr = errors.New("no space left on device") + s.store.mu.Unlock() + before := testutil.ToFloat64(metrics.ArtifactsServedUncached.WithLabelValues(gitEcosystem)) + s.releaseUpstream() + + resp := s.get(t) + body, err := io.ReadAll(resp.Body) + _ = resp.Body.Close() + if err != nil || resp.StatusCode != http.StatusOK || string(body) != streamMissContent { + t.Fatalf("status %d, %d bytes, %v; want the whole artifact", resp.StatusCode, len(body), err) + } + deadline := time.Now().Add(5 * time.Second) + for testutil.ToFloat64(metrics.ArtifactsServedUncached.WithLabelValues(gitEcosystem)) == before && time.Now().Before(deadline) { + time.Sleep(10 * time.Millisecond) + } + if got := testutil.ToFloat64(metrics.ArtifactsServedUncached.WithLabelValues(gitEcosystem)) - before; got != 1 { + t.Errorf("served-uncached count went up by %v, want 1", got) + } + if !strings.Contains(s.logs.String(), "level=ERROR") || !strings.Contains(s.logs.String(), "not cached") { + t.Errorf("storage failure not logged at error level:\n%s", s.logs.String()) + } +} + +func TestCacheMissStoredAfterClientLeaves(t *testing.T) { + s := newStreamMiss(t, streamMissContent) + resp := s.get(t) + readFirst(t, resp.Body) + _ = resp.Body.Close() + s.client.CloseClientConnections() + + s.releaseUpstream() + if !s.cached(t) { + t.Fatal("artifact not cached after the client that started the fetch left") + } +} + +func TestCacheMissWaiterGetsStoredArtifact(t *testing.T) { + s := newStreamMiss(t, streamMissContent) + first := s.get(t) + defer func() { _ = first.Body.Close() }() + readFirst(t, first.Body) + + second := make(chan string, 1) + go func() { + resp, err := s.client.Client().Get(s.client.URL + s.path) + if err != nil { + second <- err.Error() + return + } + body, _ := io.ReadAll(resp.Body) + _ = resp.Body.Close() + second <- fmt.Sprintf("%d %d %s", resp.StatusCode, resp.ContentLength, body) + }() + select { + case got := <-second: + t.Fatalf("second request answered before the artifact was stored: %s", got) + case <-time.After(200 * time.Millisecond): + } + + s.releaseUpstream() + if _, err := io.ReadAll(first.Body); err != nil { + t.Fatal(err) + } + want := fmt.Sprintf("200 %d %s", len(streamMissContent), streamMissContent) + if got := <-second; got != want { + t.Errorf("second request = %.60q..., want the stored artifact with its length", got) + } + if s.downloads.Load() != 1 { + t.Errorf("downloads = %d, want 1", s.downloads.Load()) + } +} + +func newStreamMissScanGroup(t *testing.T, mode string) *scanner.Group { + t.Helper() + g, err := scanner.NewGroup(config.ScanningConfig{ + Enabled: true, + Timeout: "15s", + SigningKey: "test-signing-key", + Scanners: []config.ScannerConfig{ + {Name: "test-scanner", URL: newTestScanServer(t, true, "").URL, Mode: mode}, + }, + }, slog.New(slog.NewTextHandler(io.Discard, nil))) + if err != nil { + t.Fatal(err) + } + return g +} + +// A block-mode scanner must see the whole artifact before any of it is +// served, so a miss isn't streamed. +func TestCacheMissNotStreamedWithBlockingScanner(t *testing.T) { + s := newStreamMiss(t, streamMissContent) + s.proxy.ScanSigningKey = []byte("test-signing-key") + s.proxy.Scanners = newStreamMissScanGroup(t, "block") + + got := make(chan *http.Response, 1) + go func() { + resp, err := s.client.Client().Get(s.client.URL + s.path) + if err != nil { + t.Error(err) + } + got <- resp + }() + select { + case resp := <-got: + _ = resp.Body.Close() + t.Fatal("response started before the upstream finished, with a block-mode scanner") + case <-time.After(300 * time.Millisecond): + } + s.releaseUpstream() + resp := <-got + body, _ := io.ReadAll(resp.Body) + _ = resp.Body.Close() + if resp.StatusCode != http.StatusOK || string(body) != streamMissContent || resp.ContentLength != int64(len(streamMissContent)) { + t.Errorf("status %d, length %d, %d bytes; want the scanned, stored artifact", resp.StatusCode, resp.ContentLength, len(body)) + } +} + +// A monitor-mode scanner doesn't gate the artifact, so the miss is streamed +// and the scan runs after the client's stream ends. +func TestCacheMissStreamedWithMonitoringScanner(t *testing.T) { + s := newStreamMiss(t, streamMissContent) + s.proxy.ScanSigningKey = []byte("test-signing-key") + s.proxy.Scanners = newStreamMissScanGroup(t, "monitor") + + resp := s.get(t) + defer func() { _ = resp.Body.Close() }() + readFirst(t, resp.Body) + s.releaseUpstream() + if _, err := io.ReadAll(resp.Body); err != nil { + t.Fatal(err) + } + if !s.cached(t) { + t.Error("artifact not cached") + } +} + +// slowStorage stores like mockStorage, but takes a while to finish once it +// has read the last byte, as an upload to S3 does. +type slowStorage struct { + *mockStorage + delay time.Duration +} + +func (s *slowStorage) Store(ctx context.Context, path string, r io.Reader) (int64, string, error) { + data, err := io.ReadAll(r) + if err != nil { + return 0, "", err + } + select { + case <-time.After(s.delay): + case <-ctx.Done(): + return 0, "", ctx.Err() + } + return s.mockStorage.Store(ctx, path, bytes.NewReader(data)) +} + +// Without a detached fetch, storing still finishes after the client's +// request has ended with the last byte. +func TestCacheMissStoredAfterResponseWithoutDetach(t *testing.T) { + s := newStreamMissMarked(t, streamMissContent, false) + s.proxy.Storage = &slowStorage{mockStorage: s.store, delay: 300 * time.Millisecond} + s.releaseUpstream() + resp := s.get(t) + body, err := io.ReadAll(resp.Body) + _ = resp.Body.Close() + if err != nil || string(body) != streamMissContent { + t.Fatalf("%d bytes, %v", len(body), err) + } + if !s.cached(t) { + t.Fatal("artifact not cached once the response ended") + } +} + +// lowerFeedLimit makes a client fall behind after n bytes. +func lowerFeedLimit(t *testing.T, n int) { + t.Helper() + old := clientFeedLimit + clientFeedLimit = n + t.Cleanup(func() { clientFeedLimit = old }) +} + +// TestCacheMissSlowClientDoesNotHoldBackFetch has the caller that starts a +// streamed miss read nothing until a second caller, waiting on the same +// fetch, has the stored artifact. The slow client then gets every byte, the +// ones past the limit from the stored copy. +func TestCacheMissSlowClientDoesNotHoldBackFetch(t *testing.T) { + for _, seekable := range []bool{false, true} { + t.Run(fmt.Sprintf("seekable=%v", seekable), func(t *testing.T) { testSlowClient(t, seekable) }) + } +} + +func testSlowClient(t *testing.T, seekable bool) { + t.Helper() + lowerFeedLimit(t, 64<<10) + proxy, _, store, _ := setupTestProxy(t) + store.seekable = seekable + fetcher := newGatedFetcher(streamMissContent) + proxy.Fetcher = fetcher + get := func(ctx context.Context) (*CacheResult, error) { + return proxy.GetOrFetchArtifactFromURL(ctx, "npm", "big", "1.0.0", "big-1.0.0.tgz", "https://example.com/big.tgz") + } + + slow := make(chan *CacheResult, 1) + go func() { + res, err := get(StreamCacheMiss(context.Background())) + if err != nil { + t.Errorf("slow client: %v", err) + } + slow <- res + }() + <-fetcher.entered + waiter := make(chan *CacheResult, 1) + go func() { + res, err := get(context.Background()) + if err != nil { + t.Errorf("waiter: %v", err) + } + waiter <- res + }() + waitForWaiters(t, proxy, 1) + close(fetcher.release) + + lead := <-slow + if lead == nil { + t.FailNow() + } + defer func() { _ = lead.Reader.Close() }() + if lead.Artifact.Size != -1 { + t.Fatalf("slow client got size %d, want a stream", lead.Artifact.Size) + } + select { + case res := <-waiter: + if res == nil { + t.FailNow() + } + body, err := io.ReadAll(res.Reader) + _ = res.Reader.Close() + if err != nil || string(body) != streamMissContent { + t.Fatalf("waiter: %d bytes, %v", len(body), err) + } + case <-time.After(5 * time.Second): + t.Fatal("waiter held back by a client that reads nothing") + } + + body, err := io.ReadAll(lead.Reader) + if err != nil || string(body) != streamMissContent { + t.Fatalf("slow client: %d bytes, %v; want the whole artifact", len(body), err) + } + if fetcher.calls.Load() != 1 { + t.Errorf("upstream fetches = %d, want 1", fetcher.calls.Load()) + } +} + +// TestCacheMissSlowClientFailsWithoutStoredCopy: a client that fell behind +// has nothing to continue from when storing fails, so its response fails +// rather than ending short. +func TestCacheMissSlowClientFailsWithoutStoredCopy(t *testing.T) { + lowerFeedLimit(t, 64<<10) + proxy, _, store, _ := setupTestProxy(t) + store.storeErr = errors.New("no space left on device") + proxy.Fetcher = &countingFetcher{content: streamMissContent} + + res, err := proxy.GetOrFetchArtifactFromURL(StreamCacheMiss(context.Background()), "npm", "big", "1.0.0", "big-1.0.0.tgz", "https://example.com/big.tgz") + if err != nil { + t.Fatal(err) + } + defer func() { _ = res.Reader.Close() }() + + // Leave the stream unread until the fetch ends so the feed must overflow. + proxy.fetchMu.Lock() + var done <-chan struct{} + for _, f := range proxy.inFlight { + done = f.done + } + proxy.fetchMu.Unlock() + if done != nil { + select { + case <-done: + case <-time.After(5 * time.Second): + t.Fatal("fetch did not finish while the client was idle") + } + } + + body, err := io.ReadAll(res.Reader) + if !errors.Is(err, store.storeErr) { + t.Fatalf("read %d bytes with error %v; want %v", len(body), err, store.storeErr) + } +} + +func TestMissFeedCloseWhileWaiting(t *testing.T) { + m := newMissFeed(4) + done := make(chan error, 1) + go func() { + _, err := m.Read(make([]byte, 8)) + done <- err + }() + time.Sleep(10 * time.Millisecond) + _ = m.Close() + select { + case err := <-done: + if !errors.Is(err, io.ErrClosedPipe) { + t.Errorf("Read after Close = %v", err) + } + case <-time.After(time.Second): + t.Fatal("Read still blocked after Close") + } + if m.push([]byte("ab")) { + t.Error("push to a closed feed reported the client fed") + } + m.resolve(io.NopCloser(strings.NewReader("x")), nil) +} diff --git a/internal/handler/swift.go b/internal/handler/swift.go index b506f1c..37f666e 100644 --- a/internal/handler/swift.go +++ b/internal/handler/swift.go @@ -31,10 +31,54 @@ const ( // Source archives are stored under the registry identity, // pkg:generic/swift-registry/{scope}.{name}, lowercased. Package rules write // the scope as the namespace, pkg:swift/apple/swift-nio, or use the stored -// form. A source repository URL such as pkg:swift/github.com/apple/swift-nio -// doesn't name a registry identity and is refused. +// form. A source repository such as pkg:swift/github.com/apple/swift-nio +// names no registry identity; it is resolved through the upstream's +// /identifiers before it applies. func init() { - retention.Default.Register(retention.Spec{Key: "swift", CanonicalPackage: swiftRetentionKey}) + retention.Default.Register(retention.Spec{ + Key: "swift", + CanonicalPackage: swiftRetentionKey, + SourcePackage: func(p *purl.PURL) bool { return SwiftSourcePURL(p) != "" }, + }) +} + +// SwiftSourceURL returns the repository URL of a pkg:swift name whose +// namespace starts with a host, as in github.com/apple/swift-nio, or "" for +// a name whose namespace is a registry scope. +func SwiftSourceURL(name string) string { + if host, _, ok := strings.Cut(name, "/"); ok && strings.Contains(host, ".") { + return "https://" + name + } + return "" +} + +// SwiftSourcePURL returns the repository URL of a pkg:swift PURL that names +// a package by its source repository, as SBOM tools and GHSA do, or "". +func SwiftSourcePURL(p *purl.PURL) string { + if p == nil || p.Type != "swift" || p.Namespace == "" { + return "" + } + return SwiftSourceURL(p.Namespace + "/" + p.Name) +} + +// ResolveSourcePURL returns p with a source repository namespace replaced by +// each registry scope and name the upstream lists for it, and p itself when +// it already names a registry identity. A policy for the repository applies +// to all of them, since a client may use any. +func (h *SwiftHandler) ResolveSourcePURL(ctx context.Context, p *purl.PURL) ([]*purl.PURL, error) { + source := SwiftSourcePURL(p) + if source == "" { + return []*purl.PURL{p}, nil + } + ids, err := h.ResolveIdentities(ctx, source) + if err != nil { + return nil, err + } + resolved := make([]*purl.PURL, 0, len(ids)) + for _, id := range ids { + resolved = append(resolved, purl.New("swift", id.Scope, id.Name, p.Version, nil)) + } + return resolved, nil } // swiftRetentionKey maps a package rule to the stored package PURL, refusing @@ -104,23 +148,23 @@ func (h *SwiftHandler) handlePackageReleases(w http.ResponseWriter, r *http.Requ scope, name = canonicalSwiftPackage(scope, name) upstreamURL := h.buildUpstreamURL(scope, name, "", "", r.URL.RawQuery) - body, contentType, responseHeaders, err := h.fetchMetadataWithHeaders( - r.Context(), upstreamURL, requestAccept(r, swiftAcceptJSON), + doc, err := h.fetchDocument( + r.Context(), swiftReleasesCacheKey(scope, name, r.URL.RawQuery), upstreamURL, requestAccept(r, swiftAcceptJSON), ) if err != nil { h.writeMetadataError(w, err) return } - rewritten, err := h.rewriteReleaseURLs(scope, name, body) + rewritten, err := h.rewriteReleaseURLs(scope, name, doc.body) if err != nil { h.proxy.Logger.Warn("failed to rewrite Swift release URLs", "error", err) - rewritten = body + rewritten = doc.body } - for _, link := range responseHeaders.Values("Link") { - w.Header().Add("Link", h.rewriteLinkHeader(link, upstreamURL)) + if doc.link != "" { + w.Header().Set("Link", h.rewriteLinkHeader(doc.link, upstreamURL)) } - writeSwiftMetadata(w, r, rewritten, contentType) + writeSwiftMetadata(w, r, rewritten, doc.contentType) } func (h *SwiftHandler) handleRelease(w http.ResponseWriter, r *http.Request) { @@ -161,7 +205,17 @@ func (h *SwiftHandler) handleManifest(w http.ResponseWriter, r *http.Request) { scope, name = canonicalSwiftPackage(scope, name) upstreamURL := h.buildUpstreamURL(scope, name, version, "Package.swift", r.URL.RawQuery) - h.proxySwiftResource(w, r, upstreamURL, swiftAcceptManifest) + doc, err := h.fetchDocument( + r.Context(), swiftManifestCacheKey(scope, name, version, r.URL.RawQuery), upstreamURL, requestAccept(r, swiftAcceptManifest), + ) + if err != nil { + h.writeMetadataError(w, err) + return + } + if doc.link != "" { + w.Header().Set("Link", h.rewriteLinkHeader(doc.link, upstreamURL)) + } + writeSwiftMetadata(w, r, doc.body, doc.contentType) } func (h *SwiftHandler) handleIdentifiers(w http.ResponseWriter, r *http.Request) { @@ -194,14 +248,13 @@ func (h *SwiftHandler) handleSourceArchive(w http.ResponseWriter, r *http.Reques } scope, name = canonicalSwiftPackage(scope, name) - packageName := scope + "/" + name - filename := fmt.Sprintf("%s-%s.zip", name, version) - upstreamURL := h.buildUpstreamURL(scope, name, version+".zip", "", r.URL.RawQuery) - packagePURL, versionPURL := packageurl.MakeCacheStrings("swift", packageName, version) - if packagePURL == "" || versionPURL == "" { - h.writeArtifactError(w, fmt.Errorf("%w: swift %q", errUnsupportedPackageIdentity, packageName)) + key, err := swiftSourceArchiveKey(scope, name, version) + if err != nil { + h.writeArtifactError(w, err) return } + filename, packagePURL, versionPURL := key.filename, key.packagePURL, key.versionPURL + upstreamURL := h.buildUpstreamURL(scope, name, version+".zip", "", r.URL.RawQuery) archiveInfo, infoErr := h.fetchArchiveInfo(r.Context(), scope, name, version) if infoErr != nil { h.writeArtifactError(w, fmt.Errorf("fetching release metadata: %w", infoErr)) @@ -215,10 +268,7 @@ func (h *SwiftHandler) handleSourceArchive(w http.ResponseWriter, r *http.Reques headers := make(http.Header) headers.Set("Accept", requestAccept(r, swiftAcceptArchive)) - result, err := h.proxy.getOrFetchArtifactFromURLWithCachePURLs( - r.Context(), "swift", packageName, version, filename, packagePURL, versionPURL, - upstreamURL, headers, archiveInfo.checksum, "", - ) + result, err := h.fetchSourceArchive(r.Context(), key, version, upstreamURL, headers, archiveInfo) if err != nil { h.writeArtifactError(w, err) return @@ -229,6 +279,32 @@ func (h *SwiftHandler) handleSourceArchive(w http.ResponseWriter, r *http.Reques ServeArtifactRequest(w, r, result) } +// swiftArchiveKey is the cache key a release's source archive is stored +// under. +type swiftArchiveKey struct { + packageName, filename, packagePURL, versionPURL string +} + +// swiftSourceArchiveKey returns the cache key of the source archive of the +// canonical (lowercased) scope and name at version. +func swiftSourceArchiveKey(scope, name, version string) (swiftArchiveKey, error) { + key := swiftArchiveKey{packageName: scope + "/" + name, filename: fmt.Sprintf("%s-%s.zip", name, version)} + key.packagePURL, key.versionPURL = packageurl.MakeCacheStrings("swift", key.packageName, version) + if key.packagePURL == "" || key.versionPURL == "" { + return swiftArchiveKey{}, fmt.Errorf("%w: swift %q", errUnsupportedPackageIdentity, key.packageName) + } + return key, nil +} + +// fetchSourceArchive returns the source archive under key from the cache, or +// fetches it from upstreamURL, verified against the checksum in info. +func (h *SwiftHandler) fetchSourceArchive(ctx context.Context, key swiftArchiveKey, version, upstreamURL string, headers http.Header, info swiftArchiveInfo) (*CacheResult, error) { + return h.proxy.getOrFetchArtifactFromURLWithCachePURLs( + ctx, "swift", key.packageName, version, key.filename, key.packagePURL, key.versionPURL, + upstreamURL, headers, info.checksum, "", + ) +} + func (h *SwiftHandler) handleSourceArchiveHead( w http.ResponseWriter, r *http.Request, @@ -424,56 +500,6 @@ func swiftDigestHeader(checksum string) string { return "sha-256=" + base64.StdEncoding.EncodeToString(digest) } -func (h *SwiftHandler) proxySwiftResource(w http.ResponseWriter, r *http.Request, upstreamURL, defaultAccept string) { - req, err := http.NewRequestWithContext(r.Context(), r.Method, upstreamURL, nil) - if err != nil { - writeSwiftProblem(w, http.StatusInternalServerError, "failed to create upstream request") - return - } - req.Header.Set("Accept", requestAccept(r, defaultAccept)) - for _, name := range []string{"If-Modified-Since", "If-None-Match"} { - if value := r.Header.Get(name); value != "" { - req.Header.Set(name, value) - } - } - - resp, err := h.proxy.HTTPClient.Do(req) - if err != nil { - if writeUpstreamHeld(w, err) { - return - } - writeSwiftProblem(w, http.StatusBadGateway, "upstream request failed") - return - } - defer func() { _ = resp.Body.Close() }() - - h.proxy.relayResponse(w, r, resp, func(dst, src http.Header) { - copySwiftResponseHeaders(dst, src) - if location := src.Get("Location"); location != "" { - dst.Set("Location", h.rewriteRegistryURL(location, upstreamURL)) - } - for _, link := range src.Values("Link") { - dst.Add("Link", h.rewriteLinkHeader(link, upstreamURL)) - } - if dst.Get("Content-Version") == "" { - dst.Set("Content-Version", swiftContentVersion) - } - }) -} - -func copySwiftResponseHeaders(dst, src http.Header) { - for _, name := range []string{ - "Cache-Control", "Content-Disposition", "Content-Language", headerContentLength, - headerContentType, "Content-Version", "Digest", headerETag, headerLastModified, - "Retry-After", "Vary", "Warning", "X-Swift-Package-Signature", - "X-Swift-Package-Signature-Format", - } { - for _, value := range src.Values(name) { - dst.Add(name, value) - } - } -} - func (h *SwiftHandler) rewriteLinkHeader(value, upstreamRequestURL string) string { var result strings.Builder for len(value) > 0 { @@ -628,6 +654,10 @@ func (h *SwiftHandler) writeArtifactError(w http.ResponseWriter, err error) { writeSwiftProblem(w, http.StatusNotFound, "release not found") return } + if errors.Is(err, ErrArtifactBlocked) || errors.Is(err, ErrVersionDenied) { + writeSwiftProblem(w, http.StatusForbidden, err.Error()) + return + } if writeUpstreamHeld(w, err) { return } diff --git a/internal/handler/swift_cache.go b/internal/handler/swift_cache.go new file mode 100644 index 0000000..d778179 --- /dev/null +++ b/internal/handler/swift_cache.go @@ -0,0 +1,128 @@ +package handler + +import ( + "bytes" + "context" + "database/sql" + "errors" + "net/url" + "strings" + "time" + + "github.com/git-pkgs/proxy/internal/database" +) + +// swiftDocument is a release list or manifest as the upstream sent it. +type swiftDocument struct { + body []byte + contentType string + // link is the upstream Link header, its values joined, with the + // upstream's URLs. + link string + fetchedAt time.Time +} + +// fetchDocument returns the document at upstreamURL, from the metadata cache +// under cacheKey while it is fresh or when the upstream fails, and otherwise +// from upstream, storing it. The upstream Link header is cached with it, +// since it carries the pagination of release lists and the version-specific +// manifests a client picks from. +func (h *SwiftHandler) fetchDocument(ctx context.Context, cacheKey, upstreamURL, accept string) (*swiftDocument, error) { + cached := h.loadDocument(ctx, cacheKey) + if cached != nil && h.proxy.MetadataTTL > 0 && time.Since(cached.fetchedAt) < h.proxy.MetadataTTL { + return cached, nil + } + body, contentType, headers, err := h.fetchMetadataWithHeaders(ctx, upstreamURL, accept) + if err != nil { + if cached == nil || errors.Is(err, ErrUpstreamNotFound) { + return nil, err + } + h.proxy.Logger.Warn("upstream Swift metadata fetch failed, serving cached copy", + "url", upstreamURL, "error", err) + return cached, nil + } + doc := &swiftDocument{ + body: body, + contentType: contentType, + link: strings.Join(headers.Values("Link"), ", "), + fetchedAt: time.Now(), + } + h.storeDocument(ctx, cacheKey, doc) + return doc, nil +} + +func (h *SwiftHandler) documentsCached() bool { + return h.proxy.CacheMetadata && h.proxy.DB != nil && h.proxy.Storage != nil +} + +// loadDocument returns the cached document under cacheKey, or nil. +func (h *SwiftHandler) loadDocument(ctx context.Context, cacheKey string) *swiftDocument { + if !h.documentsCached() { + return nil + } + entry := h.proxy.storedMetadataEntry("swift", cacheKey, true) + if entry == nil { + return nil + } + reader, err := h.proxy.openMetadataEntry(ctx, "swift", cacheKey, entry) + if err != nil { + return nil + } + defer func() { _ = reader.Close() }() + body, err := h.proxy.ReadMetadata(reader) + if err != nil { + return nil + } + h.proxy.recordMetadataRead(entry) + return &swiftDocument{ + body: body, + contentType: entry.ContentType.String, + link: entry.Link.String, + fetchedAt: entry.FetchedAt.Time, + } +} + +// storeDocument caches doc under cacheKey. A failure is logged; the +// document is still served. +func (h *SwiftHandler) storeDocument(ctx context.Context, cacheKey string, doc *swiftDocument) { + if !h.documentsCached() { + return + } + storagePath := metadataStoragePath("swift", cacheKey) + size, hash, err := h.proxy.Storage.Store(ctx, storagePath, bytes.NewReader(doc.body)) + if err == nil { + err = h.proxy.DB.UpsertMetadataCache(&database.MetadataCacheEntry{ + Ecosystem: "swift", + Name: cacheKey, + StoragePath: storagePath, + Link: sql.NullString{String: doc.link, Valid: doc.link != ""}, + ContentType: sql.NullString{String: doc.contentType, Valid: doc.contentType != ""}, + ContentDigest: sql.NullString{String: "sha256:" + hash, Valid: hash != ""}, + Size: sql.NullInt64{Int64: size, Valid: true}, + FetchedAt: sql.NullTime{Time: doc.fetchedAt, Valid: true}, + }) + } + if err != nil { + h.proxy.Logger.Warn("failed to cache Swift metadata", "key", cacheKey, "error", err) + } +} + +func swiftReleasesCacheKey(scope, name, rawQuery string) string { + return swiftMetadataCacheKey("releases", scope, name, rawQuery) +} + +// swiftManifestCacheKey keys a manifest by its swift-version as a tools +// version, so the 5.8 of a manifest's alternate link and the 5.8.0 a client +// requests for it share a key. +func swiftManifestCacheKey(scope, name, version, rawQuery string) string { + if query, err := url.ParseQuery(rawQuery); err == nil { + if tools := query.Get("swift-version"); tools != "" { + for strings.Count(tools, ".") > 0 && strings.HasSuffix(tools, ".0") { + tools = strings.TrimSuffix(tools, ".0") + } + query.Set("swift-version", tools) + } + rawQuery = query.Encode() + } + return swiftMetadataCacheKey("manifest", scope, name, version, rawQuery) +} diff --git a/internal/handler/swift_cache_test.go b/internal/handler/swift_cache_test.go new file mode 100644 index 0000000..2b194a5 --- /dev/null +++ b/internal/handler/swift_cache_test.go @@ -0,0 +1,124 @@ +package handler + +import ( + "context" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync/atomic" + "testing" + "time" +) + +func TestSwiftReleaseListAndManifestServedFromCacheWhenUpstreamFails(t *testing.T) { + var down atomic.Bool + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if down.Load() { + http.Error(w, "down", http.StatusServiceUnavailable) + return + } + w.Header().Set("Link", `; rel="next"`) + if strings.HasSuffix(r.URL.Path, "/Package.swift") { + w.Header().Set("Content-Type", "text/x-swift") + _, _ = io.WriteString(w, "// swift-tools-version:5.9") + return + } + w.Header().Set("Content-Type", "application/json") + _, _ = io.WriteString(w, `{"releases":{"1.0.0":{}}}`) + })) + defer upstream.Close() + + for _, cacheMetadata := range []bool{true, false} { + proxy, _, _, _ := setupTestProxy(t) + proxy.CacheMetadata = cacheMetadata + routes := NewSwiftHandler(proxy, "https://proxy.example", upstream.URL+"/registry").Routes() + get := func(path string) *httptest.ResponseRecorder { + w := httptest.NewRecorder() + routes.ServeHTTP(w, httptest.NewRequest(http.MethodGet, path, nil)) + return w + } + down.Store(false) + for _, path := range []string{"/apple/example", "/apple/example/1.0.0/Package.swift"} { + if w := get(path); w.Code != http.StatusOK { + t.Fatalf("%s: status = %d with the upstream up", path, w.Code) + } + } + + down.Store(true) + for path, body := range map[string]string{"/apple/example": `"1.0.0"`, "/apple/example/1.0.0/Package.swift": "swift-tools-version:5.9"} { + w := get(path) + if !cacheMetadata { + if w.Code == http.StatusOK { + t.Errorf("%s: served without cache_metadata while the upstream is down", path) + } + continue + } + if w.Code != http.StatusOK || !strings.Contains(w.Body.String(), body) { + t.Errorf("%s: status = %d, body %q; want the cached copy", path, w.Code, w.Body.String()) + } + if link := w.Header().Get("Link"); link != `; rel="next"` { + t.Errorf("%s: Link = %q, want the cached Link rewritten", path, link) + } + } + } +} + +// TestSwiftCorruptManifestRefetched checks that a cached manifest whose +// stored bytes no longer match the recorded digest is fetched again, even +// within metadata_ttl. +func TestSwiftCorruptManifestRefetched(t *testing.T) { + var hits atomic.Int32 + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + hits.Add(1) + w.Header().Set("Content-Type", "text/x-swift") + _, _ = io.WriteString(w, "// swift-tools-version:5.9") + })) + defer upstream.Close() + + proxy, db, store, _ := setupTestProxy(t) + proxy.CacheMetadata = true + proxy.MetadataTTL = time.Hour + routes := NewSwiftHandler(proxy, "https://proxy.example", upstream.URL+"/registry").Routes() + get := func() *httptest.ResponseRecorder { + w := httptest.NewRecorder() + routes.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/apple/example/1.0.0/Package.swift", nil)) + return w + } + + get() + entry, err := db.GetMetadataCache("swift", swiftManifestCacheKey("apple", "example", "1.0.0", "")) + if err != nil || entry == nil { + t.Fatalf("manifest not cached: %v", err) + } + if !strings.HasPrefix(entry.ContentDigest.String, "sha256:") { + t.Fatalf("ContentDigest = %q, want a sha256 digest", entry.ContentDigest.String) + } + if w := get(); hits.Load() != 1 || w.Code != http.StatusOK { + t.Fatalf("fresh cached manifest: status %d, %d upstream fetches; want it served from the cache", w.Code, hits.Load()) + } + + if _, _, err := store.Store(context.Background(), entry.StoragePath, strings.NewReader("// tampered")); err != nil { + t.Fatal(err) + } + w := get() + if hits.Load() != 2 { + t.Errorf("upstream fetches = %d, want the corrupt manifest fetched again", hits.Load()) + } + if w.Code != http.StatusOK || !strings.Contains(w.Body.String(), "swift-tools-version:5.9") { + t.Errorf("status = %d, body %q; want the upstream manifest", w.Code, w.Body.String()) + } +} + +func TestSwiftManifestCacheKeyIgnoresToolsVersionZeros(t *testing.T) { + key := swiftManifestCacheKey("apple", "example", "1.0.0", "swift-version=5.8") + if got := swiftManifestCacheKey("apple", "example", "1.0.0", "swift-version=5.8.0"); got != key { + t.Error("5.8.0 and 5.8 have different keys") + } + if got := swiftManifestCacheKey("apple", "example", "1.0.0", "swift-version=5.9"); got == key { + t.Error("5.9 and 5.8 share a key") + } + if got := swiftManifestCacheKey("apple", "example", "1.0.0", ""); got == key { + t.Error("Package.swift and the 5.8 manifest share a key") + } +} diff --git a/internal/handler/swift_mirror.go b/internal/handler/swift_mirror.go new file mode 100644 index 0000000..5326c1d --- /dev/null +++ b/internal/handler/swift_mirror.go @@ -0,0 +1,187 @@ +package handler + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "net/http" + "net/url" + "strings" +) + +// MirrorRelease caches release version of scope.name so that a client can +// resolve and fetch the release without the upstream. +func (h *SwiftHandler) MirrorRelease(ctx context.Context, scope, name, version string) (*CacheResult, error) { + if !validSwiftPackageReference(scope, name, version) { + return nil, fmt.Errorf("invalid Swift registry release %s.%s@%s", scope, name, version) + } + scope, name = canonicalSwiftPackage(scope, name) + key, err := swiftSourceArchiveKey(scope, name, version) + if err != nil { + return nil, err + } + if h.documentsCached() { + if err := h.mirrorReleaseList(ctx, scope, name); err != nil { + return nil, fmt.Errorf("fetching release list: %w", err) + } + if err := h.mirrorManifests(ctx, scope, name, version); err != nil { + return nil, fmt.Errorf("fetching manifest: %w", err) + } + } + info, err := h.fetchArchiveInfo(ctx, scope, name, version) + if err != nil { + return nil, fmt.Errorf("fetching release metadata: %w", err) + } + headers := http.Header{"Accept": {swiftAcceptArchive}} + return h.fetchSourceArchive(ctx, key, version, h.buildUpstreamURL(scope, name, version+".zip", "", ""), headers, info) +} + +// maxSwiftReleasePages bounds the release list pages a mirror follows. +const maxSwiftReleasePages = 100 + +// mirrorReleaseList caches every page of the release list, under the keys +// the release list route reads for the page links it rewrites. +func (h *SwiftHandler) mirrorReleaseList(ctx context.Context, scope, name string) error { + query := "" + seen := map[string]bool{} + for page := 0; page < maxSwiftReleasePages && !seen[query]; page++ { + seen[query] = true + upstreamURL := h.buildUpstreamURL(scope, name, "", "", query) + doc, err := h.fetchDocument(ctx, swiftReleasesCacheKey(scope, name, query), upstreamURL, swiftAcceptJSON) + if err != nil { + return err + } + next := swiftLinkQueries(doc.link, "next", upstreamURL) + if len(next) == 0 { + return nil + } + query = next[0] + } + return nil +} + +// mirrorManifests caches Package.swift of a release and the version-specific +// manifests its Link header lists, under the keys the manifest route reads +// for the alternate links it rewrites. +func (h *SwiftHandler) mirrorManifests(ctx context.Context, scope, name, version string) error { + upstreamURL := h.buildUpstreamURL(scope, name, version, "Package.swift", "") + doc, err := h.fetchDocument(ctx, swiftManifestCacheKey(scope, name, version, ""), upstreamURL, swiftAcceptManifest) + if err != nil { + return err + } + for _, query := range swiftLinkQueries(doc.link, "alternate", upstreamURL) { + alternateURL := h.buildUpstreamURL(scope, name, version, "Package.swift", query) + if _, err := h.fetchDocument(ctx, swiftManifestCacheKey(scope, name, version, query), alternateURL, swiftAcceptManifest); err != nil { + return fmt.Errorf("%s: %w", query, err) + } + } + return nil +} + +// swiftLinkQueries returns the queries of the links with relation rel in +// link, a Link header, that point at requestURL's own path with a query, +// such as the next page of a release list or a version-specific manifest. +func swiftLinkQueries(link, rel, requestURL string) []string { + base, err := url.Parse(requestURL) + if err != nil { + return nil + } + var queries []string + for _, value := range strings.Split(link, ",") { + target, params, ok := strings.Cut(strings.TrimSpace(value), ";") + if !ok || !strings.HasPrefix(target, "<") || !strings.HasSuffix(target, ">") || !swiftLinkHasRel(params, rel) { + continue + } + ref, err := url.Parse(strings.TrimSpace(target[1 : len(target)-1])) + if err != nil { + continue + } + resolved := base.ResolveReference(ref) + if resolved.Host != base.Host || resolved.EscapedPath() != base.EscapedPath() || resolved.RawQuery == "" { + continue + } + queries = append(queries, resolved.RawQuery) + } + return queries +} + +func swiftLinkHasRel(params, rel string) bool { + for _, param := range strings.Split(params, ";") { + key, value, ok := strings.Cut(strings.TrimSpace(param), "=") + if !ok || !strings.EqualFold(strings.TrimSpace(key), "rel") { + continue + } + for _, r := range strings.Fields(strings.Trim(strings.TrimSpace(value), `"`)) { + if strings.EqualFold(r, rel) { + return true + } + } + } + return false +} + +// SwiftIdentity is a package's identity in a Swift registry, scope.name. +type SwiftIdentity struct { + Scope, Name string +} + +// ResolveIdentity returns the first registry identity the upstream lists for +// the source repository at sourceURL, the one a download uses. +func (h *SwiftHandler) ResolveIdentity(ctx context.Context, sourceURL string) (scope, name string, _ error) { + ids, err := h.ResolveIdentities(ctx, sourceURL) + if err != nil { + return "", "", err + } + return ids[0].Scope, ids[0].Name, nil +} + +// ResolveIdentities returns every registry identity the upstream lists for +// the source repository at sourceURL; the registry protocol allows several. +// The answer is cached as the identifiers route caches it. +func (h *SwiftHandler) ResolveIdentities(ctx context.Context, sourceURL string) ([]SwiftIdentity, error) { + query := url.Values{"url": {sourceURL}}.Encode() + body, _, err := h.proxy.FetchOrCacheMetadata(ctx, "swift", swiftMetadataCacheKey("identifiers", query), + h.upstreamURL+"/identifiers?"+query, swiftAcceptJSON) + if errors.Is(err, ErrUpstreamNotFound) { + return nil, fmt.Errorf("the Swift registry has no package for %s", sourceURL) + } + if err != nil { + return nil, err + } + return SwiftIdentitiesOf(body, sourceURL) +} + +// SwiftIdentityOf returns the scope and name of the first identity in body, +// a registry's answer to an identifiers lookup for sourceURL. +func SwiftIdentityOf(body []byte, sourceURL string) (scope, name string, _ error) { + ids, err := SwiftIdentitiesOf(body, sourceURL) + if err != nil { + return "", "", err + } + return ids[0].Scope, ids[0].Name, nil +} + +// SwiftIdentitiesOf returns every identity in body, a registry's answer to +// an identifiers lookup for sourceURL. One invalid identity fails the whole +// answer, so a policy never covers only some of them. +func SwiftIdentitiesOf(body []byte, sourceURL string) ([]SwiftIdentity, error) { + var answer struct { + Identifiers []string `json:"identifiers"` + } + if err := json.Unmarshal(body, &answer); err != nil { + return nil, fmt.Errorf("parsing the Swift registry's identifiers for %s: %w", sourceURL, err) + } + if len(answer.Identifiers) == 0 { + return nil, fmt.Errorf("the Swift registry has no package for %s", sourceURL) + } + ids := make([]SwiftIdentity, 0, len(answer.Identifiers)) + for _, identifier := range answer.Identifiers { + scope, name, ok := strings.Cut(identifier, ".") + if !ok || scope == "" || name == "" { + return nil, fmt.Errorf("the Swift registry answered %s with the invalid identity %q", sourceURL, identifier) + } + ids = append(ids, SwiftIdentity{Scope: scope, Name: name}) + } + return ids, nil +} diff --git a/internal/handler/swift_mirror_test.go b/internal/handler/swift_mirror_test.go new file mode 100644 index 0000000..8359a5e --- /dev/null +++ b/internal/handler/swift_mirror_test.go @@ -0,0 +1,22 @@ +package handler + +import ( + "reflect" + "testing" +) + +func TestSwiftLinkQueries(t *testing.T) { + const manifest = "https://registry.example/swift/apple/example/1.0.0/Package.swift" + link := `; rel="alternate"; filename="Package@swift-5.8.swift", ` + + `; rel=alternate, ` + + `; rel="alternate", ` + + `; rel="alternate", ` + + `; rel="canonical"` + + got := swiftLinkQueries(link, "alternate", manifest) + + want := []string{"swift-version=5.8", "swift-version=5.7"} + if !reflect.DeepEqual(got, want) { + t.Errorf("swiftLinkQueries() = %q, want %q", got, want) + } +} diff --git a/internal/handler/unrecorded_test.go b/internal/handler/unrecorded_test.go new file mode 100644 index 0000000..d87ddc9 --- /dev/null +++ b/internal/handler/unrecorded_test.go @@ -0,0 +1,415 @@ +package handler + +import ( + "context" + "errors" + "io" + "maps" + "net/http" + "net/http/httptest" + "slices" + "sync" + "testing" + "time" +) + +// These tests refetch an artifact whose stored file is gone while +// pending_deletes refuses writes. The record can't move to the new file and +// the file can't be queued, so the fetch must serve it to every caller sharing +// it and delete it once the last of them is done. + +const ( + unrecordedContent = "refetched content" + unrecordedURL = "https://example.com/gone.tgz" +) + +func setupUnrecorded(t *testing.T) (*Proxy, *mockStorage) { + t.Helper() + proxy, db, store, _ := setupTestProxy(t) + seedPackage(t, db, store, "npm", "gone", "1.0.0", "gone-1.0.0.tgz", "old content") + oldPath := recordedStoragePath(t, db, "pkg:npm/gone@1.0.0", "gone-1.0.0.tgz") + delete(store.files, oldPath) + if _, err := db.Exec(`CREATE TRIGGER refuse_queue BEFORE INSERT ON pending_deletes + BEGIN SELECT RAISE(ABORT, 'queue refused'); END`); err != nil { + t.Fatalf("creating trigger: %v", err) + } + t.Cleanup(func() { + if got := recordedStoragePath(t, db, "pkg:npm/gone@1.0.0", "gone-1.0.0.tgz"); got != oldPath { + t.Errorf("record points at %q, want it kept at %q", got, oldPath) + } + }) + return proxy, store +} + +func fetchGone(ctx context.Context, proxy *Proxy) (*CacheResult, error) { + return proxy.GetOrFetchArtifactFromURL(ctx, "npm", "gone", "1.0.0", "gone-1.0.0.tgz", unrecordedURL) +} + +func storedFiles(store *mockStorage) []string { + store.mu.Lock() + defer store.mu.Unlock() + return slices.Collect(maps.Keys(store.files)) +} + +func readAndClose(t *testing.T, res *CacheResult) { + t.Helper() + body, err := io.ReadAll(res.Reader) + _ = res.Reader.Close() + if err != nil || string(body) != unrecordedContent { + t.Errorf("body = %q, %v, want %q", body, err, unrecordedContent) + } +} + +// waitForWaiters blocks until n callers wait on the one fetch in flight. +func waitForWaiters(t *testing.T, proxy *Proxy, n int) { + t.Helper() + deadline := time.Now().Add(5 * time.Second) + for time.Now().Before(deadline) { + proxy.fetchMu.Lock() + got := -1 + for _, f := range proxy.inFlight { + got = f.waiters + } + proxy.fetchMu.Unlock() + if got == n { + return + } + time.Sleep(time.Millisecond) + } + t.Fatalf("never saw %d waiters on the fetch", n) +} + +func TestUnrecordedRefetchIsDeletedOnceServed(t *testing.T) { + proxy, store := setupUnrecorded(t) + fetcher := &countingFetcher{content: unrecordedContent} + proxy.Fetcher = fetcher + + for range 2 { + res, err := fetchGone(context.Background(), proxy) + if err != nil { + t.Fatalf("fetch: %v", err) + } + if got := storedFiles(store); len(got) != 1 { + t.Errorf("stored files while serving = %v, want the refetched one", got) + } + readAndClose(t, res) + if got := storedFiles(store); len(got) != 0 { + t.Errorf("stored files after serving = %v, want none left untracked", got) + } + } +} + +func TestUnrecordedRefetchServesRangeRequests(t *testing.T) { + proxy, store := setupUnrecorded(t) + store.seekable = true + proxy.Fetcher = &countingFetcher{content: unrecordedContent} + + res, err := fetchGone(context.Background(), proxy) + if err != nil { + t.Fatalf("fetch: %v", err) + } + req := httptest.NewRequest(http.MethodGet, "/gone-1.0.0.tgz", nil) + req.Header.Set("Range", "bytes=2-5") + rec := httptest.NewRecorder() + ServeArtifactRequest(rec, req, res) + + if rec.Code != http.StatusPartialContent || rec.Body.String() != unrecordedContent[2:6] { + t.Errorf("range response = %d %q, want 206 %q", rec.Code, rec.Body.String(), unrecordedContent[2:6]) + } + if got := storedFiles(store); len(got) != 0 { + t.Errorf("stored files after serving = %v, want none left untracked", got) + } +} + +// TestUnrecordedRefetchWaitsForEveryCaller keeps the object until the caller +// that ran the fetch and every caller that waited on it have closed. +func TestUnrecordedRefetchWaitsForEveryCaller(t *testing.T) { + const waiters = 4 + proxy, store := setupUnrecorded(t) + fetcher := newGatedFetcher(unrecordedContent) + proxy.Fetcher = fetcher + + leader := make(chan *CacheResult, 1) + go func() { + res, err := fetchGone(context.Background(), proxy) + if err != nil { + t.Errorf("leader: %v", err) + } + leader <- res + }() + <-fetcher.entered + + results := make(chan *CacheResult, waiters) + var wg sync.WaitGroup + for range waiters { + wg.Go(func() { + res, err := fetchGone(context.Background(), proxy) + if err != nil { + t.Errorf("waiter: %v", err) + return + } + results <- res + }) + } + waitForWaiters(t, proxy, waiters) + close(fetcher.release) + + // The leader holds its reader open while every waiter reads and closes. + lead := <-leader + wg.Wait() + close(results) + for res := range results { + readAndClose(t, res) + } + if got := storedFiles(store); len(got) != 1 { + t.Fatalf("stored files with the leader still reading = %v, want the refetched one", got) + } + readAndClose(t, lead) + if got := storedFiles(store); len(got) != 0 { + t.Errorf("stored files after every caller closed = %v, want none", got) + } +} + +func TestUnrecordedRefetchSurvivesDoubleClose(t *testing.T) { + proxy, store := setupUnrecorded(t) + fetcher := newGatedFetcher(unrecordedContent) + proxy.Fetcher = fetcher + + leader := make(chan *CacheResult, 1) + go func() { + res, err := fetchGone(context.Background(), proxy) + if err != nil { + t.Errorf("leader: %v", err) + } + leader <- res + }() + <-fetcher.entered + + waiter := make(chan *CacheResult, 1) + go func() { + res, err := fetchGone(context.Background(), proxy) + if err != nil { + t.Errorf("waiter: %v", err) + } + waiter <- res + }() + waitForWaiters(t, proxy, 1) + close(fetcher.release) + + lead, wait := <-leader, <-waiter + readAndClose(t, lead) + _ = lead.Reader.Close() + if got := storedFiles(store); len(got) != 1 { + t.Fatalf("stored files with the waiter still reading = %v, want the refetched one", got) + } + readAndClose(t, wait) + if got := storedFiles(store); len(got) != 0 { + t.Errorf("stored files after every caller closed = %v, want none", got) + } +} + +// ctxStorage fails to open under a cancelled context, as cloud backends do. +type ctxStorage struct{ *mockStorage } + +func (s ctxStorage) Open(ctx context.Context, path string) (io.ReadCloser, error) { + if err := ctx.Err(); err != nil { + return nil, err + } + return s.mockStorage.Open(ctx, path) +} + +// TestUnrecordedRefetchOutlivesDetachedCaller is the retry a detached fetch +// exists for: the client that started it gave up, and its retry waits on the +// same fetch. The retry must get the bytes rather than a deleted object. +func TestUnrecordedRefetchOutlivesDetachedCaller(t *testing.T) { + proxy, store := setupUnrecorded(t) + proxy.Storage = ctxStorage{store} + fetcher := newGatedFetcher(unrecordedContent) + proxy.Fetcher = fetcher + + ctx, cancel := context.WithCancel(DetachUpstreamFetch(context.Background())) + leaderDone := make(chan struct{}) + go func() { + defer close(leaderDone) + res, _ := fetchGone(ctx, proxy) + drain(res) + }() + <-fetcher.entered + cancel() + + retry := make(chan *CacheResult, 1) + go func() { + res, err := fetchGone(context.Background(), proxy) + if err != nil { + t.Errorf("retry: %v", err) + } + retry <- res + }() + waitForWaiters(t, proxy, 1) + close(fetcher.release) + <-leaderDone + + if res := <-retry; res != nil { + readAndClose(t, res) + } + if got := storedFiles(store); len(got) != 0 { + t.Errorf("stored files after the retry closed = %v, want none", got) + } +} + +// TestUnrecordedRefetchIgnoresWaiterThatLeft checks that a waiter giving up +// before the fetch ends does not keep the object forever. +func TestUnrecordedRefetchIgnoresWaiterThatLeft(t *testing.T) { + proxy, store := setupUnrecorded(t) + fetcher := newGatedFetcher(unrecordedContent) + proxy.Fetcher = fetcher + + leader := make(chan *CacheResult, 1) + go func() { + res, err := fetchGone(context.Background(), proxy) + if err != nil { + t.Errorf("leader: %v", err) + } + leader <- res + }() + <-fetcher.entered + + ctx, cancel := context.WithCancel(context.Background()) + left := make(chan error, 1) + go func() { + _, err := fetchGone(ctx, proxy) + left <- err + }() + waitForWaiters(t, proxy, 1) + cancel() + if err := <-left; !errors.Is(err, context.Canceled) { + t.Fatalf("waiter that left: err = %v, want context.Canceled", err) + } + close(fetcher.release) + + readAndClose(t, <-leader) + if got := storedFiles(store); len(got) != 0 { + t.Errorf("stored files after the leader closed = %v, want none", got) + } +} + +// TestLeaveFetch covers both ways a waiter can give up: before the fetch +// finished, when it was not handed a hold yet, and after, when it was. +func TestLeaveFetch(t *testing.T) { + proxy, _, _, _ := setupTestProxy(t) + deleted := false + newFetch := func() *inflightFetch { + f := &inflightFetch{done: make(chan struct{}), waiters: 1} + f.unrecorded = &unrecordedObject{delete: func() { deleted = true }} + f.unrecorded.refs.Add(1) + return f + } + + f := newFetch() + proxy.leaveFetch(f) + if f.waiters != 0 || deleted { + t.Errorf("before done: waiters = %d, deleted = %v, want 0 and false", f.waiters, deleted) + } + + f = newFetch() + close(f.done) + proxy.leaveFetch(f) + if f.waiters != 1 || !deleted { + t.Errorf("after done: waiters = %d, deleted = %v, want 1 and true", f.waiters, deleted) + } +} + +// TestRecordedAt is the check that keeps an object whose record update +// committed despite reporting an error. +func TestRecordedAt(t *testing.T) { + proxy, db, store, _ := setupTestProxy(t) + seedPackage(t, db, store, "npm", "kept", "1.0.0", "kept-1.0.0.tgz", "content") + path := recordedStoragePath(t, db, "pkg:npm/kept@1.0.0", "kept-1.0.0.tgz") + + if !proxy.recordedAt("pkg:npm/kept@1.0.0", "kept-1.0.0.tgz", path) { + t.Error("record pointing at the path not seen") + } + if proxy.recordedAt("pkg:npm/kept@1.0.0", "kept-1.0.0.tgz", "other/path.tgz") { + t.Error("record pointing elsewhere taken as recorded") + } + if proxy.recordedAt("pkg:npm/none@1.0.0", "none-1.0.0.tgz", path) { + t.Error("missing record taken as recorded") + } + _ = db.Close() + if proxy.recordedAt("pkg:npm/kept@1.0.0", "kept-1.0.0.tgz", path) { + t.Error("failed lookup taken as recorded") + } +} + +// TestUnrecordedStreamedMiss streams an unrecorded refetch to the caller +// that started it, and the waiters still get the stored object. A caller fed +// from upstream holds no reader on it, so it is deleted once the waiters are +// done; one that fell behind reads it, so it is deleted once that caller is +// done too. +func TestUnrecordedStreamedMiss(t *testing.T) { + for _, behind := range []bool{false, true} { + t.Run(map[bool]string{false: "fed", true: "behind"}[behind], func(t *testing.T) { + testUnrecordedStreamedMiss(t, behind) + }) + } +} + +func testUnrecordedStreamedMiss(t *testing.T, behind bool) { + t.Helper() + if behind { + old := clientFeedLimit + clientFeedLimit = 4 + t.Cleanup(func() { clientFeedLimit = old }) + } + proxy, store := setupUnrecorded(t) + fetcher := newGatedFetcher(unrecordedContent) + proxy.Fetcher = fetcher + + leader := make(chan *CacheResult, 1) + go func() { + res, err := fetchGone(StreamCacheMiss(context.Background()), proxy) + if err != nil { + t.Errorf("leader: %v", err) + } + leader <- res + }() + <-fetcher.entered + waiter := make(chan *CacheResult, 1) + go func() { + res, err := fetchGone(context.Background(), proxy) + if err != nil { + t.Errorf("waiter: %v", err) + } + waiter <- res + }() + waitForWaiters(t, proxy, 1) + close(fetcher.release) + + lead := <-leader + if lead == nil || lead.Artifact.Size != -1 { + t.Fatalf("leader = %+v, want a stream", lead) + } + w := <-waiter + if w == nil { + t.FailNow() + } + readAndClose(t, w) + if behind { + // The leader reads the stored copy, so it must outlive the + // waiter. + if len(storedFiles(store)) == 0 { + t.Fatal("stored copy deleted while the leader still reads it") + } + readAndClose(t, lead) + } + deadline := time.Now().Add(5 * time.Second) + for len(storedFiles(store)) != 0 && time.Now().Before(deadline) { + time.Sleep(time.Millisecond) + } + if got := storedFiles(store); len(got) != 0 { + t.Errorf("stored files after every reader closed = %v, want none", got) + } + if !behind { + readAndClose(t, lead) + } +} diff --git a/internal/handler/upstream_body.go b/internal/handler/upstream_body.go new file mode 100644 index 0000000..7db9076 --- /dev/null +++ b/internal/handler/upstream_body.go @@ -0,0 +1,26 @@ +package handler + +import ( + "errors" + "io" +) + +// upstreamBodyReader marks a failure to read a document from upstream, so a +// body upstream cuts off is told apart from one that ends, and from a +// failure to store it. +type upstreamBodyReader struct{ r io.Reader } + +func (u upstreamBodyReader) Read(b []byte) (int, error) { + n, err := u.r.Read(b) + if err != nil && !errors.Is(err, io.EOF) { + err = &upstreamBodyError{err} + } + return n, err +} + +// upstreamBodyError is a failure to read a document from upstream. It is +// handled as an upstream failure: the stored copy, if any, is served. +type upstreamBodyError struct{ err error } + +func (e *upstreamBodyError) Error() string { return "reading upstream metadata: " + e.err.Error() } +func (e *upstreamBodyError) Unwrap() error { return e.err } diff --git a/internal/handler/upstream_held.go b/internal/handler/upstream_held.go index fa2ff96..57ac84d 100644 --- a/internal/handler/upstream_held.go +++ b/internal/handler/upstream_held.go @@ -6,14 +6,14 @@ import ( "net/http" "strconv" - "github.com/git-pkgs/proxy/internal/httpclient" + registryclient "github.com/git-pkgs/registries/client" ) // writeUpstreamHeld answers a request the rate limit gate refused to send // with 503 and the Retry-After the upstream asked for, and reports whether // err was such a refusal. func writeUpstreamHeld(w http.ResponseWriter, err error) bool { - var held *httpclient.HeldError + var held *registryclient.HeldError if !errors.As(err, &held) { return false } @@ -25,3 +25,29 @@ func writeUpstreamHeld(w http.ResponseWriter, err error) bool { http.Error(w, held.Error(), http.StatusServiceUnavailable) return true } + +// UpstreamHolds reports whether requests to a URL's host are held by rate +// limiting. *registryclient.RateLimitGate and the shared gate in +// internal/httpclient implement it. +type UpstreamHolds interface { + // Held returns a *registryclient.HeldError while rawURL's host is held. + Held(rawURL string) error +} + +// upstreamHeld returns the hold on rawURL's host, if any. +func (p *Proxy) upstreamHeld(rawURL string) error { + if p.RateLimits == nil { + return nil + } + return p.RateLimits.Held(rawURL) +} + +// reloadUpstreamHolds rereads holds shared with other instances, when the +// gate shares them. It is called after another instance's fetch failed, +// since a 429 there will have placed a hold this instance may not have read +// yet. +func (p *Proxy) reloadUpstreamHolds() { + if r, ok := p.RateLimits.(interface{ Reload() }); ok { + r.Reload() + } +} diff --git a/internal/handler/upstream_test.go b/internal/handler/upstream_test.go index 7839eaa..9d99214 100644 --- a/internal/handler/upstream_test.go +++ b/internal/handler/upstream_test.go @@ -1,6 +1,7 @@ package handler import ( + "context" "io" "net/http" "net/http/httptest" @@ -92,9 +93,10 @@ func TestHexHandlerUsesConfiguredAPIUpstream(t *testing.T) { upstream.URL+"/hex", upstream.URL+"/hex-api", ) - _, err := h.fetchFilteredVersions(httptest.NewRequest(http.MethodGet, "/", nil), "demo") - if err != nil { - t.Fatalf("fetchFilteredVersions failed: %v", err) + timed := h.timedPackage("demo") + res := h.proxy.lookupMetadata(context.Background(), "hex", timed.timesKey, timed.timesURL, timed.timesAccept, "", nil) + if res.err != nil { + t.Fatalf("fetching publish times failed: %v", res.err) } if requestedPath != "/hex-api/api/packages/demo" { t.Errorf("API path = %q, want %q", requestedPath, "/hex-api/api/packages/demo") diff --git a/internal/httpclient/ratelimit.go b/internal/httpclient/ratelimit.go deleted file mode 100644 index 53e3e8e..0000000 --- a/internal/httpclient/ratelimit.go +++ /dev/null @@ -1,228 +0,0 @@ -package httpclient - -import ( - "errors" - "fmt" - "log/slog" - "net/http" - "net/url" - "strconv" - "strings" - "sync" - "time" -) - -const ( - // holdWithoutHeader is the first hold for a 429 that carries no usable - // Retry-After; each further such 429 after a hold expires doubles it. - holdWithoutHeader = time.Minute - maxHoldWithoutHeader = 15 * time.Minute //nolint:mnd // doubling stops here - // maxHold caps what an upstream's Retry-After can ask for. - maxHold = time.Hour -) - -// ErrUpstreamHeld marks a request the gate did not send because the upstream -// is rate limiting this proxy. Match it with errors.Is; the *HeldError in -// the chain carries the host and how long to wait. -var ErrUpstreamHeld = errors.New("upstream is rate limiting this proxy") - -// HeldError is returned in place of a response while a host is held. -type HeldError struct { - Host string - Until time.Time - RetryAfter time.Duration -} - -func (e *HeldError) Error() string { - return fmt.Sprintf("%s is rate limiting this proxy, holding requests for %s", e.Host, e.RetryAfter.Round(time.Second)) -} - -func (e *HeldError) Is(target error) bool { return target == ErrUpstreamHeld } - -type hostHold struct { - until time.Time - strikes int -} - -// RateLimitGate stops sending to a host that answered 429, or 503 with a -// Retry-After, for as long as it asked, and fails those requests locally -// with a *HeldError instead. Clients and fetchers above it see an error -// rather than a slow upstream, so they fall back to cache or fail fast -// without adding to the traffic the upstream is already refusing. The first -// non-limited response after the hold ends releases it. -type RateLimitGate struct { - base http.RoundTripper - Logger *slog.Logger - // OnHold is called with the host each time a hold starts. - OnHold func(host string) - now func() time.Time - - mu sync.Mutex - holds map[string]*hostHold -} - -// NewRateLimitGate wraps base. A nil base uses http.DefaultTransport. -func NewRateLimitGate(base http.RoundTripper) *RateLimitGate { - if base == nil { - base = http.DefaultTransport - } - return &RateLimitGate{ - base: base, - now: time.Now, - holds: make(map[string]*hostHold), - } -} - -// RoundTrip implements http.RoundTripper. -func (g *RateLimitGate) RoundTrip(req *http.Request) (*http.Response, error) { - host := hostKey(req.URL) - if until, held := g.heldUntil(host); held { - return nil, &HeldError{Host: host, Until: until, RetryAfter: until.Sub(g.now())} - } - - resp, err := g.base.RoundTrip(req) - if err != nil { - return nil, err - } - - retryAfter := resp.Header.Get("Retry-After") - switch { - case resp.StatusCode == http.StatusTooManyRequests, - resp.StatusCode == http.StatusServiceUnavailable && retryAfter != "": - g.hold(host, retryAfter) - default: - g.release(host) - } - return resp, nil -} - -// Held returns a *HeldError when requests to rawURL's host are being held, -// and nil otherwise. It is safe to call on a nil gate. -func (g *RateLimitGate) Held(rawURL string) error { - if g == nil { - return nil - } - u, err := url.Parse(rawURL) - if err != nil { - return nil - } - host := hostKey(u) - until, held := g.heldUntil(host) - if !held { - return nil - } - return &HeldError{Host: host, Until: until, RetryAfter: until.Sub(g.now())} -} - -// Holds returns the hosts currently held and when each hold ends. It is -// safe to call on a nil gate. -func (g *RateLimitGate) Holds() map[string]time.Time { - if g == nil { - return nil - } - now := g.now() - g.mu.Lock() - defer g.mu.Unlock() - held := make(map[string]time.Time) - for host, h := range g.holds { - if now.Before(h.until) { - held[host] = h.until - } - } - return held -} - -func (g *RateLimitGate) heldUntil(host string) (time.Time, bool) { - now := g.now() - g.mu.Lock() - defer g.mu.Unlock() - h, ok := g.holds[host] - if !ok || !now.Before(h.until) { - return time.Time{}, false - } - return h.until, true -} - -func (g *RateLimitGate) hold(host, header string) { - now := g.now() - - g.mu.Lock() - h, ok := g.holds[host] - if !ok { - h = &hostHold{} - g.holds[host] = h - } - // Responses already in flight when a hold starts all report the same - // rate limiting; only a 429 after the hold ran out is a further strike. - if !now.Before(h.until) { - h.strikes++ - } - d, fromHeader := parseRetryAfter(header, now) - if !fromHeader { - d = min(holdWithoutHeader<<(h.strikes-1), maxHoldWithoutHeader) - } - d = min(d, maxHold) - until := now.Add(d) - if until.After(h.until) { - h.until = until - } - g.mu.Unlock() - - if g.Logger != nil { - source := "default" - if fromHeader { - source = "retry-after" - } - g.Logger.Warn("upstream rate limited this proxy, holding its requests", - "host", host, "hold", d.Round(time.Second).String(), "source", source, - "until", until.UTC().Format(time.RFC3339)) - } - if g.OnHold != nil { - g.OnHold(host) - } -} - -// release drops host's hold once it has ended. Nothing is sent during a -// hold, so a success arriving while one is active was sent before it began. -func (g *RateLimitGate) release(host string) { - now := g.now() - g.mu.Lock() - h, had := g.holds[host] - if had && now.Before(h.until) { - g.mu.Unlock() - return - } - delete(g.holds, host) - g.mu.Unlock() - if had && g.Logger != nil { - g.Logger.Info("upstream rate limit cleared", "host", host) - } -} - -// parseRetryAfter reads a Retry-After value as delay seconds or an HTTP -// date. It reports false for anything unusable, including a zero or past -// value, so the caller applies its default instead. -func parseRetryAfter(value string, now time.Time) (time.Duration, bool) { - value = strings.TrimSpace(value) - if value == "" { - return 0, false - } - if secs, err := strconv.ParseInt(value, 10, 64); err == nil { - if secs <= 0 { - return 0, false - } - return time.Duration(secs) * time.Second, true - } - at, err := http.ParseTime(value) - if err != nil || !at.After(now) { - return 0, false - } - return at.Sub(now), true -} - -func hostKey(u *url.URL) string { - if u == nil { - return "" - } - return strings.ToLower(u.Host) -} diff --git a/internal/httpclient/ratelimit_test.go b/internal/httpclient/ratelimit_test.go deleted file mode 100644 index 8ad7e9c..0000000 --- a/internal/httpclient/ratelimit_test.go +++ /dev/null @@ -1,257 +0,0 @@ -package httpclient - -import ( - "errors" - "io" - "net/http" - "strings" - "testing" - "time" -) - -type gateHarness struct { - gate *RateLimitGate - now time.Time - calls map[string]int - // respond returns the status and Retry-After the fake upstream answers with. - respond func(req *http.Request) (int, string) -} - -func newGateHarness() *gateHarness { - h := &gateHarness{ - now: time.Date(2026, 10, 14, 12, 0, 0, 0, time.UTC), - calls: map[string]int{}, - respond: func(*http.Request) (int, string) { - return http.StatusOK, "" - }, - } - h.gate = NewRateLimitGate(roundTripperFunc(func(req *http.Request) (*http.Response, error) { - h.calls[req.URL.Host]++ - status, retryAfter := h.respond(req) - resp := &http.Response{ - StatusCode: status, - Header: http.Header{}, - Body: io.NopCloser(strings.NewReader("")), - Request: req, - } - if retryAfter != "" { - resp.Header.Set("Retry-After", retryAfter) - } - return resp, nil - })) - h.gate.now = func() time.Time { return h.now } - return h -} - -func (h *gateHarness) get(t *testing.T, rawURL string) (*http.Response, error) { - t.Helper() - req, err := http.NewRequest(http.MethodGet, rawURL, nil) - if err != nil { - t.Fatalf("building request: %v", err) - } - resp, err := h.gate.RoundTrip(req) - if resp != nil { - _ = resp.Body.Close() - } - return resp, err -} - -func TestRateLimitGate_HoldsHostForRetryAfter(t *testing.T) { - h := newGateHarness() - h.respond = func(*http.Request) (int, string) { return http.StatusTooManyRequests, "785" } - - resp, err := h.get(t, "https://repo1.maven.org/maven2/a/b/maven-metadata.xml") - if err != nil || resp.StatusCode != http.StatusTooManyRequests { - t.Fatalf("first request: resp=%v err=%v, want the upstream 429 passed through", resp, err) - } - - h.respond = func(*http.Request) (int, string) { return http.StatusOK, "" } - _, err = h.get(t, "https://repo1.maven.org/maven2/a/b/b-1.0.jar") - var held *HeldError - if !errors.As(err, &held) || !errors.Is(err, ErrUpstreamHeld) { - t.Fatalf("second request error = %v, want *HeldError", err) - } - if held.Host != "repo1.maven.org" || held.RetryAfter != 785*time.Second { - t.Errorf("held = %+v, want repo1.maven.org for 785s", held) - } - if h.calls["repo1.maven.org"] != 1 { - t.Errorf("upstream calls = %d, want 1: held requests must not reach it", h.calls["repo1.maven.org"]) - } - - if _, err := h.get(t, "https://plugins.gradle.org/m2/x.pom"); err != nil { - t.Errorf("other host: %v, want unaffected", err) - } - - holds := h.gate.Holds() - if until, ok := holds["repo1.maven.org"]; !ok || !until.Equal(h.now.Add(785*time.Second)) { - t.Errorf("Holds() = %v, want repo1.maven.org until now+785s", holds) - } -} - -func TestRateLimitGate_ReleasesWhenHoldExpiresAndUpstreamServes(t *testing.T) { - h := newGateHarness() - h.respond = func(*http.Request) (int, string) { return http.StatusTooManyRequests, "60" } - _, _ = h.get(t, "https://repo1.maven.org/x") - - h.now = h.now.Add(59 * time.Second) - if _, err := h.get(t, "https://repo1.maven.org/x"); !errors.Is(err, ErrUpstreamHeld) { - t.Fatalf("at 59s: err = %v, want still held", err) - } - - h.now = h.now.Add(time.Second) - h.respond = func(*http.Request) (int, string) { return http.StatusOK, "" } - resp, err := h.get(t, "https://repo1.maven.org/x") - if err != nil || resp.StatusCode != http.StatusOK { - t.Fatalf("at 60s: resp=%v err=%v, want the request sent", resp, err) - } - if len(h.gate.Holds()) != 0 { - t.Errorf("Holds() = %v after a success, want empty", h.gate.Holds()) - } -} - -func TestRateLimitGate_LateSuccessKeepsHold(t *testing.T) { - h := newGateHarness() - // The slow request is in flight when the limited one starts the hold, - // and its 200 arrives afterwards. - h.respond = func(req *http.Request) (int, string) { - if req.URL.Path == "/limited" { - return http.StatusTooManyRequests, "120" - } - _, _ = h.get(t, "https://repo1.maven.org/limited") - return http.StatusOK, "" - } - - resp, err := h.get(t, "https://repo1.maven.org/slow") - if err != nil || resp.StatusCode != http.StatusOK { - t.Fatalf("slow request: resp=%v err=%v, want its 200", resp, err) - } - if until, ok := h.gate.Holds()["repo1.maven.org"]; !ok || !until.Equal(h.now.Add(120*time.Second)) { - t.Fatalf("Holds() = %v after a late 200, want repo1.maven.org until now+120s", h.gate.Holds()) - } - if _, err := h.get(t, "https://repo1.maven.org/x"); !errors.Is(err, ErrUpstreamHeld) { - t.Errorf("next request err = %v, want held", err) - } -} - -func TestRateLimitGate_Held(t *testing.T) { - var nilGate *RateLimitGate - if err := nilGate.Held("https://repo1.maven.org/x"); err != nil { - t.Errorf("nil gate Held() = %v, want nil", err) - } - - h := newGateHarness() - if err := h.gate.Held("https://repo1.maven.org/x"); err != nil { - t.Errorf("before any limit: Held() = %v, want nil", err) - } - h.respond = func(*http.Request) (int, string) { return http.StatusTooManyRequests, "45" } - _, _ = h.get(t, "https://repo1.maven.org/x") - - var held *HeldError - if err := h.gate.Held("https://REPO1.maven.org/a/b.jar"); !errors.As(err, &held) || held.RetryAfter != 45*time.Second { - t.Errorf("Held() = %v, want *HeldError for 45s", err) - } - if err := h.gate.Held("https://plugins.gradle.org/m2/x.pom"); err != nil { - t.Errorf("other host: Held() = %v, want nil", err) - } - h.now = h.now.Add(45 * time.Second) - if err := h.gate.Held("https://repo1.maven.org/x"); err != nil { - t.Errorf("after the hold: Held() = %v, want nil", err) - } -} - -func TestRateLimitGate_DefaultHoldDoublesWithoutHeader(t *testing.T) { - h := newGateHarness() - h.respond = func(*http.Request) (int, string) { return http.StatusTooManyRequests, "" } - - wantHolds := []time.Duration{time.Minute, 2 * time.Minute, 4 * time.Minute} - for i, want := range wantHolds { - _, _ = h.get(t, "https://repo1.maven.org/x") - until := h.gate.Holds()["repo1.maven.org"] - if got := until.Sub(h.now); got != want { - t.Errorf("strike %d: hold = %s, want %s", i+1, got, want) - } - h.now = until - } -} - -func TestRateLimitGate_ConcurrentLimitedResponsesAreOneStrike(t *testing.T) { - h := newGateHarness() - h.respond = func(*http.Request) (int, string) { return http.StatusTooManyRequests, "" } - - // Two requests already in flight when the limit starts both see 429. - // The gate only consults the hold before sending, so drive the base - // directly for the second. - _, _ = h.get(t, "https://repo1.maven.org/x") - req, _ := http.NewRequest(http.MethodGet, "https://repo1.maven.org/y", nil) - h.gate.hold(hostKey(req.URL), "") - - if got := h.gate.Holds()["repo1.maven.org"].Sub(h.now); got != time.Minute { - t.Errorf("hold = %s after two concurrent 429s, want the single-strike %s", got, time.Minute) - } -} - -func TestRateLimitGate_CapsUpstreamRetryAfter(t *testing.T) { - h := newGateHarness() - h.respond = func(*http.Request) (int, string) { return http.StatusTooManyRequests, "86400" } - _, _ = h.get(t, "https://repo1.maven.org/x") - if got := h.gate.Holds()["repo1.maven.org"].Sub(h.now); got != maxHold { - t.Errorf("hold = %s, want capped at %s", got, maxHold) - } -} - -func TestRateLimitGate_ServiceUnavailableNeedsRetryAfter(t *testing.T) { - h := newGateHarness() - h.respond = func(*http.Request) (int, string) { return http.StatusServiceUnavailable, "" } - _, _ = h.get(t, "https://repo1.maven.org/x") - if len(h.gate.Holds()) != 0 { - t.Errorf("503 without Retry-After created hold %v, want none", h.gate.Holds()) - } - - h.respond = func(*http.Request) (int, string) { return http.StatusServiceUnavailable, "30" } - _, _ = h.get(t, "https://repo1.maven.org/x") - if got := h.gate.Holds()["repo1.maven.org"].Sub(h.now); got != 30*time.Second { - t.Errorf("hold = %s, want 30s from the 503's Retry-After", got) - } -} - -func TestRateLimitGate_ReportsHoldsAndNilSafe(t *testing.T) { - var nilGate *RateLimitGate - if holds := nilGate.Holds(); holds != nil { - t.Errorf("nil gate Holds() = %v, want nil", holds) - } - - h := newGateHarness() - var reported []string - h.gate.OnHold = func(host string) { - reported = append(reported, host) - } - h.respond = func(*http.Request) (int, string) { return http.StatusTooManyRequests, "10" } - _, _ = h.get(t, "https://repo1.maven.org/x") - if len(reported) != 1 || reported[0] != "repo1.maven.org" { - t.Errorf("OnHold reported %v, want [repo1.maven.org]", reported) - } -} - -func TestParseRetryAfter(t *testing.T) { - now := time.Date(2026, 10, 14, 12, 0, 0, 0, time.UTC) - tests := []struct { - value string - want time.Duration - ok bool - }{ - {"785", 785 * time.Second, true}, - {" 30 ", 30 * time.Second, true}, - {"0", 0, false}, - {"-5", 0, false}, - {"", 0, false}, - {"soon", 0, false}, - {now.Add(90 * time.Second).Format(http.TimeFormat), 90 * time.Second, true}, - {now.Add(-time.Minute).Format(http.TimeFormat), 0, false}, - } - for _, tt := range tests { - got, ok := parseRetryAfter(tt.value, now) - if got != tt.want || ok != tt.ok { - t.Errorf("parseRetryAfter(%q) = (%s, %v), want (%s, %v)", tt.value, got, ok, tt.want, tt.ok) - } - } -} diff --git a/internal/httpclient/shared_holds.go b/internal/httpclient/shared_holds.go new file mode 100644 index 0000000..175931b --- /dev/null +++ b/internal/httpclient/shared_holds.go @@ -0,0 +1,213 @@ +package httpclient + +import ( + "log/slog" + "net/http" + "net/url" + "strings" + "sync" + "time" + + registryclient "github.com/git-pkgs/registries/client" +) + +// DefaultHoldRefresh is how long a SharedRateLimitGate trusts its copy of +// the shared holds before reading them again. It bounds both the database +// reads, at one per interval per instance, and how long another instance +// may keep sending after a hold is placed. +const DefaultHoldRefresh = 2 * time.Second + +// HoldStore keeps rate-limit holds where every instance sharing it sees them. +type HoldStore interface { + PutUpstreamHold(host string, until time.Time) error + UpstreamHolds(now time.Time) (map[string]time.Time, error) +} + +// SharedRateLimitGate adds holds shared with other instances to a +// RateLimitGate. Holds the gate places are published to the store, and +// requests to a host another instance holds are refused like the gate's own, +// with a HeldError. Without a store it behaves as the gate alone. +type SharedRateLimitGate struct { + gate *registryclient.RateLimitGate + store HoldStore + logger *slog.Logger + now func() time.Time + + // Refresh is how long the shared holds read from the store are used + // before reading them again. Set it before use. + Refresh time.Duration + + mu sync.Mutex + shared map[string]time.Time + // published holds the holds this instance wrote, so a read that started + // before a write does not drop it. + published map[string]time.Time + loaded time.Time + loading bool +} + +// NewSharedRateLimitGate wraps gate, publishing its holds to store and +// honouring those in store. It takes over gate.OnHold, calling the callback +// set before. A nil store shares nothing. +func NewSharedRateLimitGate(gate *registryclient.RateLimitGate, store HoldStore, logger *slog.Logger) *SharedRateLimitGate { + s := &SharedRateLimitGate{ + gate: gate, + store: store, + logger: logger, + now: time.Now, + Refresh: DefaultHoldRefresh, + shared: make(map[string]time.Time), + published: make(map[string]time.Time), + } + if store != nil { + onHold := gate.OnHold + gate.OnHold = func(event registryclient.HoldEvent) { + s.publish(event.Host, event.Until) + if onHold != nil { + onHold(event) + } + } + } + return s +} + +// RoundTrip implements http.RoundTripper. +func (s *SharedRateLimitGate) RoundTrip(req *http.Request) (*http.Response, error) { + if err := s.sharedHeld(hostKey(req.URL)); err != nil { + return nil, err + } + return s.gate.RoundTrip(req) +} + +// Held returns a *registryclient.HeldError when requests to rawURL's host are +// held by this instance or another, and nil otherwise. It is safe to call on +// a nil gate. +func (s *SharedRateLimitGate) Held(rawURL string) error { + if s == nil { + return nil + } + if err := s.gate.Held(rawURL); err != nil { + return err + } + u, err := url.Parse(rawURL) + if err != nil { + return nil + } + return s.sharedHeld(hostKey(u)) +} + +// Holds returns the hosts held by this instance or another, and when each +// hold ends. It is safe to call on a nil gate. +func (s *SharedRateLimitGate) Holds() map[string]time.Time { + if s == nil { + return nil + } + holds := s.gate.Holds() + if s.store == nil { + return holds + } + s.load(false) + now := s.now() + s.mu.Lock() + defer s.mu.Unlock() + for host, until := range s.shared { + if now.Before(until) && until.After(holds[host]) { + if holds == nil { + holds = make(map[string]time.Time) + } + holds[host] = until + } + } + return holds +} + +// Reload reads the shared holds now rather than when the copy runs out. A +// caller that knows another instance has just failed, say on a 429, uses it +// to see that instance's hold at once. +func (s *SharedRateLimitGate) Reload() { + if s == nil || s.store == nil { + return + } + s.load(true) +} + +func (s *SharedRateLimitGate) sharedHeld(host string) error { + if s.store == nil { + return nil + } + s.load(false) + now := s.now() + s.mu.Lock() + until, ok := s.shared[host] + s.mu.Unlock() + if !ok || !now.Before(until) { + return nil + } + return ®istryclient.HeldError{Host: host, Until: until, RetryAfter: until.Sub(now)} +} + +// load refreshes the copy of the shared holds once it is older than Refresh, +// or at once when force is set. One caller reads the store while concurrent +// callers go on with the copy they have; a forced read does not wait for +// one already running, which may have started before the hold it is after. +func (s *SharedRateLimitGate) load(force bool) { + now := s.now() + s.mu.Lock() + if !force && (s.loading || now.Sub(s.loaded) < s.Refresh) { + s.mu.Unlock() + return + } + s.loading = true + s.mu.Unlock() + + holds, err := s.store.UpstreamHolds(now) + + s.mu.Lock() + defer s.mu.Unlock() + s.loading = false + // A failed read keeps the last copy and waits a full interval before + // trying again, so a database outage costs no more queries than usual. + s.loaded = now + if err != nil { + if s.logger != nil { + s.logger.Warn("reading shared upstream holds failed", "error", err) + } + if holds == nil { + return + } + } + for host, until := range s.published { + if !now.Before(until) { + delete(s.published, host) + } else if until.After(holds[host]) { + holds[host] = until + } + } + s.shared = holds +} + +// publish records a hold this instance placed, locally and in the store. The +// responses already in flight when a hold starts each report it again; only a +// later end is written. +func (s *SharedRateLimitGate) publish(host string, until time.Time) { + s.mu.Lock() + if !until.After(s.published[host]) { + s.mu.Unlock() + return + } + s.published[host] = until + if until.After(s.shared[host]) { + s.shared[host] = until + } + s.mu.Unlock() + if err := s.store.PutUpstreamHold(host, until); err != nil && s.logger != nil { + s.logger.Warn("publishing upstream hold failed", "host", host, "error", err) + } +} + +func hostKey(u *url.URL) string { + if u == nil { + return "" + } + return strings.ToLower(u.Host) +} diff --git a/internal/httpclient/shared_holds_test.go b/internal/httpclient/shared_holds_test.go new file mode 100644 index 0000000..31b9d79 --- /dev/null +++ b/internal/httpclient/shared_holds_test.go @@ -0,0 +1,125 @@ +package httpclient + +import ( + "errors" + "net/http" + "net/http/httptest" + "sync" + "sync/atomic" + "testing" + "time" + + registryclient "github.com/git-pkgs/registries/client" +) + +// memoryHoldStore is a HoldStore shared by gates in one test, counting reads. +type memoryHoldStore struct { + mu sync.Mutex + holds map[string]time.Time + reads atomic.Int32 +} + +func (m *memoryHoldStore) PutUpstreamHold(host string, until time.Time) error { + m.mu.Lock() + defer m.mu.Unlock() + if until.After(m.holds[host]) { + m.holds[host] = until + } + return nil +} + +func (m *memoryHoldStore) UpstreamHolds(now time.Time) (map[string]time.Time, error) { + m.reads.Add(1) + m.mu.Lock() + defer m.mu.Unlock() + out := make(map[string]time.Time) + for host, until := range m.holds { + if now.Before(until) { + out[host] = until + } + } + return out, nil +} + +func TestSharedRateLimitGateSharesHolds(t *testing.T) { + var calls atomic.Int32 + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + calls.Add(1) + w.Header().Set("Retry-After", "120") + w.WriteHeader(http.StatusTooManyRequests) + })) + defer upstream.Close() + + store := &memoryHoldStore{holds: make(map[string]time.Time)} + a := NewSharedRateLimitGate(registryclient.NewRateLimitGate(upstream.Client().Transport), store, nil) + b := NewSharedRateLimitGate(registryclient.NewRateLimitGate(upstream.Client().Transport), store, nil) + clock := time.Now() + b.now = func() time.Time { return clock } + + // b reads the store before a is rate limited, and keeps that copy for + // Refresh. + if err := b.Held(upstream.URL); err != nil { + t.Fatalf("b held before any 429: %v", err) + } + resp, err := a.RoundTrip(httptest.NewRequest(http.MethodGet, upstream.URL, nil)) + if err != nil || resp.StatusCode != http.StatusTooManyRequests { + t.Fatalf("a: %v, %v; want the 429", resp, err) + } + _ = resp.Body.Close() + if err := b.Held(upstream.URL); err != nil { + t.Errorf("b refreshed before Refresh ran out: %v", err) + } + + clock = clock.Add(DefaultHoldRefresh) + _, err = b.RoundTrip(httptest.NewRequest(http.MethodGet, upstream.URL, nil)) + var held *registryclient.HeldError + if !errors.As(err, &held) || held.RetryAfter <= 100*time.Second { + t.Fatalf("b after refresh: %v, want a hold of about two minutes", err) + } + if calls.Load() != 1 { + t.Errorf("upstream requests = %d, want 1", calls.Load()) + } + if holds := b.Holds(); len(holds) != 1 { + t.Errorf("b.Holds() = %v, want a's hold", holds) + } + // One read by a before its request, two by b: the first and the one + // after Refresh. + if n := store.reads.Load(); n != 3 { + t.Errorf("store reads = %d, want 3", n) + } + + // Once the hold ends, b sends again. + clock = clock.Add(2 * time.Minute) + if err := b.Held(upstream.URL); err != nil { + t.Errorf("b after the hold ended: %v", err) + } +} + +func TestSharedRateLimitGateReload(t *testing.T) { + store := &memoryHoldStore{holds: make(map[string]time.Time)} + g := NewSharedRateLimitGate(registryclient.NewRateLimitGate(nil), store, nil) + g.Refresh = time.Hour + if err := g.Held("https://registry.example/x"); err != nil { + t.Fatal(err) + } + _ = store.PutUpstreamHold("registry.example", time.Now().Add(time.Minute)) + if err := g.Held("https://registry.example/x"); err != nil { + t.Fatalf("held before reload: %v", err) + } + g.Reload() + if !errors.Is(g.Held("https://registry.example/x"), registryclient.ErrUpstreamHeld) { + t.Error("not held after reload") + } +} + +func TestSharedRateLimitGateWithoutStore(t *testing.T) { + g := NewSharedRateLimitGate(registryclient.NewRateLimitGate(nil), nil, nil) + if err := g.Held("https://registry.example/x"); err != nil { + t.Fatal(err) + } + g.Reload() + var nilGate *SharedRateLimitGate + if nilGate.Held("https://registry.example/x") != nil || nilGate.Holds() != nil { + t.Error("nil gate holds") + } +} diff --git a/internal/httpclient/token_scope_test.go b/internal/httpclient/token_scope_test.go index 97d8154..563d939 100644 --- a/internal/httpclient/token_scope_test.go +++ b/internal/httpclient/token_scope_test.go @@ -141,24 +141,92 @@ func TestTransportFollowsAnonymousTokenServiceOnAnotherHost(t *testing.T) { } } -func TestSameSite(t *testing.T) { +// TestTransportDoesNotSendCredentialedTokenToHostWithOtherCredentials checks +// that a registry with credentials of its own, but not the realm's, is not +// handed a token minted from the realm's credentials. +func TestTransportDoesNotSendCredentialedTokenToHostWithOtherCredentials(t *testing.T) { + var issued atomic.Int32 + realm := tokenService(t, &issued) + var received []string + vendor := challengingRegistry(t, realm.URL, &received) + + auth := func(rawURL string) (string, string) { + switch { + case strings.HasPrefix(rawURL, realm.URL): + return "Authorization", "Basic Y29ycDpwYXNz" + case strings.HasPrefix(rawURL, vendor.URL): + return "Authorization", "Basic dmVuZG9yOmtleQ==" + } + return "", "" + } + client := &http.Client{Transport: NewTransport(http.DefaultTransport, auth)} + if status := get(t, client, vendor.URL+"/v2/corp/private/blobs/sha256:abc"); status != http.StatusUnauthorized { + t.Errorf("status = %d, want the challenge passed back as 401", status) + } + for _, got := range received { + if got != "Basic dmVuZG9yOmtleQ==" { + t.Errorf("the vendor registry received Authorization %q, want only its own credentials", got) + } + } + if n := issued.Load(); n != 0 { + t.Errorf("token service was asked %d times on the vendor registry's behalf, want 0", n) + } +} + +// TestTransportRequestsPullScopeForRequestedRepository checks that the token +// is requested for pull access to the repository in the request path, not +// whatever scope the challenge names. +func TestTransportRequestsPullScopeForRequestedRepository(t *testing.T) { + var scopes [][]string + var srv *httptest.Server + srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/token" { + scopes = append(scopes, r.URL.Query()["scope"]) + _, _ = io.WriteString(w, `{"token":"t","expires_in":3600}`) + return + } + if r.Header.Get("Authorization") != "Bearer t" { + w.Header().Set("WWW-Authenticate", `Bearer realm="`+srv.URL+`/token",service="registry.corp",scope="repository:corp/other:pull,push"`) + http.Error(w, "authentication required", http.StatusUnauthorized) + return + } + _, _ = io.WriteString(w, "blob") + })) + t.Cleanup(srv.Close) + + client := &http.Client{Transport: NewTransport(http.DefaultTransport, credentialsFor(srv.URL))} + if status := get(t, client, srv.URL+"/v2/corp/app/manifests/latest"); status != http.StatusOK { + t.Fatalf("status = %d, want 200", status) + } + if len(scopes) != 1 || len(scopes[0]) != 1 || scopes[0][0] != "repository:corp/app:pull" { + t.Errorf("token requested with scopes %q, want [[repository:corp/app:pull]]", scopes) + } +} + +func TestSameTokenService(t *testing.T) { for _, tt := range []struct { registry, realm string want bool }{ - {"https://registry-1.docker.io", "https://auth.docker.io", true}, - {"https://registry.gitlab.com", "https://gitlab.com", true}, - {"https://ghcr.io", "https://ghcr.io", true}, - {"https://registry.corp.example", "https://auth.corp.example:8443", true}, - {"https://evil.example", "https://auth.docker.io", false}, - {"https://docker.io.evil.example", "https://auth.docker.io", false}, - {"https://a.github.io", "https://b.github.io", false}, // public suffix: separate sites - {"http://127.0.0.1:5000", "http://127.0.0.1:5000", true}, - {"http://127.0.0.1:5000", "http://127.0.0.1:5001", false}, - {"http://localhost:5000", "http://localhost:5001", false}, + {"https://registry-1.docker.io", "https://auth.docker.io/token", true}, + {"https://index.docker.io", "https://auth.docker.io/token", true}, + {"https://registry.gitlab.com", "https://gitlab.com/jwt/auth", true}, + {"https://ghcr.io", "https://ghcr.io/token", true}, + {"https://harbor.corp.example", "https://harbor.corp.example/service/token", true}, + {"https://registry.corp.example", "https://auth.corp.example", false}, + {"https://evil.example", "https://auth.docker.io/token", false}, + {"https://docker.io.evil.example", "https://auth.docker.io/token", false}, + {"https://evil.jfrog.io", "https://myco.jfrog.io/artifactory/api/docker/token", false}, + {"https://evil.azurecr.io", "https://myco.azurecr.io/oauth2/token", false}, + {"https://gitlab.com", "https://registry.gitlab.com", false}, + {"http://registry-1.docker.io", "https://auth.docker.io/token", false}, + {"https://registry-1.docker.io", "https://auth.docker.io:8443/token", false}, + {"http://127.0.0.1:5000", "http://127.0.0.1:5000/token", true}, + {"http://127.0.0.1:5000", "http://127.0.0.1:5001/token", false}, + {"http://localhost:5000", "https://localhost:5000/token", false}, } { - if got := sameSite(mustParse(t, tt.registry), mustParse(t, tt.realm)); got != tt.want { - t.Errorf("sameSite(%s, %s) = %v, want %v", tt.registry, tt.realm, got, tt.want) + if got := sameTokenService(mustParse(t, tt.registry), mustParse(t, tt.realm)); got != tt.want { + t.Errorf("sameTokenService(%s, %s) = %v, want %v", tt.registry, tt.realm, got, tt.want) } } } diff --git a/internal/httpclient/transport.go b/internal/httpclient/transport.go index 56c0f48..a007c8d 100644 --- a/internal/httpclient/transport.go +++ b/internal/httpclient/transport.go @@ -13,8 +13,6 @@ import ( "strings" "sync" "time" - - "golang.org/x/net/publicsuffix" ) const ( @@ -24,6 +22,15 @@ const ( shortTokenSkewDivisor = 10 tokenMaxRetries = 3 tokenRetryBaseDelay = 500 * time.Millisecond + + // maxTokenLifetime caps how long a token is reused, whatever lifetime + // the token service claims. + maxTokenLifetime = time.Hour + // maxCachedTokens and maxCachedChallenges bound the token and + // challenge caches, which grow with every repository and registry + // host the proxy pulls from. + maxCachedTokens = 1024 + maxCachedChallenges = 256 ) // AuthFunc returns a configured authentication header for a URL. @@ -37,7 +44,7 @@ type Transport struct { mu sync.Mutex tokens map[string]cachedToken - challenges map[string]bearerChallenge + challenges map[string]bearerChallenge // by registry origin, without scopes } type cachedToken struct { @@ -85,11 +92,15 @@ func (t *Transport) RoundTrip(req *http.Request) (*http.Response, error) { if hasExplicitAuthorization { return resp, nil } - if registryProtectionSpace(req.URL) == "" { + repository := registryRepository(req.URL) + if repository == "" { return resp, nil } challenge, ok := parseBearerChallenge(resp.Header.Values("WWW-Authenticate")) + // Ask only for pull access to the repository being fetched, whatever + // scope the challenge names: the proxy only reads. + challenge.scopes = []string{pullScope(repository)} if !ok || !canReplay(req) || !t.trustedWithToken(req.URL, challenge) { return resp, nil } @@ -115,37 +126,46 @@ func (t *Transport) RoundTrip(req *http.Request) (*http.Response, error) { // from that registry, which can be any host the proxy fetches from, such as // one named in a Composer dist URL or a Helm index. Credentials configured for // the realm would otherwise be turned into a token handed to that host. A -// registry is trusted with such a token when it has configured credentials of -// its own, or is on the same site as the realm, as Docker Hub's -// registry-1.docker.io is with auth.docker.io. A token from a realm with no -// configured credentials is anonymous, and any registry may have it. +// token from a realm with no configured credentials is anonymous, and any +// registry may have it. A credentialed token only goes to the realm's own +// host, to a registry configured with the same credentials as the realm, or +// to a registry in knownTokenServices. func (t *Transport) trustedWithToken(requestURL *url.URL, challenge bearerChallenge) bool { if t.authForURL == nil { return true } - if name, value := t.authForURL(challenge.realm); name == "" || value == "" { + realmName, realmValue := t.authForURL(challenge.realm) + if realmName == "" || realmValue == "" { return true } - if name, value := t.authForURL(requestURL.String()); name != "" && value != "" { + if name, value := t.authForURL(requestURL.String()); name == realmName && value == realmValue { return true } realm, err := url.Parse(challenge.realm) - return err == nil && sameSite(requestURL, realm) + return err == nil && sameTokenService(requestURL, realm) } -// sameSite reports whether two URLs are on the same site: the same registrable -// domain (public suffix plus one label), or, for IP addresses and names -// without one, such as localhost, the same host and port. -func sameSite(a, b *url.URL) bool { - hostA, hostB := strings.ToLower(a.Hostname()), strings.ToLower(b.Hostname()) - if net.ParseIP(hostA) == nil && net.ParseIP(hostB) == nil { - siteA, errA := publicsuffix.EffectiveTLDPlusOne(hostA) - siteB, errB := publicsuffix.EffectiveTLDPlusOne(hostB) - if errA == nil && errB == nil { - return siteA == siteB - } +// knownTokenServices maps registry hosts to the token service host they +// use where the two differ and the registry cannot be configured with the +// token service's credentials under the same upstream.auth key. +var knownTokenServices = map[string]string{ + "registry-1.docker.io": "auth.docker.io", + "index.docker.io": "auth.docker.io", + "registry.gitlab.com": "gitlab.com", +} + +// sameTokenService reports whether a token service at realm belongs to the +// registry at registry: both on the same scheme, host and port, or a known +// pair of registry and token service hosts. +func sameTokenService(registry, realm *url.URL) bool { + if strings.EqualFold(registry.Scheme, realm.Scheme) && strings.EqualFold(registry.Host, realm.Host) { + return true } - return strings.EqualFold(a.Host, b.Host) + if registry.Scheme != "https" || realm.Scheme != "https" || registry.Port() != "" || realm.Port() != "" { + return false + } + want, ok := knownTokenServices[strings.ToLower(registry.Hostname())] + return ok && strings.EqualFold(realm.Hostname(), want) } func (t *Transport) applyAuthentication(req *http.Request, hasExplicitAuthorization bool) { @@ -193,6 +213,17 @@ func (t *Transport) cacheToken(key string, token cachedToken) { delete(t.tokens, cachedKey) } } + if _, ok := t.tokens[key]; !ok && len(t.tokens) >= maxCachedTokens { + // Drop the token that expires soonest. + var oldestKey string + var oldest time.Time + for cachedKey, cached := range t.tokens { + if oldestKey == "" || cached.expiresAt.Before(oldest) { + oldestKey, oldest = cachedKey, cached.expiresAt + } + } + delete(t.tokens, oldestKey) + } t.tokens[key] = token } @@ -272,6 +303,7 @@ func decodeTokenResponse(resp *http.Response) (string, time.Time, error) { if lifetime <= 0 { lifetime = defaultTokenLifetime } + lifetime = min(lifetime, maxTokenLifetime) expiresAt := issuedAt.Add(lifetime).Add(-expirySkew(lifetime)) return token, expiresAt, nil } @@ -334,17 +366,18 @@ func (t configuredTransport) RoundTrip(req *http.Request) (*http.Response, error } func (t *Transport) cachedTokenForRequest(requestURL *url.URL) string { - space := registryProtectionSpace(requestURL) - if space == "" { + repository := registryRepository(requestURL) + if repository == "" { return "" } t.mu.Lock() - challenge, ok := t.challenges[space] + challenge, ok := t.challenges[registryOrigin(requestURL)] t.mu.Unlock() if !ok { return "" } + challenge.scopes = []string{pullScope(repository)} return t.cachedToken(challenge.key()) } @@ -364,21 +397,38 @@ func (t *Transport) cachedToken(key string) string { return token.value } +// rememberChallenge records the token service a registry named, so later +// requests to any of its repositories can send a cached token up front. func (t *Transport) rememberChallenge(requestURL *url.URL, challenge bearerChallenge) { - space := registryProtectionSpace(requestURL) - if space == "" { - return - } + origin := registryOrigin(requestURL) + challenge.scopes = nil t.mu.Lock() - t.challenges[space] = challenge - t.mu.Unlock() + defer t.mu.Unlock() + if _, ok := t.challenges[origin]; !ok && len(t.challenges) >= maxCachedChallenges { + for evict := range t.challenges { + delete(t.challenges, evict) + break + } + } + t.challenges[origin] = challenge } func (c bearerChallenge) key() string { return c.realm + "\x00" + c.service + "\x00" + strings.Join(c.scopes, "\x00") } -func registryProtectionSpace(u *url.URL) string { +func registryOrigin(u *url.URL) string { + return strings.ToLower(u.Scheme + "://" + u.Host) +} + +func pullScope(repository string) string { + return "repository:" + repository + ":pull" +} + +// registryRepository returns the repository name from an OCI distribution +// API path, such as library/alpine from /v2/library/alpine/manifests/latest, +// or "" if the path is not one. +func registryRepository(u *url.URL) string { const registryPrefix = "/v2/" if u == nil || !strings.HasPrefix(u.Path, registryPrefix) { return "" @@ -393,7 +443,7 @@ func registryProtectionSpace(u *url.URL) string { if end == len(rest) || end == 0 { return "" } - return u.Scheme + "://" + u.Host + registryPrefix + rest[:end] + return rest[:end] } func parseBearerChallenge(values []string) (bearerChallenge, bool) { diff --git a/internal/httpclient/transport_test.go b/internal/httpclient/transport_test.go index 01f3e8b..46a31b6 100644 --- a/internal/httpclient/transport_test.go +++ b/internal/httpclient/transport_test.go @@ -3,6 +3,7 @@ package httpclient import ( "context" "errors" + "fmt" "io" "net" "net/http" @@ -412,3 +413,51 @@ func TestTransportDoesNotFollowBearerChallengeOutsideOCIRegistry(t *testing.T) { t.Errorf("token requests = %d, want 0", tokenRequests) } } + +func TestTransportBoundsTokenCache(t *testing.T) { + transport := NewTransport(http.DefaultTransport, nil) + expiry := time.Now().Add(time.Hour) + for i := range maxCachedTokens + 10 { + transport.cacheToken(fmt.Sprintf("key-%d", i), cachedToken{ + value: "token", + expiresAt: expiry.Add(time.Duration(i) * time.Second), + }) + } + if got := len(transport.tokens); got != maxCachedTokens { + t.Errorf("cached tokens = %d, want %d", got, maxCachedTokens) + } + if got := transport.cachedToken(fmt.Sprintf("key-%d", maxCachedTokens+9)); got != "token" { + t.Error("the newest token was evicted") + } + if got := transport.cachedToken("key-0"); got != "" { + t.Error("the token expiring soonest was kept") + } +} + +func TestTransportBoundsChallengeCache(t *testing.T) { + transport := NewTransport(http.DefaultTransport, nil) + challenge := bearerChallenge{realm: "https://auth.example.test/token", service: "registry"} + for i := range 50 { + transport.rememberChallenge(mustParse(t, fmt.Sprintf("https://registry.example.test/v2/repo-%d/blobs/sha256:abc", i)), challenge) + } + if got := len(transport.challenges); got != 1 { + t.Errorf("challenges for one registry host = %d, want 1", got) + } + for i := range maxCachedChallenges + 10 { + transport.rememberChallenge(mustParse(t, fmt.Sprintf("https://registry-%d.example.test/v2/repo/blobs/sha256:abc", i)), challenge) + } + if got := len(transport.challenges); got != maxCachedChallenges { + t.Errorf("challenges = %d, want %d", got, maxCachedChallenges) + } +} + +func TestTransportCapsTokenLifetime(t *testing.T) { + resp := &http.Response{Body: io.NopCloser(strings.NewReader(`{"token":"t","expires_in":31536000}`))} + _, expiresAt, err := decodeTokenResponse(resp) + if err != nil { + t.Fatal(err) + } + if limit := time.Now().Add(maxTokenLifetime); expiresAt.After(limit) { + t.Errorf("token expires at %v, want no later than %v", expiresAt, limit) + } +} diff --git a/internal/inventory/fuzz_test.go b/internal/inventory/fuzz_test.go new file mode 100644 index 0000000..f7fcadd --- /dev/null +++ b/internal/inventory/fuzz_test.go @@ -0,0 +1,28 @@ +package inventory + +import ( + "os" + "testing" +) + +// FuzzParse checks that no uploaded body makes the SBOM parsing panic. +func FuzzParse(f *testing.F) { + if data, err := os.ReadFile("testdata/syft-cyclonedx.json"); err == nil { + f.Add(data) + } + f.Add([]byte(`{"bomFormat":"CycloneDX","specVersion":"1.5","components":[{"type":"library","name":"x","version":"1","purl":"pkg:npm/x@1"}]}`)) + f.Add([]byte(`{"spdxVersion":"SPDX-2.3","SPDXID":"SPDXRef-DOCUMENT","packages":[{"SPDXID":"SPDXRef-a","name":"a","versionInfo":"1","externalRefs":[{"referenceCategory":"PACKAGE-MANAGER","referenceType":"purl","referenceLocator":"pkg:conda/a@1?channel=c"}]}]}`)) + f.Add([]byte("SPDXVersion: SPDX-2.3\nPackageName: a\nSPDXID: SPDXRef-a\nExternalRef: PACKAGE-MANAGER purl pkg:deb/debian/a@1\n")) + f.Add([]byte(`xpkg:pypi/X_Y@1`)) + f.Fuzz(func(t *testing.T, data []byte) { + components, _, err := Parse(data) + if err != nil { + return + } + for _, c := range components { + if c.PackagePURL == "" || c.Version == "" || c.Ecosystem == "" { + t.Errorf("component with an empty field: %+v", c) + } + } + }) +} diff --git a/internal/inventory/inventory.go b/internal/inventory/inventory.go new file mode 100644 index 0000000..c48f387 --- /dev/null +++ b/internal/inventory/inventory.go @@ -0,0 +1,190 @@ +// Package inventory turns SBOMs uploaded for a project into the package +// versions the proxy records for it, named the way the proxy's handlers name +// the packages they cache, so the two can be joined. +package inventory + +import ( + "errors" + "fmt" + "strings" + + "github.com/git-pkgs/proxy/internal/packageurl" + "github.com/git-pkgs/purl" + "github.com/git-pkgs/sbom" + "github.com/git-pkgs/vers" +) + +// MaxProjectNameLength bounds a project name, such as a GitLab project path. +const MaxProjectNameLength = 255 + +// Component is one package version a project uses. +type Component struct { + // Ecosystem is the name the proxy's handlers store the package under, + // e.g. "npm", "composer", "golang" or "alpine". + Ecosystem string + // Name is the ecosystem-native package name, e.g. "@babel/core", + // "symfony/console" or "org.slf4j:slf4j-api". + Name string + // Version is the version as the SBOM gives it; it may be empty. + Version string + // PackagePURL is the unversioned package URL the proxy records the + // package under, so it matches packages.purl. + PackagePURL string +} + +// servedTypes are the PURL types the proxy serves packages of and the +// inventory records. +var servedTypes = map[string]bool{ + "alpm": true, "apk": true, "bsd": true, "cargo": true, "chef": true, + "composer": true, "conan": true, "conda": true, "cran": true, "deb": true, + "gem": true, "golang": true, "hex": true, "julia": true, "maven": true, + "npm": true, "nuget": true, "pub": true, "pypi": true, "rpm": true, + "swift": true, +} + +// ErrUnsupportedPURL is returned for a package URL whose type the proxy +// doesn't serve. +var ErrUnsupportedPURL = errors.New("package type is not served by the proxy") + +// ErrNoCondaChannel is returned for a conda package URL without a channel +// qualifier: the proxy records conda packages per channel. +var ErrNoCondaChannel = errors.New("conda package URL has no channel qualifier") + +// FromPURL maps a package URL to a component, with the package named the way +// the handler for its type records it. Qualifiers and subpath are dropped; +// the version is kept as given. +func FromPURL(s string) (Component, error) { + p, err := purl.Parse(s) + if err != nil { + return Component{}, err + } + if !servedTypes[p.Type] { + return Component{}, fmt.Errorf("%w: %s", ErrUnsupportedPURL, p.Type) + } + ecosystem, name := packageurl.HandlerPackage(p) + if ecosystem == "conda" && !strings.Contains(name, "/") { + return Component{}, ErrNoCondaChannel + } + packagePURL, _ := packageurl.MakeCacheStrings(ecosystem, name, "") + if packagePURL == "" { + return Component{}, fmt.Errorf("package URL %q has no valid package name", s) + } + return Component{Ecosystem: ecosystem, Name: name, Version: p.Version, PackagePURL: packagePURL}, nil +} + +// syftMainModule is the property syft sets on modules found in a Go binary, +// naming the module the binary was built from. +const syftMainModule = "syft:metadata:mainModule" + +// unknownVersion is what syft gives a package without a resolved version, +// such as the project's own module in go.mod or the root of a lock file. +const unknownVersion = "UNKNOWN" + +// Parse reads a CycloneDX (JSON or XML) or SPDX SBOM and returns the package +// versions it lists, without duplicates. Packages without a package URL, of a +// type the proxy doesn't serve, without a version, or conda packages without +// a channel are counted in skipped. +// So are the project's own packages: Go modules its binaries were built from, +// and the roots sbom finds for the dependency graph. +func Parse(data []byte) (components []Component, skipped int, err error) { + doc, err := sbom.Parse(data) + if err != nil { + return nil, 0, err + } + ownModules := mainModules(doc.Packages) + roots := map[string]bool{} + for _, id := range doc.ProjectRoots() { + roots[id] = true + } + seen := make(map[[2]string]bool, len(doc.Packages)) + for _, pkg := range doc.Packages { + c, ok := componentOf(pkg) + if !ok || roots[pkg.ID] || (c.Ecosystem == "golang" && ownModules[c.Name]) { + skipped++ + continue + } + key := [2]string{c.PackagePURL, c.Version} + if seen[key] { + continue + } + seen[key] = true + components = append(components, c) + } + return components, skipped, nil +} + +func componentOf(pkg sbom.Package) (Component, bool) { + locator := pkg.PURL() + if locator == "" { + return Component{}, false + } + c, err := FromPURL(locator) + if err != nil { + return Component{}, false + } + if c.Version == "" { + c.Version = pkg.Version + } + // A package without a version is the project itself (the module in + // go.mod, the root of package-lock.json), not something it depends on. + if c.Version == "" || c.Version == unknownVersion { + return Component{}, false + } + return c, true +} + +// mainModules returns the Go modules the SBOM's binaries were built from, +// which are the project's own. Module paths are case-sensitive and package +// URLs keep their case, so they are compared as they are. +func mainModules(pkgs []sbom.Package) map[string]bool { + own := map[string]bool{} + for _, pkg := range pkgs { + for _, prop := range pkg.Properties { + if prop.Name == syftMainModule && prop.Value != "" { + own[prop.Value] = true + } + } + } + return own +} + +// ValidateProjectName checks a project name such as "group/sub/repo": one or +// more segments of letters, digits, ".", "_" and "-", none of them "." or +// "..". +func ValidateProjectName(name string) error { + if name == "" { + return errors.New("project name is empty") + } + if len(name) > MaxProjectNameLength { + return fmt.Errorf("project name is longer than %d characters", MaxProjectNameLength) + } + for segment := range strings.SplitSeq(name, "/") { + if segment == "" || segment == "." || segment == ".." { + return fmt.Errorf("project name %q has an empty, \".\" or \"..\" segment", name) + } + for _, r := range segment { + if !validNameRune(r) { + return fmt.Errorf("project name %q may only contain letters, digits, '.', '_', '-' and '/'", name) + } + } + } + return nil +} + +func validNameRune(r rune) bool { + return r >= 'a' && r <= 'z' || r >= 'A' && r <= 'Z' || r >= '0' && r <= '9' || r == '.' || r == '_' || r == '-' +} + +// CompareVersions compares two versions of a package in ecosystem with the +// ecosystem's version rules, returning -1, 0 or 1. +func CompareVersions(ecosystem, a, b string) int { + return vers.CompareWithScheme(a, b, purl.EcosystemToPURLType(ecosystem)) +} + +// Outdated reports whether version is lower than latest. +func Outdated(ecosystem, version, latest string) bool { + if version == "" || latest == "" || version == latest { + return false + } + return CompareVersions(ecosystem, version, latest) < 0 +} diff --git a/internal/inventory/inventory_test.go b/internal/inventory/inventory_test.go new file mode 100644 index 0000000..89b070b --- /dev/null +++ b/internal/inventory/inventory_test.go @@ -0,0 +1,337 @@ +package inventory + +import ( + "errors" + "os" + "slices" + "strings" + "testing" + + "github.com/git-pkgs/proxy/internal/packageurl" +) + +func TestParseSyftCycloneDX(t *testing.T) { + data, err := os.ReadFile("testdata/syft-cyclonedx.json") + if err != nil { + t.Fatal(err) + } + components, skipped, err := Parse(data) + if err != nil { + t.Fatalf("Parse: %v", err) + } + want := []Component{ + {Ecosystem: "npm", Name: "@babel/core", Version: "7.23.0", PackagePURL: "pkg:npm/%40babel/core"}, + {Ecosystem: "alpine", Name: "busybox", Version: "1.36.1-r15", PackagePURL: "pkg:apk/alpine/busybox"}, + {Ecosystem: "golang", Name: "github.com/inconshreveable/mousetrap", Version: "v1.1.0", PackagePURL: "pkg:golang/github.com/inconshreveable/mousetrap"}, + {Ecosystem: "golang", Name: "github.com/spf13/cobra", Version: "v1.8.0", PackagePURL: "pkg:golang/github.com/spf13/cobra"}, + {Ecosystem: "golang", Name: "github.com/spf13/pflag", Version: "v1.0.5", PackagePURL: "pkg:golang/github.com/spf13/pflag"}, + {Ecosystem: "npm", Name: "lodash", Version: "4.17.20", PackagePURL: "pkg:npm/lodash"}, + {Ecosystem: "composer", Name: "monolog/monolog", Version: "3.5.0", PackagePURL: "pkg:composer/monolog/monolog"}, + {Ecosystem: "alpine", Name: "musl", Version: "1.2.4-r2", PackagePURL: "pkg:apk/alpine/musl"}, + {Ecosystem: "composer", Name: "symfony/console", Version: "v6.4.1", PackagePURL: "pkg:composer/symfony/console"}, + } + if !slices.Equal(components, want) { + t.Errorf("components =\n%v\nwant\n%v", components, want) + } + // The operating system and the four lock files syft lists carry no PURL, + // and webapp is the root of package-lock.json, the project itself. + if skipped != 6 { + t.Errorf("skipped = %d, want 6", skipped) + } +} + +func TestParseDeduplicatesAndSkipsUnknownTypes(t *testing.T) { + doc := `{"bomFormat":"CycloneDX","specVersion":"1.5","components":[ + {"type":"library","name":"lodash","version":"4.17.21","purl":"pkg:npm/lodash@4.17.21"}, + {"type":"library","name":"lodash","version":"4.17.21","purl":"pkg:npm/lodash@4.17.21"}, + {"type":"library","name":"lodash","version":"4.17.20","purl":"pkg:npm/lodash@4.17.20"}, + {"type":"library","name":"checkout","version":"v4","purl":"pkg:github/actions/checkout@v4"}, + {"type":"library","name":"Django","version":"4.2.0","purl":"pkg:pypi/Django"}, + {"type":"library","name":"guava","version":"32.1.3-jre","purl":"pkg:maven/com.google.guava/guava@32.1.3-jre?type=jar"}, + {"type":"library","name":"libc6","version":"2.36-9","purl":"pkg:deb/debian/libc6@2.36-9?arch=amd64&distro=debian-12"}, + {"type":"library","name":"broken","purl":"not a purl"} + ]}` + components, skipped, err := Parse([]byte(doc)) + if err != nil { + t.Fatal(err) + } + want := []Component{ + {Ecosystem: "npm", Name: "lodash", Version: "4.17.21", PackagePURL: "pkg:npm/lodash"}, + {Ecosystem: "npm", Name: "lodash", Version: "4.17.20", PackagePURL: "pkg:npm/lodash"}, + {Ecosystem: "pypi", Name: "django", Version: "4.2.0", PackagePURL: "pkg:pypi/django"}, + {Ecosystem: "maven", Name: "com.google.guava:guava", Version: "32.1.3-jre", PackagePURL: "pkg:maven/com.google.guava/guava"}, + {Ecosystem: "deb", Name: "libc6", Version: "2.36-9", PackagePURL: "pkg:deb/libc6"}, + } + if !slices.Equal(components, want) { + t.Errorf("components =\n%v\nwant\n%v", components, want) + } + if skipped != 2 { + t.Errorf("skipped = %d, want 2", skipped) + } +} + +func TestParseRejectsNonSBOM(t *testing.T) { + if _, _, err := Parse([]byte(`{"hello":"world"}`)); err == nil { + t.Error("Parse accepted a document that is not an SBOM") + } +} + +func TestFromPURLUnsupported(t *testing.T) { + _, err := FromPURL("pkg:github/actions/checkout") + if !errors.Is(err, ErrUnsupportedPURL) { + t.Errorf("err = %v, want ErrUnsupportedPURL", err) + } +} + +// TestFromPURLMatchesHandlerNames checks, for every PURL type the inventory +// maps, that an SBOM's package URL ends up as the package URL the handler +// records when it caches that package. handlerName is the name the handler +// passes to GetOrFetchArtifactFromURL, taken from the handler's code. +func TestFromPURLMatchesHandlerNames(t *testing.T) { + tests := []struct { + purlType string + sbomPURL string + handlerName string + }{ + {"alpm", "pkg:alpm/arch/glibc@2.39-1?arch=x86_64", "glibc"}, + {"apk", "pkg:apk/alpine/busybox@1.36.1-r15?arch=x86_64", "busybox"}, + {"bsd", "pkg:bsd/freebsd/curl@8.7.1", "curl"}, + {"cargo", "pkg:cargo/serde@1.0.200", "serde"}, + {"chef", "pkg:chef/nginx@12.0.0", "nginx"}, + {"composer", "pkg:composer/symfony/console@v6.4.1", "symfony/console"}, + {"conan", "pkg:conan/zlib@1.3.1", "zlib"}, + {"conda", "pkg:conda/numpy@1.26.4?channel=conda-forge&subdir=linux-64", "conda-forge/numpy"}, + {"cran", "pkg:cran/ggplot2@3.5.1", "ggplot2"}, + {"deb", "pkg:deb/debian/libc6@2.36-9?arch=amd64&distro=debian-12", "libc6"}, + {"gem", "pkg:gem/rails@7.1.3", "rails"}, + // The go handler stores the module path with its case; PURLs of + // golang modules are lowercased on both sides. + {"golang", "pkg:golang/github.com/Azure/azure-sdk-for-go@v68.0.0", "github.com/Azure/azure-sdk-for-go"}, + {"hex", "pkg:hex/phoenix@1.7.12", "phoenix"}, + {"julia", "pkg:julia/Example@0.5.3?uuid=7876af07-990d-54b4-ab0e-23690620f79a", "Example"}, + {"maven", "pkg:maven/org.slf4j/slf4j-api@2.0.13?type=jar", "org.slf4j:slf4j-api"}, + {"npm", "pkg:npm/%40babel/core@7.23.0", "@babel/core"}, + // The NuGet handler lowercases the package ID. + {"nuget", "pkg:nuget/Newtonsoft.Json@13.0.3", "newtonsoft.json"}, + {"pub", "pkg:pub/http@1.2.1", "http"}, + // The PyPI handler takes the name from the wheel or sdist file name, + // which spells "." and "-" as "_". + {"pypi", "pkg:pypi/zope.interface@6.4", "zope_interface"}, + {"rpm", "pkg:rpm/fedora/curl@8.6.0-7.fc40?arch=x86_64", "curl"}, + {"swift", "pkg:swift/github.com/apple/swift-argument-parser@1.3.1", "github.com/apple/swift-argument-parser"}, + } + covered := map[string]bool{} + for _, tt := range tests { + t.Run(tt.purlType, func(t *testing.T) { + covered[tt.purlType] = true + c, err := FromPURL(tt.sbomPURL) + if err != nil { + t.Fatalf("FromPURL(%q): %v", tt.sbomPURL, err) + } + want, _ := packageurl.MakeCacheStrings(packageurl.HandlerEcosystem(tt.purlType), tt.handlerName, "") + if want == "" { + t.Fatalf("handler name %q has no package URL", tt.handlerName) + } + if c.PackagePURL != want { + t.Errorf("PackagePURL = %q, want %q as the handler records it", c.PackagePURL, want) + } + }) + } + for purlType := range servedTypes { + if !covered[purlType] { + t.Errorf("no case for PURL type %q", purlType) + } + } +} + +func TestFromPURLNormalizesPyPINames(t *testing.T) { + for _, s := range []string{"pkg:pypi/zope.interface", "pkg:pypi/Zope_Interface", "pkg:pypi/zope--interface", "pkg:pypi/zope._-interface"} { + c, err := FromPURL(s) + if err != nil { + t.Fatal(err) + } + if c.Name != "zope-interface" || c.PackagePURL != "pkg:pypi/zope-interface" { + t.Errorf("FromPURL(%q) = %+v, want zope-interface", s, c) + } + } +} + +func TestFromPURLCondaNeedsChannel(t *testing.T) { + if _, err := FromPURL("pkg:conda/numpy@1.26.4"); !errors.Is(err, ErrNoCondaChannel) { + t.Errorf("err = %v, want ErrNoCondaChannel", err) + } + doc := `{"bomFormat":"CycloneDX","specVersion":"1.5","components":[ + {"type":"library","name":"numpy","version":"1.26.4","purl":"pkg:conda/numpy@1.26.4"}, + {"type":"library","name":"numpy","version":"1.26.4","purl":"pkg:conda/numpy@1.26.4?channel=conda-forge"} + ]}` + components, skipped, err := Parse([]byte(doc)) + if err != nil { + t.Fatal(err) + } + if len(components) != 1 || components[0].Name != "conda-forge/numpy" || skipped != 1 { + t.Errorf("components = %+v, skipped = %d; want conda-forge/numpy and 1 skipped", components, skipped) + } +} + +func TestValidateProjectName(t *testing.T) { + valid := []string{"repo", "group/repo", "group/sub/my_repo-2.0", strings.Repeat("a", MaxProjectNameLength)} + for _, name := range valid { + if err := ValidateProjectName(name); err != nil { + t.Errorf("ValidateProjectName(%q) = %v, want nil", name, err) + } + } + invalid := []string{ + "", "/repo", "repo/", "group//repo", ".", "..", "group/../repo", "group/./repo", + "group/re po", "group/repo?x", "group\\repo", "grüppe/repo", "group/repo%2F", + strings.Repeat("a", MaxProjectNameLength+1), + } + for _, name := range invalid { + if err := ValidateProjectName(name); err == nil { + t.Errorf("ValidateProjectName(%q) = nil, want an error", name) + } + } +} + +func TestOutdated(t *testing.T) { + tests := []struct { + name string + ecosystem string + version string + other string + outdated bool + }{ + {"npm older", "npm", "4.17.20", "4.17.21", true}, + {"npm same", "npm", "4.17.21", "4.17.21", false}, + {"npm newer", "npm", "4.18.0", "4.17.21", false}, + {"composer v prefix", "composer", "v6.4.1", "v6.4.2", true}, + {"golang", "golang", "v1.8.0", "v1.10.0", true}, + {"alpine revisions", "alpine", "1.36.1-r15", "1.36.1-r2", false}, + {"empty version", "npm", "", "1.0.0", false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := Outdated(tt.ecosystem, tt.version, tt.other); got != tt.outdated { + t.Errorf("Outdated = %v, want %v", got, tt.outdated) + } + }) + } +} + +func TestParseSkipsTheProjectsOwnPackages(t *testing.T) { + doc := `{"bomFormat":"CycloneDX","specVersion":"1.6","components":[ + {"bom-ref":"mod","type":"library","name":"github.com/acme/app","version":"UNKNOWN","purl":"pkg:golang/github.com/acme/app"}, + {"bom-ref":"bin","type":"library","name":"github.com/acme/app","version":"v0.0.0-20261027162038-a3e9dd9fd3f4+dirty","purl":"pkg:golang/github.com/acme/app@v0.0.0-20261027162038-a3e9dd9fd3f4%2Bdirty", + "properties":[{"name":"syft:metadata:mainModule","value":"github.com/acme/app"}]}, + {"bom-ref":"cobra","type":"library","name":"github.com/spf13/cobra","version":"v1.8.0","purl":"pkg:golang/github.com/spf13/cobra@v1.8.0", + "properties":[{"name":"syft:metadata:mainModule","value":"github.com/acme/app"}]}, + {"bom-ref":"root","type":"library","name":"app-frontend","version":"2.1.0","purl":"pkg:npm/app-frontend@2.1.0", + "properties":[{"name":"syft:package:metadataType","value":"javascript-npm-package-lock-entry"},{"name":"syft:location:0:path","value":"/package-lock.json"}]}, + {"bom-ref":"nover","type":"library","name":"app-tools","purl":"pkg:npm/app-tools"}, + {"bom-ref":"jsdom","type":"library","name":"jsdom","version":"30.1.3","purl":"pkg:npm/jsdom@30.1.3", + "properties":[{"name":"syft:package:metadataType","value":"javascript-npm-package-lock-entry"},{"name":"syft:location:0:path","value":"/package-lock.json"}]} + ],"dependencies":[{"ref":"root","dependsOn":["jsdom"]}]}` + components, skipped, err := Parse([]byte(doc)) + if err != nil { + t.Fatal(err) + } + want := []Component{ + {Ecosystem: "golang", Name: "github.com/spf13/cobra", Version: "v1.8.0", PackagePURL: "pkg:golang/github.com/spf13/cobra"}, + {Ecosystem: "npm", Name: "jsdom", Version: "30.1.3", PackagePURL: "pkg:npm/jsdom"}, + } + if !slices.Equal(components, want) { + t.Errorf("components =\n%v\nwant\n%v", components, want) + } + if skipped != 4 { + t.Errorf("skipped = %d, want 4", skipped) + } +} + +func TestParseKeepsTopLevelDependenciesOfLockFiles(t *testing.T) { + // A poetry.lock doesn't list the project, so requests is a direct + // dependency, not the project's own entry. + doc := `{"bomFormat":"CycloneDX","specVersion":"1.6","components":[ + {"bom-ref":"requests","type":"library","name":"requests","version":"2.32.3","purl":"pkg:pypi/requests@2.32.3", + "properties":[{"name":"syft:package:metadataType","value":"python-poetry-lock-entry"},{"name":"syft:location:0:path","value":"/poetry.lock"}]}, + {"bom-ref":"urllib3","type":"library","name":"urllib3","version":"2.2.3","purl":"pkg:pypi/urllib3@2.2.3", + "properties":[{"name":"syft:package:metadataType","value":"python-poetry-lock-entry"},{"name":"syft:location:0:path","value":"/poetry.lock"}]} + ],"dependencies":[{"ref":"requests","dependsOn":["urllib3"]}]}` + components, skipped, err := Parse([]byte(doc)) + if err != nil { + t.Fatal(err) + } + if len(components) != 2 || skipped != 0 { + t.Errorf("components = %+v, skipped = %d; want requests and urllib3, 0 skipped", components, skipped) + } +} + +func TestParseKeepsOSPackagesNothingDependsOn(t *testing.T) { + // syft's CycloneDX of an image: metadata.component is the image, with + // no edges, and busybox is something nothing else depends on. + doc := `{"bomFormat":"CycloneDX","specVersion":"1.6", + "metadata":{"component":{"bom-ref":"image","type":"container","name":"alpine:3.20"}}, + "components":[ + {"bom-ref":"busybox","type":"library","name":"busybox","version":"1.36.1-r29","purl":"pkg:apk/alpine/busybox@1.36.1-r29?distro=alpine-3.20.3", + "properties":[{"name":"syft:package:metadataType","value":"apk-db-entry"}]}, + {"bom-ref":"musl","type":"library","name":"musl","version":"1.2.5-r0","purl":"pkg:apk/alpine/musl@1.2.5-r0?distro=alpine-3.20.3", + "properties":[{"name":"syft:package:metadataType","value":"apk-db-entry"}]} + ],"dependencies":[{"ref":"busybox","dependsOn":["musl"]}]}` + components, skipped, err := Parse([]byte(doc)) + if err != nil { + t.Fatal(err) + } + if len(components) != 2 || skipped != 0 { + t.Errorf("components = %+v, skipped = %d; want busybox and musl, 0 skipped", components, skipped) + } +} + +func TestParseSkipsTheDeclaredRoot(t *testing.T) { + doc := `{"bomFormat":"CycloneDX","specVersion":"1.6", + "metadata":{"component":{"bom-ref":"app","type":"application","name":"app","version":"1.0.0","purl":"pkg:npm/app@1.0.0"}}, + "components":[ + {"bom-ref":"lodash","type":"library","name":"lodash","version":"4.17.21","purl":"pkg:npm/lodash@4.17.21"} + ],"dependencies":[{"ref":"app","dependsOn":["lodash"]}]}` + components, _, err := Parse([]byte(doc)) + if err != nil { + t.Fatal(err) + } + if len(components) != 1 || components[0].Name != "lodash" { + t.Errorf("components = %+v, want only lodash", components) + } +} + +func TestParseSkipsMixedCaseMainModule(t *testing.T) { + // syft keeps the module path's case in mainModule, and so does the + // package URL. + doc := `{"bomFormat":"CycloneDX","specVersion":"1.6","components":[ + {"bom-ref":"bin","type":"library","name":"github.com/Azure/foo","version":"v1.2.0","purl":"pkg:golang/github.com/Azure/foo@v1.2.0", + "properties":[{"name":"syft:metadata:mainModule","value":"github.com/Azure/foo"}]}, + {"bom-ref":"cobra","type":"library","name":"github.com/spf13/cobra","version":"v1.8.0","purl":"pkg:golang/github.com/spf13/cobra@v1.8.0", + "properties":[{"name":"syft:metadata:mainModule","value":"github.com/Azure/foo"}]} + ]}` + components, skipped, err := Parse([]byte(doc)) + if err != nil { + t.Fatal(err) + } + if len(components) != 1 || components[0].Name != "github.com/spf13/cobra" || skipped != 1 { + t.Errorf("components = %+v, skipped = %d; want only cobra, 1 skipped", components, skipped) + } +} + +func TestParseMainModuleKeepsCase(t *testing.T) { + // Go module paths are case-sensitive, and package URLs keep their case, + // so github.com/azure/foo is another module than the main module + // github.com/Azure/foo, and a dependency. + doc := `{"bomFormat":"CycloneDX","specVersion":"1.6","components":[ + {"bom-ref":"bin","type":"library","name":"github.com/Azure/foo","version":"v1.2.0","purl":"pkg:golang/github.com/Azure/foo@v1.2.0", + "properties":[{"name":"syft:metadata:mainModule","value":"github.com/Azure/foo"}]}, + {"bom-ref":"other","type":"library","name":"github.com/azure/foo","version":"v0.1.0","purl":"pkg:golang/github.com/azure/foo@v0.1.0", + "properties":[{"name":"syft:metadata:mainModule","value":"github.com/Azure/foo"}]} + ]}` + components, skipped, err := Parse([]byte(doc)) + if err != nil { + t.Fatal(err) + } + if len(components) != 1 || components[0].Name != "github.com/azure/foo" || skipped != 1 { + t.Errorf("components = %+v, skipped = %d; want only github.com/azure/foo, 1 skipped", components, skipped) + } +} diff --git a/internal/inventory/testdata/syft-cyclonedx.json b/internal/inventory/testdata/syft-cyclonedx.json new file mode 100644 index 0000000..7647d68 --- /dev/null +++ b/internal/inventory/testdata/syft-cyclonedx.json @@ -0,0 +1 @@ +{"$schema":"http://cyclonedx.org/schema/bom-1.7.schema.json","bomFormat":"CycloneDX","specVersion":"1.7","serialNumber":"urn:uuid:d69cf664-a43e-4d65-93e3-e43e24d33c0e","version":1,"metadata":{"timestamp":"2026-10-27T19:17:53+01:00","tools":{"components":[{"type":"application","author":"anchore","name":"syft","version":"1.55.0"}]},"component":{"bom-ref":"af63bd4c8601b7f1","type":"file","name":"."}},"components":[{"bom-ref":"pkg:npm/%40babel/core@7.23.0?package-id=7b01fd7a9ce63128","type":"library","name":"@babel/core","version":"7.23.0","licenses":[{"license":{"id":"MIT"}}],"cpe":"cpe:2.3:a:\\@babel\\/core:\\@babel\\/core:7.23.0:*:*:*:*:*:*:*","purl":"pkg:npm/%40babel/core@7.23.0","properties":[{"name":"syft:package:foundBy","value":"javascript-lock-cataloger"},{"name":"syft:package:language","value":"javascript"},{"name":"syft:package:type","value":"npm"},{"name":"syft:package:metadataType","value":"javascript-npm-package-lock-entry"},{"name":"syft:location:0:path","value":"/package-lock.json"}]},{"bom-ref":"pkg:apk/alpine/busybox@1.36.1-r15?arch=x86_64&distro=alpine-3.19.1&package-id=464f552f6c89c192","type":"library","publisher":"Sören Tempel ","name":"busybox","version":"1.36.1-r15","description":"Size optimized toolbox of many common UNIX utilities","licenses":[{"license":{"id":"GPL-2.0-only"}}],"cpe":"cpe:2.3:a:busybox:busybox:1.36.1-r15:*:*:*:*:*:*:*","purl":"pkg:apk/alpine/busybox@1.36.1-r15?arch=x86_64&distro=alpine-3.19.1","externalReferences":[{"url":"https://busybox.net/","type":"distribution"}],"properties":[{"name":"syft:package:foundBy","value":"apk-db-cataloger"},{"name":"syft:package:type","value":"apk"},{"name":"syft:package:metadataType","value":"apk-db-entry"},{"name":"syft:location:0:path","value":"/lib/apk/db/installed"},{"name":"syft:metadata:gitCommitOfApkPort","value":"1b0b2f6e7d0e6a5b4c3d2e1f0a9b8c7d6e5f4a3b"},{"name":"syft:metadata:installedSize","value":"950272"},{"name":"syft:metadata:originPackage","value":"busybox"},{"name":"syft:metadata:pullChecksum","value":"Q1Xy0qB0j7Y7uQ2kGmWbN8vT6Ff0A4E="},{"name":"syft:metadata:pullDependencies:0","value":"so:libc.musl-x86_64.so.1"},{"name":"syft:metadata:size","value":"509268"}]},{"bom-ref":"pkg:golang/github.com/inconshreveable/mousetrap@v1.1.0?package-id=f6300927a9f6b106","type":"library","name":"github.com/inconshreveable/mousetrap","version":"v1.1.0","cpe":"cpe:2.3:a:inconshreveable:mousetrap:v1.1.0:*:*:*:*:*:*:*","purl":"pkg:golang/github.com/inconshreveable/mousetrap@v1.1.0","properties":[{"name":"syft:package:foundBy","value":"go-module-file-cataloger"},{"name":"syft:package:language","value":"go"},{"name":"syft:package:type","value":"go-module"},{"name":"syft:package:metadataType","value":"go-module-entry"},{"name":"syft:location:0:path","value":"/go.mod"},{"name":"syft:metadata:h1Digest","value":"h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8="}]},{"bom-ref":"pkg:golang/github.com/spf13/cobra@v1.8.0?package-id=81b06fbcbe87f414","type":"library","name":"github.com/spf13/cobra","version":"v1.8.0","cpe":"cpe:2.3:a:spf13:cobra:v1.8.0:*:*:*:*:*:*:*","purl":"pkg:golang/github.com/spf13/cobra@v1.8.0","properties":[{"name":"syft:package:foundBy","value":"go-module-file-cataloger"},{"name":"syft:package:language","value":"go"},{"name":"syft:package:type","value":"go-module"},{"name":"syft:package:metadataType","value":"go-module-entry"},{"name":"syft:location:0:path","value":"/go.mod"},{"name":"syft:metadata:h1Digest","value":"h1:7aJaZx1B85qltLMc546zn58BxxfZdR/W22ej9CFoEf0="}]},{"bom-ref":"pkg:golang/github.com/spf13/pflag@v1.0.5?package-id=163f67459b76e534","type":"library","name":"github.com/spf13/pflag","version":"v1.0.5","cpe":"cpe:2.3:a:spf13:pflag:v1.0.5:*:*:*:*:*:*:*","purl":"pkg:golang/github.com/spf13/pflag@v1.0.5","properties":[{"name":"syft:package:foundBy","value":"go-module-file-cataloger"},{"name":"syft:package:language","value":"go"},{"name":"syft:package:type","value":"go-module"},{"name":"syft:package:metadataType","value":"go-module-entry"},{"name":"syft:location:0:path","value":"/go.mod"},{"name":"syft:metadata:h1Digest","value":"h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRPuqXzS0rkr6qZw="}]},{"bom-ref":"pkg:npm/lodash@4.17.20?package-id=ece3658907628a6b","type":"library","name":"lodash","version":"4.17.20","licenses":[{"license":{"id":"MIT"}}],"cpe":"cpe:2.3:a:lodash:lodash:4.17.20:*:*:*:*:node.js:*:*","purl":"pkg:npm/lodash@4.17.20","properties":[{"name":"syft:package:foundBy","value":"javascript-lock-cataloger"},{"name":"syft:package:language","value":"javascript"},{"name":"syft:package:type","value":"npm"},{"name":"syft:package:metadataType","value":"javascript-npm-package-lock-entry"},{"name":"syft:location:0:path","value":"/package-lock.json"}]},{"bom-ref":"pkg:composer/monolog/monolog@3.5.0?package-id=3abfdcdd00fd8d2f","type":"library","name":"monolog/monolog","version":"3.5.0","licenses":[{"license":{"id":"MIT"}}],"cpe":"cpe:2.3:a:monolog\\/monolog:monolog\\/monolog:3.5.0:*:*:*:*:*:*:*","purl":"pkg:composer/monolog/monolog@3.5.0","properties":[{"name":"syft:package:foundBy","value":"php-composer-lock-cataloger"},{"name":"syft:package:language","value":"php"},{"name":"syft:package:type","value":"php-composer"},{"name":"syft:package:metadataType","value":"php-composer-lock-entry"},{"name":"syft:location:0:path","value":"/composer.lock"}]},{"bom-ref":"pkg:apk/alpine/musl@1.2.4-r2?arch=x86_64&distro=alpine-3.19.1&package-id=9f0e3d80c35c10bc","type":"library","publisher":"Timo Teräs ","name":"musl","version":"1.2.4-r2","description":"the musl c library (libc) implementation","licenses":[{"license":{"id":"MIT"}}],"cpe":"cpe:2.3:a:musl-libc:musl:1.2.4-r2:*:*:*:*:*:*:*","purl":"pkg:apk/alpine/musl@1.2.4-r2?arch=x86_64&distro=alpine-3.19.1","externalReferences":[{"url":"https://musl.libc.org/","type":"distribution"}],"properties":[{"name":"syft:package:foundBy","value":"apk-db-cataloger"},{"name":"syft:package:type","value":"apk"},{"name":"syft:package:metadataType","value":"apk-db-entry"},{"name":"syft:cpe23","value":"cpe:2.3:a:musl_libc:musl:1.2.4-r2:*:*:*:*:*:*:*"},{"name":"syft:cpe23","value":"cpe:2.3:a:musl:musl:1.2.4-r2:*:*:*:*:*:*:*"},{"name":"syft:location:0:path","value":"/lib/apk/db/installed"},{"name":"syft:metadata:gitCommitOfApkPort","value":"4b2f0d7b4e0e8a4b0e1b1b4d2b8a7a3d1a2f8e0c"},{"name":"syft:metadata:installedSize","value":"647168"},{"name":"syft:metadata:originPackage","value":"musl"},{"name":"syft:metadata:pullChecksum","value":"Q1N9CgYbNRm8SgkqbXqJhCAc6iqXo="},{"name":"syft:metadata:size","value":"407383"}]},{"bom-ref":"pkg:composer/symfony/console@v6.4.1?package-id=767524bf09da7da7","type":"library","name":"symfony/console","version":"v6.4.1","licenses":[{"license":{"id":"MIT"}}],"cpe":"cpe:2.3:a:symfony\\/console:symfony\\/console:v6.4.1:*:*:*:*:*:*:*","purl":"pkg:composer/symfony/console@v6.4.1","properties":[{"name":"syft:package:foundBy","value":"php-composer-lock-cataloger"},{"name":"syft:package:language","value":"php"},{"name":"syft:package:type","value":"php-composer"},{"name":"syft:package:metadataType","value":"php-composer-lock-entry"},{"name":"syft:location:0:path","value":"/composer.lock"}]},{"bom-ref":"pkg:npm/webapp@1.0.0?package-id=982a05090388c92d","type":"library","name":"webapp","version":"1.0.0","cpe":"cpe:2.3:a:webapp:webapp:1.0.0:*:*:*:*:*:*:*","purl":"pkg:npm/webapp@1.0.0","properties":[{"name":"syft:package:foundBy","value":"javascript-lock-cataloger"},{"name":"syft:package:language","value":"javascript"},{"name":"syft:package:type","value":"npm"},{"name":"syft:package:metadataType","value":"javascript-npm-package-lock-entry"},{"name":"syft:location:0:path","value":"/package-lock.json"}]},{"bom-ref":"os:alpine@3.19.1","type":"operating-system","name":"alpine","version":"3.19.1","description":"Alpine Linux v3.19","swid":{"tagId":"alpine","name":"alpine","version":"3.19.1"},"properties":[{"name":"syft:distro:extendedSupport","value":"false"},{"name":"syft:distro:id","value":"alpine"},{"name":"syft:distro:prettyName","value":"Alpine Linux v3.19"},{"name":"syft:distro:versionID","value":"3.19.1"}]},{"bom-ref":"c8bb62e6bded633e","type":"file","name":"/builds/acme/webapp/composer.lock","hashes":[{"alg":"SHA-1","content":"53c59ca459a8ff42918b5ed4fdcea1d8ba98432f"},{"alg":"SHA-256","content":"63738301cc7186a6645f00ae0a63ae6347e04552489f3cc70e92200463f5b4ac"}]},{"bom-ref":"3fc5a8d3d86e9790","type":"file","name":"/builds/acme/webapp/go.mod","hashes":[{"alg":"SHA-1","content":"c67c41265c415c41049b31f850b4497898eff1fd"},{"alg":"SHA-256","content":"f2303d4139e491238d8cb9a6c448e4c366b82bae3a646164465387df76e44f32"}]},{"bom-ref":"9f5aca292136191a","type":"file","name":"/builds/acme/webapp/lib/apk/db/installed","hashes":[{"alg":"SHA-1","content":"b2ebf78ea604d3a76359a262afd401ab966a36a1"},{"alg":"SHA-256","content":"d363cb96812dc6eb1d6f4c00879c2564cdbff238b6c1d0a37701d2adedd326e0"}]},{"bom-ref":"fd71c2238fc07657","type":"file","name":"/builds/acme/webapp/package-lock.json","hashes":[{"alg":"SHA-1","content":"fc26eadd11405354163eb0f53ffd2bb8cb56c5e7"},{"alg":"SHA-256","content":"69094786dd997053d1c7a81d4349bb5b608c08b576e67360f07cdc2726a041ea"}]}],"dependencies":[{"ref":"pkg:npm/webapp@1.0.0?package-id=982a05090388c92d","dependsOn":["pkg:npm/%40babel/core@7.23.0?package-id=7b01fd7a9ce63128","pkg:npm/lodash@4.17.20?package-id=ece3658907628a6b"]}]} diff --git a/internal/jsonscan/jsonscan.go b/internal/jsonscan/jsonscan.go index d1ab0e8..7fcade7 100644 --- a/internal/jsonscan/jsonscan.go +++ b/internal/jsonscan/jsonscan.go @@ -1,3 +1,12 @@ +// Package jsonscan walks a JSON document in place, reporting where +// object members sit as offsets into the original bytes. It lets a caller +// read or replace one value in a large metadata document without decoding the +// rest of it into Go values, which for an npm packument costs many times the +// document's size. +// +// It checks structure only as far as it needs to find its way through +// the document. Callers that copy unvisited bytes into a response validate the +// whole document first with json.Valid. package jsonscan import ( @@ -6,16 +15,7 @@ import ( "errors" ) -// The helpers in this file walk a JSON document in place, reporting where -// object members sit as offsets into the original bytes. They let a handler -// read or replace one value in a large metadata document without decoding the -// rest of it into Go values, which for an npm packument costs many times the -// document's size. -// -// They check structure only as far as they need to find their way through -// the document. Callers that copy unvisited bytes into a response validate the -// whole document first with json.Valid. - +// ErrMalformed is returned when the document is not well-formed JSON. var ErrMalformed = errors.New("malformed JSON") // ErrNotObject is returned when a value expected to be an object is not. @@ -120,23 +120,23 @@ func EachMember(obj []byte, fn func(Member) error) error { if i >= len(obj) || obj[i] != '"' { return ErrMalformed } - KeyEnd, err := skipJSONString(obj, i) + keyEnd, err := skipJSONString(obj, i) if err != nil { return err } - colon := skipJSONSpace(obj, KeyEnd) + colon := skipJSONSpace(obj, keyEnd) if colon >= len(obj) || obj[colon] != ':' { return ErrMalformed } - ValStart := skipJSONSpace(obj, colon+1) - ValEnd, err := skipJSONValue(obj, ValStart) + valStart := skipJSONSpace(obj, colon+1) + valEnd, err := skipJSONValue(obj, valStart) if err != nil { return err } - if err := fn(Member{KeyStart: i, KeyEnd: KeyEnd, ValStart: ValStart, ValEnd: ValEnd}); err != nil { + if err := fn(Member{KeyStart: i, KeyEnd: keyEnd, ValStart: valStart, ValEnd: valEnd}); err != nil { return err } - next := skipJSONSpace(obj, ValEnd) + next := skipJSONSpace(obj, valEnd) if next >= len(obj) { return ErrMalformed } diff --git a/internal/jsonstream/jsonstream.go b/internal/jsonstream/jsonstream.go new file mode 100644 index 0000000..cf213ce --- /dev/null +++ b/internal/jsonstream/jsonstream.go @@ -0,0 +1,172 @@ +// Package jsonstream copies JSON objects from a reader to a writer one member +// at a time, so a document can be filtered without holding it in memory. +// Values that are kept are written with their original bytes. +package jsonstream + +import ( + "bytes" + "encoding/json/jsontext" + "errors" + "fmt" + "io" +) + +// ErrNotObject is returned when a value expected to be an object is not. +var ErrNotObject = errors.New("JSON value is not an object") + +var ( + errConsumed = errors.New("jsonstream: member value already consumed") + errUnconsumed = errors.New("jsonstream: Write before the member value was read") +) + +// Member is one member of an object being copied. Its value must be consumed +// exactly once, with Raw, Skip, Copy or Object. +type Member struct { + Key string + rawKey []byte + dec *jsontext.Decoder + out *objectWriter + consumed bool +} + +// Raw reads the member's value without writing it. Follow it with Write to +// keep the member. The bytes are only valid until the next member is read. +func (m *Member) Raw() ([]byte, error) { + if m.consumed { + return nil, errConsumed + } + m.consumed = true + return m.dec.ReadValue() +} + +// Skip reads past the member's value, leaving the member out. +func (m *Member) Skip() error { + if m.consumed { + return errConsumed + } + m.consumed = true + return m.dec.SkipValue() +} + +// Write writes the member with value as its raw JSON value. +func (m *Member) Write(value []byte) error { + if !m.consumed { + return errUnconsumed + } + if err := m.out.key(m.rawKey); err != nil { + return err + } + _, err := m.out.w.Write(value) + return err +} + +// Copy writes the member with its value unchanged. +func (m *Member) Copy() error { + raw, err := m.Raw() + if err != nil { + return err + } + return m.Write(raw) +} + +// Object writes the member and copies its value, which must be an object, +// calling fn for each of its members. A null value is written as null. +func (m *Member) Object(fn func(*Member) error) error { + if m.consumed { + return errConsumed + } + m.consumed = true + if err := m.out.key(m.rawKey); err != nil { + return err + } + return copyObject(m.dec, m.out.w, fn, true) +} + +// CopyObject copies the object read from r to w, calling fn for each member. +// fn decides what is written by how it consumes the member's value; a member +// whose value fn leaves unconsumed is copied unchanged. As with +// encoding/json, of repeated names each is passed to fn, and invalid UTF-8 +// is accepted. +func CopyObject(r io.Reader, w io.Writer, fn func(*Member) error) error { + dec := jsontext.NewDecoder(r, jsontext.AllowDuplicateNames(true), jsontext.AllowInvalidUTF8(true)) + if err := copyObject(dec, w, fn, false); err != nil { + return err + } + _, err := dec.ReadToken() + switch err { + case io.EOF: + return nil + case nil: + return errors.New("unexpected data after the top-level object") + } + return err +} + +func copyObject(dec *jsontext.Decoder, w io.Writer, fn func(*Member) error, allowNull bool) error { + tok, err := dec.ReadToken() + if err != nil { + return err + } + if tok.Kind() == 'n' && allowNull { + _, err := io.WriteString(w, "null") + return err + } + if tok.Kind() != '{' { + return ErrNotObject + } + if _, err := io.WriteString(w, "{"); err != nil { + return err + } + out := &objectWriter{w: w} + m := &Member{dec: dec, out: out} + // keyBuf holds the current key; ReadValue's bytes don't outlast fn. + var keyBuf []byte + for dec.PeekKind() != '}' { + // The key is read raw, so it is written with its own bytes. + rawKey, err := dec.ReadValue() + if err != nil { + return err + } + if rawKey.Kind() != '"' { + return fmt.Errorf("object key is %v, not a string", rawKey.Kind()) + } + keyBuf = append(keyBuf[:0], rawKey...) + // The decoder has checked the key, so the only error left is invalid + // UTF-8, which AppendUnquote reports after replacing it with U+FFFD, + // as encoding/json does. + key, _ := jsontext.AppendUnquote(nil, keyBuf) + *m = Member{Key: string(key), rawKey: keyBuf, dec: dec, out: out} + if err := fn(m); err != nil { + return err + } + if !m.consumed { + if err := m.Copy(); err != nil { + return err + } + } + } + if _, err := dec.ReadToken(); err != nil { + return err + } + _, err = io.WriteString(w, "}") + return err +} + +type objectWriter struct { + w io.Writer + wrote bool + buf bytes.Buffer +} + +// key writes the separator and the key's bytes for the next member. +func (o *objectWriter) key(rawKey []byte) error { + o.buf.Reset() + if o.wrote { + o.buf.WriteByte(',') + } + o.buf.Write(rawKey) + o.buf.WriteByte(':') + o.wrote = true + _, err := o.w.Write(o.buf.Bytes()) + return err +} diff --git a/internal/jsonstream/jsonstream_test.go b/internal/jsonstream/jsonstream_test.go new file mode 100644 index 0000000..cd201ae --- /dev/null +++ b/internal/jsonstream/jsonstream_test.go @@ -0,0 +1,202 @@ +package jsonstream + +import ( + "bytes" + "encoding/json" + "errors" + "slices" + "strings" + "testing" +) + +func copyString(t *testing.T, in string, fn func(*Member) error) (string, error) { + t.Helper() + var out bytes.Buffer + err := CopyObject(strings.NewReader(in), &out, fn) + return out.String(), err +} + +func TestCopyObjectKeepsValueBytes(t *testing.T) { + in := `{"a": 1.50, "b" : {"x": "<&>", "y":[1, 2]}, "c":null, "d":"é"}` + got, err := copyString(t, in, func(m *Member) error { return nil }) + if err != nil { + t.Fatal(err) + } + if want := `{"a":1.50,"b":{"x": "<&>", "y":[1, 2]},"c":null,"d":"é"}`; got != want { + t.Errorf("got %s\nwant %s", got, want) + } +} + +func TestCopyObjectFiltersNested(t *testing.T) { + in := `{"info":{"subdir":"noarch"},"packages":{"keep":{"n":1},"drop":{"n":2},"also":{"n":3}},"tail":[]}` + got, err := copyString(t, in, func(m *Member) error { + if m.Key != "packages" { + return m.Copy() + } + return m.Object(func(entry *Member) error { + raw, err := entry.Raw() + if err != nil { + return err + } + if entry.Key == "drop" { + return nil + } + return entry.Write(raw) + }) + }) + if err != nil { + t.Fatal(err) + } + if want := `{"info":{"subdir":"noarch"},"packages":{"keep":{"n":1},"also":{"n":3}},"tail":[]}`; got != want { + t.Errorf("got %s\nwant %s", got, want) + } + if !json.Valid([]byte(got)) { + t.Error("output is not valid JSON") + } +} + +func TestCopyObjectSkipReplaceAndEmpty(t *testing.T) { + got, err := copyString(t, `{"first":1,"secret":"x","n":2,"empty":{}}`, func(m *Member) error { + switch m.Key { + case "first", "secret": + _, err := m.Raw() + return err + case "n": + if _, err := m.Raw(); err != nil { + return err + } + return m.Write([]byte(`3`)) + case "empty": + return m.Object(func(*Member) error { return nil }) + } + return nil + }) + if err != nil { + t.Fatal(err) + } + if want := `{"n":3,"empty":{}}`; got != want { + t.Errorf("got %s, want %s", got, want) + } +} + +func TestCopyObjectKeys(t *testing.T) { + got, err := copyString(t, `{"a 0 && limit < noLimit { + return limit, true + } + } + return 0, false +} + +// ownCgroups returns the process's cgroup v2 path and its cgroup v1 memory +// controller path from /proc/self/cgroup, each "" when not listed. +func ownCgroups(fsys fs.FS) (v2, v1 string) { + f, err := fsys.Open("proc/self/cgroup") + if err != nil { + return "", "" + } + defer func() { _ = f.Close() }() + scanner := bufio.NewScanner(f) + for scanner.Scan() { + // Lines are "hierarchy-ID:controller-list:cgroup-path". + id, rest, ok := strings.Cut(scanner.Text(), ":") + if !ok { + continue + } + controllers, cgroup, ok := strings.Cut(rest, ":") + if !ok { + continue + } + switch { + case id == "0" && controllers == "": + v2 = cgroup + case hasController(controllers, "memory"): + v1 = cgroup + } + } + return v2, v1 +} + +func hasController(list, name string) bool { + for controller := range strings.SplitSeq(list, ",") { + if controller == name { + return true + } + } + return false +} diff --git a/internal/memlimit/memlimit_test.go b/internal/memlimit/memlimit_test.go new file mode 100644 index 0000000..bf8474b --- /dev/null +++ b/internal/memlimit/memlimit_test.go @@ -0,0 +1,66 @@ +package memlimit + +import ( + "testing" + "testing/fstest" +) + +func TestCgroupLimit(t *testing.T) { + const gib = 1 << 30 + for _, tt := range []struct { + name string + files map[string]string + want int64 + }{ + { + name: "cgroup v2 container", + files: map[string]string{"proc/self/cgroup": "0::/\n", "sys/fs/cgroup/memory.max": "2147483648\n"}, + want: 2 * gib, + }, + { + name: "cgroup v2 own cgroup", + files: map[string]string{ + "proc/self/cgroup": "0::/system.slice/proxy.service\n", + "sys/fs/cgroup/system.slice/proxy.service/memory.max": "1073741824\n", + }, + want: gib, + }, + { + name: "cgroup v2 unlimited", + files: map[string]string{"proc/self/cgroup": "0::/\n", "sys/fs/cgroup/memory.max": "max\n"}, + }, + { + name: "cgroup v1", + files: map[string]string{ + "proc/self/cgroup": "12:cpu,cpuacct:/\n4:memory:/\n", + "sys/fs/cgroup/memory/memory.limit_in_bytes": "536870912\n", + }, + want: gib / 2, + }, + { + name: "cgroup v1 unlimited", + files: map[string]string{ + "proc/self/cgroup": "4:memory:/\n", + "sys/fs/cgroup/memory/memory.limit_in_bytes": "9223372036854771712\n", + }, + }, + { + name: "malformed", + files: map[string]string{"sys/fs/cgroup/memory.max": "lots\n"}, + }, + { + name: "no cgroup files", + }, + } { + t.Run(tt.name, func(t *testing.T) { + fsys := fstest.MapFS{} + for name, data := range tt.files { + fsys[name] = &fstest.MapFile{Data: []byte(data)} + } + got, ok := cgroupLimit(fsys) + if got != tt.want || ok != (tt.want != 0) { + t.Errorf("cgroupLimit = %d, %v; want %d", got, ok, tt.want) + } + }) + } +} diff --git a/internal/metadata/npm/imports_test.go b/internal/metadata/npm/imports_test.go new file mode 100644 index 0000000..19f828c --- /dev/null +++ b/internal/metadata/npm/imports_test.go @@ -0,0 +1,48 @@ +package npm + +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/Masterminds/semver/v3", + "github.com/git-pkgs/cooldown", + "github.com/git-pkgs/proxy/internal/jsonscan", + "github.com/git-pkgs/proxy/internal/jsonstream", + "github.com/git-pkgs/proxy/internal/metadata/npm", + "github.com/git-pkgs/proxy/internal/packageurl", + "github.com/git-pkgs/purl", + "github.com/git-pkgs/vers", + "github.com/package-url/packageurl-go", + } + // database/sql/driver comes in through semver, which implements its + // Valuer interface; it is only interfaces, no driver. + 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/npm/metadata.go b/internal/metadata/npm/metadata.go index 0eff29f..7fc4a40 100644 --- a/internal/metadata/npm/metadata.go +++ b/internal/metadata/npm/metadata.go @@ -44,16 +44,18 @@ type Options struct { EvaluatedAt time.Time LocalVersions []LocalVersion // Optional callbacks report changes synchronously without retaining events. - OnTarballRewrite func(version, oldURL, newURL string) - OnCooldownFilter func(version, publishedAt string) + // OnTarballsRewritten is called at most once per document, with how many + // tarball URLs it pointed at the proxy, and not at all when none. + OnTarballsRewritten func(count int) + OnCooldownFilter func(version, publishedAt string) } type transformer struct{ Options } -// Rewrite filters upstream versions and rewrites their tarball URLs, preserving -// untouched JSON values verbatim. Hosted entries override upstream versions. -// The returned version set is unordered. The document, denylist and hosted -// entries are not modified. +// Rewrite filters upstream versions and points their tarball and attestation +// URLs at the proxy, preserving untouched JSON values verbatim. Hosted entries +// override upstream versions. The returned version set is unordered. The +// document, denylist and hosted entries are not modified. func Rewrite(packageName string, body []byte, options Options) ([]byte, []string, error) { return (&transformer{options}).rewriteMetadataWithLocal(packageName, body, options.LocalVersions) } @@ -89,6 +91,25 @@ func Version(packageName, specifier string, packument []byte, options Options) ( return out.Bytes(), nil } +// Abbreviated reports whether body is an abbreviated packument: one with the +// top-level "modified" field the abbreviated format carries and no "time" +// map, which cooldown needs. A full document without a time map, as some +// registries serve, is not abbreviated, and neither is anything that is not +// a JSON object. +func Abbreviated(body []byte) bool { + var hasTime, hasModified bool + err := jsonscan.EachMember(body, func(m jsonscan.Member) error { + switch key := m.Key(body); { + case jsonscan.KeyIs(key, "time"): + hasTime = true + case jsonscan.KeyIs(key, "modified"): + hasModified = true + } + return nil + }) + return err == nil && hasModified && !hasTime +} + func (h *transformer) rewriteMetadataWithLocal(packageName string, body []byte, local []LocalVersion) ([]byte, []string, error) { doc, err := indexNPMPackument(body) if err != nil { @@ -106,7 +127,9 @@ func (h *transformer) rewriteMetadataWithLocal(packageName string, body []byte, return nil, nil, ErrVersionDenied } var out bytes.Buffer - h.writeNPMVersion(&out, packageName, version, body) + if h.writeNPMVersion(&out, packageName, version, body) { + h.tarballsRewritten(1) + } return out.Bytes(), []string{version}, nil } if len(h.DeniedVersions) != 0 { @@ -258,6 +281,7 @@ func (d *npmPackument) write(writeValue func(out *bytes.Buffer, i int) error) ([ func (h *transformer) writeNPMVersions(out *bytes.Buffer, packageName string, versionsRaw []byte, keep map[string]any, local []LocalVersion) error { out.WriteByte('{') first := true + rewritten := 0 err := jsonscan.EachMember(versionsRaw, func(m jsonscan.Member) error { version, err := jsonscan.Key(m.Key(versionsRaw)) if err != nil { @@ -272,9 +296,12 @@ func (h *transformer) writeNPMVersions(out *bytes.Buffer, packageName string, ve first = false out.Write(m.Key(versionsRaw)) out.WriteByte(':') - h.writeNPMVersion(out, packageName, version, m.Value(versionsRaw)) + if h.writeNPMVersion(out, packageName, version, m.Value(versionsRaw)) { + rewritten++ + } return nil }) + h.tarballsRewritten(rewritten) for _, e := range local { if !first { out.WriteByte(',') @@ -289,42 +316,93 @@ func (h *transformer) writeNPMVersions(out *bytes.Buffer, packageName string, ve return err } -// writeNPMVersion writes one version entry with its dist.tarball pointing at -// this proxy. An entry without a string tarball is written unchanged. -func (h *transformer) writeNPMVersion(out *bytes.Buffer, packageName, version string, raw []byte) { +// writeNPMVersion writes one version entry with its dist.tarball and +// dist.attestations.url pointing at this proxy, and reports whether it +// rewrote the tarball. Members that are missing or not strings are written +// unchanged. +func (h *transformer) writeNPMVersion(out *bytes.Buffer, packageName, version string, raw []byte) bool { dist, ok, err := jsonscan.FindMember(raw, "dist") if err != nil || !ok { out.Write(raw) - return + return false } distRaw := dist.Value(raw) - tarball, ok, err := jsonscan.FindMember(distRaw, "tarball") - if err != nil || !ok || distRaw[tarball.ValStart] != '"' { - out.Write(raw) - return - } - var oldTarball string - if err := json.Unmarshal(tarball.Value(distRaw), &oldTarball); err != nil { - out.Write(raw) - return - } - newTarball := TarballURL(h.ProxyURL, packageName, version, oldTarball) - encoded, err := json.Marshal(newTarball) - if err != nil { - out.Write(raw) - return + var buf [2]urlEdit + edits := buf[:0] + tarball, ok := stringMember(distRaw, "tarball") + if ok { + tarball.replacement = TarballURL(h.ProxyURL, packageName, version, tarball.old) + edits = append(edits, tarball.shift(dist.ValStart)) } - out.Write(raw[:dist.ValStart+tarball.ValStart]) - out.Write(encoded) - out.Write(raw[dist.ValStart+tarball.ValEnd:]) - if h.OnTarballRewrite != nil { - h.OnTarballRewrite(version, oldTarball, newTarball) + if attestations, found, err := jsonscan.FindMember(distRaw, "attestations"); err == nil && found { + if att, ok := stringMember(attestations.Value(distRaw), "url"); ok { + att.replacement = AttestationsURL(h.ProxyURL, packageName, version) + edits = append(edits, att.shift(dist.ValStart+attestations.ValStart)) + } + } + writeEdits(out, raw, edits) + return tarball.replacement != "" +} + +// urlEdit replaces the string value at raw[start:end], which decodes to old, +// with replacement. +type urlEdit struct { + start, end int + old string + replacement string +} + +func (e urlEdit) shift(offset int) urlEdit { + e.start += offset + e.end += offset + return e +} + +// stringMember finds the string member name in obj. +func stringMember(obj []byte, name string) (urlEdit, bool) { + m, ok, err := jsonscan.FindMember(obj, name) + if err != nil || !ok || obj[m.ValStart] != '"' { + return urlEdit{}, false + } + var old string + if err := json.Unmarshal(m.Value(obj), &old); err != nil { + return urlEdit{}, false + } + return urlEdit{start: m.ValStart, end: m.ValEnd, old: old}, true +} + +// writeEdits writes raw with the edits applied. There are at most two, which +// may come in either order. +func writeEdits(out *bytes.Buffer, raw []byte, edits []urlEdit) { + if len(edits) == 2 && edits[1].start < edits[0].start { + edits[0], edits[1] = edits[1], edits[0] + } + pos := 0 + for _, e := range edits { + encoded, err := json.Marshal(e.replacement) + if err != nil { + continue + } + out.Write(raw[pos:e.start]) + out.Write(encoded) + pos = e.end + } + out.Write(raw[pos:]) +} + +// tarballsRewritten reports once per document how many tarball URLs it +// rewrote. A report per version flooded debug logs: packages such as eslint +// list hundreds of versions, and with cooldown on every request rewrites the +// document again. +func (h *transformer) tarballsRewritten(count int) { + if count > 0 && h.OnTarballsRewritten != nil { + h.OnTarballsRewritten(count) } } // applyCooldownFiltering removes versions that are too recently published, -// and updates dist-tags.latest if the current latest was filtered out. +// and updates the dist-tags that named them. func (h *transformer) applyCooldownFiltering(metadata map[string]any, versions map[string]any, packageName string) { if h.Cooldown == nil || !h.Cooldown.Enabled() { return @@ -337,6 +415,7 @@ func (h *transformer) applyCooldownFiltering(metadata map[string]any, versions m packagePURL := packageurl.MakeString("npm", packageName, "") + withheld := map[string]bool{} for version := range versions { publishedStr, ok := timeMap[version].(string) if !ok { @@ -352,20 +431,29 @@ func (h *transformer) applyCooldownFiltering(metadata map[string]any, versions m } delete(versions, version) delete(timeMap, version) + withheld[version] = true } } - h.updateDistTagsLatest(metadata, versions, timeMap) + h.updateDistTags(metadata, versions, timeMap, withheld) } -// updateDistTagsLatest updates the dist-tags.latest field if the current latest -// version was removed by cooldown filtering. -func (h *transformer) updateDistTagsLatest(metadata, versions, timeMap map[string]any) { +// updateDistTags moves dist-tags.latest to the newest remaining version if +// the current latest was removed by cooldown filtering, and, as the denylist +// does, drops other tags that name a withheld version. +func (h *transformer) updateDistTags(metadata, versions, timeMap map[string]any, withheld map[string]bool) { distTags, ok := metadata["dist-tags"].(map[string]any) if !ok { return } + for tag, value := range distTags { + version, _ := value.(string) + if tag != "latest" && withheld[version] { + delete(distTags, tag) + } + } + latest, ok := distTags["latest"].(string) if !ok { return @@ -377,6 +465,8 @@ func (h *transformer) updateDistTagsLatest(metadata, versions, timeMap map[strin if newLatest := h.findNewestVersion(versions, timeMap); newLatest != "" { distTags["latest"] = newLatest + } else if withheld[latest] { + delete(distTags, "latest") } } @@ -398,6 +488,13 @@ func TarballURL(proxyURL, packageName, version, tarball string) string { return fmt.Sprintf("%s/npm/%s/-/%s", proxyURL, url.PathEscape(packageName), filename) } +// AttestationsURL returns the proxy URL that serves the attestations of a +// version, in the form the npm registry uses: the package name with its scope +// slash encoded, "@", and the version. +func AttestationsURL(proxyURL, packageName, version string) string { + return fmt.Sprintf("%s/npm/-/npm/v1/attestations/%s@%s", proxyURL, url.PathEscape(packageName), url.PathEscape(version)) +} + // findNewestVersion returns the version string with the most recent timestamp // from the remaining versions, using the time map. func (h *transformer) findNewestVersion(versions map[string]any, timeMap map[string]any) string { diff --git a/internal/metadata/npm/metadata_test.go b/internal/metadata/npm/metadata_test.go index a1e5e4b..2748ed3 100644 --- a/internal/metadata/npm/metadata_test.go +++ b/internal/metadata/npm/metadata_test.go @@ -151,3 +151,82 @@ func TestNPMRewriteMetadataDuplicateKeys(t *testing.T) { t.Errorf("rewrite = %s", out) } } + +func TestAbbreviated(t *testing.T) { + for body, want := range map[string]bool{ + `{"name":"demo","modified":"2024-01-01T00:00:00Z","versions":{}}`: true, + `{"name":"demo","modified":"2024-01-01T00:00:00Z","time":{},"versions":{}}`: false, + `{"name":"demo","versions":{}}`: false, + `["modified"]`: false, + `{"modified":`: false, + } { + if got := Abbreviated([]byte(body)); got != want { + t.Errorf("Abbreviated(%s) = %v, want %v", body, got, want) + } + } +} + +// TestNPMRewriteAttestationsURL checks that dist.attestations.url points at +// the proxy whichever order dist lists its members in, and that nothing else +// in dist changes. +func TestNPMRewriteAttestationsURL(t *testing.T) { + options := Options{ProxyURL: "http://proxy"} + tests := []struct{ name, version, dist, want string }{ + {"demo", "1.0.0", + `{"tarball":"https://registry.npmjs.org/demo/-/demo-1.0.0.tgz","attestations":{"url":"https://registry.npmjs.org/-/npm/v1/attestations/demo@1.0.0","provenance":{"predicateType":"p"}}}`, + `{"tarball":"http://proxy/npm/demo/-/demo-1.0.0.tgz","attestations":{"url":"http://proxy/npm/-/npm/v1/attestations/demo@1.0.0","provenance":{"predicateType":"p"}}}`}, + {"@scope/demo", "2.0.0-rc.1", + `{"attestations":{"provenance":{},"url":"https://registry.npmjs.org/-/npm/v1/attestations/@scope%2fdemo@2.0.0-rc.1"},"tarball":"https://registry.npmjs.org/@scope/demo/-/demo-2.0.0-rc.1.tgz"}`, + `{"attestations":{"provenance":{},"url":"http://proxy/npm/-/npm/v1/attestations/@scope%2Fdemo@2.0.0-rc.1"},"tarball":"http://proxy/npm/@scope%2Fdemo/-/demo-2.0.0-rc.1.tgz"}`}, + {"demo", "3.0.0", + `{"attestations":{"url":7}}`, + `{"attestations":{"url":7}}`}, + } + for _, tt := range tests { + input := `{"versions":{"` + tt.version + `":{"dist":` + tt.dist + `}}}` + out, _, err := Rewrite(tt.name, []byte(input), options) + if err != nil { + t.Fatal(err) + } + want := `{"versions":{"` + tt.version + `":{"dist":` + tt.want + `}}}` + if string(out) != want { + t.Errorf("%s@%s: rewrite =\n%s\nwant\n%s", tt.name, tt.version, out, want) + } + } +} + +// TestNPMRewriteCooldownDropsTags checks that cooldown, like the denylist, +// drops a tag other than latest that names a version it withholds, in both +// the in-memory and the streamed rewrite. +func TestNPMRewriteCooldownDropsTags(t *testing.T) { + now := time.Date(2026, 10, 18, 12, 0, 0, 0, time.UTC) + ts := func(age time.Duration) string { return now.Add(-age).UTC().Format(time.RFC3339) } + options := Options{ProxyURL: "http://proxy", EvaluatedAt: now, Cooldown: &cooldown.Config{Default: "3d"}} + input := `{"name":"demo",` + + `"dist-tags":{"latest":"3.0.0","next":"3.0.0","legacy":"1.0.0"},` + + `"versions":{"1.0.0":{},"2.0.0":{},"3.0.0":{}},` + + `"time":{"1.0.0":"` + ts(900*time.Hour) + `","2.0.0":"` + ts(800*time.Hour) + `","3.0.0":"` + ts(time.Hour) + `"}}` + + rewrite := map[string]func() ([]byte, []string, error){ + "memory": func() ([]byte, []string, error) { return Rewrite("demo", []byte(input), options) }, + "stream": func() ([]byte, []string, error) { return rewriteStream("demo", []byte(input), options) }, + } + for name, run := range rewrite { + t.Run(name, func(t *testing.T) { + out, _, err := run() + if err != nil { + t.Fatal(err) + } + var doc struct { + DistTags map[string]string `json:"dist-tags"` + } + if err := json.Unmarshal(out, &doc); err != nil { + t.Fatalf("output is not JSON: %v\n%s", err, out) + } + want := map[string]string{"latest": "2.0.0", "legacy": "1.0.0"} + if fmt.Sprint(doc.DistTags) != fmt.Sprint(want) { + t.Errorf("dist-tags = %v, want %v", doc.DistTags, want) + } + }) + } +} diff --git a/internal/metadata/npm/npmbench/npmbench.go b/internal/metadata/npm/npmbench/npmbench.go new file mode 100644 index 0000000..cc4ad57 --- /dev/null +++ b/internal/metadata/npm/npmbench/npmbench.go @@ -0,0 +1,42 @@ +// Package npmbench builds npm packuments for benchmarks. +package npmbench + +import ( + "fmt" + "strings" +) + +// readmeSentences makes each version's readme about 4KB. +const readmeSentences = 160 + +// Packument builds a full packument shaped like a large real one: versions +// 1.0.0 to 1.0.{versions-1}, each with dependencies, scripts and a readme, +// and a time entry for each. +func Packument(versions int) []byte { + var b strings.Builder + readme := strings.Repeat("Some documentation text. ", readmeSentences) + b.WriteString(`{"_id":"big","name":"big","dist-tags":{"latest":"1.0.` + fmt.Sprint(versions-1) + `"},"versions":{`) + for i := range versions { + if i > 0 { + b.WriteByte(',') + } + v := fmt.Sprintf("1.0.%d", i) + fmt.Fprintf(&b, `%q:{"name":"big","version":%q,"description":"A big package","main":"index.js",`+ + `"scripts":{"test":"node test.js","build":"tsc -p ."},"dependencies":{`, v, v) + for d := range 25 { + if d > 0 { + b.WriteByte(',') + } + fmt.Fprintf(&b, `"dep-%d":"^%d.0.0"`, d, d) + } + fmt.Fprintf(&b, `},"readme":%q,"dist":{"shasum":"0123456789abcdef0123456789abcdef01234567",`+ + `"integrity":"sha512-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA==",`+ + `"tarball":"https://registry.npmjs.org/big/-/big-%s.tgz"}}`, readme, v) + } + b.WriteString(`},"time":{"created":"2015-01-01T00:00:00.000Z"`) + for i := range versions { + fmt.Fprintf(&b, `,"1.0.%d":"2016-01-01T00:00:00.000Z"`, i) + } + b.WriteString(`}}`) + return []byte(b.String()) +} diff --git a/internal/metadata/npm/policy_test.go b/internal/metadata/npm/policy_test.go index 8ef3729..7726d29 100644 --- a/internal/metadata/npm/policy_test.go +++ b/internal/metadata/npm/policy_test.go @@ -24,10 +24,10 @@ func TestRewriteCallbacks(t *testing.T) { t.Fatal(err) } var rewrites, filtered int - options.OnTarballRewrite = func(version, oldURL, newURL string) { + options.OnTarballsRewritten = func(count int) { rewrites++ - if version != "1.0.0" || oldURL != "https://registry.npmjs.org/@example/widgets/-/widgets-1.0.0.tgz" || newURL != "https://proxy.example/npm/@example%2Fwidgets/-/widgets-1.0.0.tgz" { - t.Errorf("rewrite event: %s, %s, %s", version, oldURL, newURL) + if count != 1 { + t.Errorf("rewrite count = %d, want 1", count) } } options.OnCooldownFilter = func(version, publishedAt string) { @@ -99,10 +99,18 @@ func TestVersionPolicyErrors(t *testing.T) { {"1.0.0", nil}, {"latest", nil}, {"2.0.0", ErrVersionDenied}, {"3.0.0", ErrVersionNotFound}, {"beta", ErrVersionNotFound}, {"missing", ErrVersionNotFound}, } { t.Run(tc.specifier, func(t *testing.T) { + var counts []int + options := options + options.OnTarballsRewritten = func(count int) { counts = append(counts, count) } out, err := Version("@example/widgets", tc.specifier, packument, options) if !errors.Is(err, tc.want) { t.Fatalf("error = %v, want %v", err, tc.want) } + // The packument is reported once; picking one version out of it + // is not a second report. + if !slices.Equal(counts, []int{1}) { + t.Errorf("rewrite reports = %v, want [1]", counts) + } if tc.want == nil && (!bytes.Contains(out, []byte(`"version": "1.0.0"`)) || !bytes.Contains(out, []byte("https://proxy.example/npm/@example%2Fwidgets/-/widgets-1.0.0.tgz"))) { t.Fatalf("resolved version: %s", out) } @@ -141,6 +149,11 @@ func TestRewriteVersionDocument(t *testing.T) { if err != nil || !slices.Equal(kept, []string{"1.0.0"}) || !bytes.Contains(out, []byte("https://proxy.example/npm/@example%2Fwidgets/-/widgets-1.0.0.tgz")) { t.Fatalf("rewrite: %s, %v, %v", out, kept, err) } + var counts []int + options.OnTarballsRewritten = func(count int) { counts = append(counts, count) } + if _, _, err := Rewrite("@example/widgets", body, options); err != nil || !slices.Equal(counts, []int{1}) { + t.Fatalf("version document reported %v, %v", counts, err) + } options.DeniedVersions = map[string]bool{"1.0.0": true} if _, _, err := Rewrite("@example/widgets", body, options); !errors.Is(err, ErrVersionDenied) { t.Fatalf("denied version: %v", err) diff --git a/internal/metadata/npm/stream.go b/internal/metadata/npm/stream.go new file mode 100644 index 0000000..ba847df --- /dev/null +++ b/internal/metadata/npm/stream.go @@ -0,0 +1,426 @@ +package npm + +import ( + "bytes" + "encoding/json" + "encoding/json/jsontext" + "errors" + "fmt" + "io" + "maps" + "reflect" + "slices" + + "github.com/git-pkgs/proxy/internal/jsonstream" +) + +// ErrNotStreamable is returned by RewriteStream for a document it leaves to +// Rewrite: one without a versions object, such as a single version's +// metadata, or a rewrite that lists pushed versions. +var ErrNotStreamable = errors.New("npm metadata can't be rewritten as a stream") + +// Scan is what a first pass over a packument learns: the version names, and +// the time map and dist-tags the filters work on. It holds no version +// entries, so it stays small whatever the size of the packument. +type Scan struct { + versions []string + versionsObject bool + time any + distTags any + // occurrences counts each filtered key, so the second pass can drop the + // earlier duplicates, as Rewrite does. + occurrences map[string]int + hasModified bool +} + +// Abbreviated reports whether the scanned document is an abbreviated +// packument, as the package function Abbreviated does for a document in +// memory. +func (s *Scan) Abbreviated() bool { + return s.hasModified && s.occurrences["time"] == 0 +} + +// ScanPackument reads a packument once, keeping only what RewriteStream +// needs to decide which versions remain. Version entries are read one at a +// time and dropped. +func ScanPackument(r io.Reader) (*Scan, error) { + s := &Scan{occurrences: map[string]int{}} + dec := newDecoder(r) + if err := expectDelim(dec, '{'); err != nil { + return nil, err + } + for dec.PeekKind() != '}' { + key, err := objectKey(dec) + if err != nil { + return nil, err + } + switch key { + case "versions": + s.occurrences[key]++ + s.versions, s.versionsObject, err = objectKeys(dec) + case "time": + s.occurrences[key]++ + s.time = nil + err = decodeValue(dec, &s.time) + case "dist-tags": + s.occurrences[key]++ + s.distTags = nil + err = decodeValue(dec, &s.distTags) + default: + if key == "modified" { + s.hasModified = true + } + err = dec.SkipValue() + } + if err != nil { + return nil, err + } + } + if err := expectDelim(dec, '}'); err != nil { + return nil, err + } + return s, expectEnd(dec) +} + +// RewriteStream is Rewrite for a packument too large to hold in memory. scan +// is the result of ScanPackument over the same bytes r reads again; the +// caller checks they are the same. The rewritten document is written to w +// with the bytes of untouched values copied as they are, and its output is +// the same as Rewrite's for the same document and options. It returns the +// versions it kept. For a document without a versions object, or options +// listing pushed versions, it returns ErrNotStreamable before writing. +func RewriteStream(packageName string, scan *Scan, r io.Reader, w io.Writer, options Options) ([]string, error) { + if !scan.versionsObject || len(options.LocalVersions) > 0 { + return nil, ErrNotStreamable + } + h := &transformer{options} + f := scan.filter(h, packageName) + sw := &streamWriter{ + transformer: h, + packageName: packageName, + scan: scan, + filtered: f, + seen: map[string]int{}, + } + if err := jsonstream.CopyObject(r, w, sw.member); err != nil { + return nil, err + } + h.tarballsRewritten(sw.rewritten) + return slices.Collect(maps.Keys(f.versions)), nil +} + +// filtered is what cooldown and the denylist leave of a scanned packument. +type filtered struct { + versions map[string]any + timeMap, distTags map[string]any + timeChanged, tagsChanged bool +} + +// filter runs the filters Rewrite runs over what scan collected. The scan is +// left as it is, so it can be filtered again. +func (s *Scan) filter(h *transformer, packageName string) filtered { + versions := make(map[string]any, len(s.versions)) + for _, v := range s.versions { + versions[v] = nil + } + metadata := map[string]any{} + timeMap := s.objectValue(metadata, "time", s.time) + distTags := s.objectValue(metadata, "dist-tags", s.distTags) + timeEntries := len(timeMap) + originalTags := maps.Clone(distTags) + + h.applyCooldownFiltering(metadata, versions, packageName) + h.applyDenylistFiltering(metadata, versions) + + return filtered{ + versions: versions, + timeMap: timeMap, + distTags: distTags, + timeChanged: timeMap != nil && len(timeMap) != timeEntries, + tagsChanged: distTags != nil && !reflect.DeepEqual(distTags, originalTags), + } +} + +// streamWriter writes the second pass of RewriteStream from the filtered +// state the first pass left. +type streamWriter struct { + *transformer + filtered + packageName string + scan *Scan + seen map[string]int + entry bytes.Buffer + rewritten int +} + +// member writes one top-level member. Members the filters don't touch are +// left unconsumed, so CopyObject copies them as they are. +func (s *streamWriter) member(m *jsonstream.Member) error { + total, filtered := s.scan.occurrences[m.Key] + if !filtered { + return nil + } + s.seen[m.Key]++ + if s.seen[m.Key] < total { + return m.Skip() // an earlier duplicate, dropped + } + switch { + case m.Key == "versions": + return m.Object(s.version) + case m.Key == "time" && s.timeChanged: + return m.Object(s.time) + case m.Key == "dist-tags" && s.tagsChanged: + if err := m.Skip(); err != nil { + return err + } + encoded, err := json.Marshal(s.distTags) + if err != nil { + return err + } + return m.Write(encoded) + } + return nil +} + +// version writes a kept version with its tarball pointing at the proxy. +func (s *streamWriter) version(v *jsonstream.Member) error { + if _, keep := s.versions[v.Key]; !keep { + return v.Skip() + } + raw, err := v.Raw() + if err != nil { + return err + } + s.entry.Reset() + if s.writeNPMVersion(&s.entry, s.packageName, v.Key, raw) { + s.rewritten++ + } + return v.Write(s.entry.Bytes()) +} + +// time writes a time entry the filters kept. +func (s *streamWriter) time(t *jsonstream.Member) error { + if _, keep := s.timeMap[t.Key]; keep { + return t.Copy() + } + return t.Skip() +} + +// objectValue records value under name in metadata, as Rewrite's +// decodeObject does, and returns it when it is an object. An object is +// copied, since the filters edit it. +func (s *Scan) objectValue(metadata map[string]any, name string, value any) map[string]any { + if s.occurrences[name] == 0 { + return nil + } + object, ok := value.(map[string]any) + if !ok { + metadata[name] = value + return nil + } + object = maps.Clone(object) + metadata[name] = object + return object +} + +// newDecoder reads JSON as encoding/json does: of repeated names the last +// counts, and invalid UTF-8 in strings is replaced rather than refused. +func newDecoder(r io.Reader) *jsontext.Decoder { + return jsontext.NewDecoder(r, jsontext.AllowDuplicateNames(true), jsontext.AllowInvalidUTF8(true)) +} + +func expectDelim(dec *jsontext.Decoder, want jsontext.Kind) error { + tok, err := dec.ReadToken() + if err != nil { + return err + } + if tok.Kind() != want { + return fmt.Errorf("npm metadata: expected %v, got %v", want, tok.Kind()) + } + return nil +} + +// expectEnd checks nothing follows the top-level object. +func expectEnd(dec *jsontext.Decoder) error { + _, err := dec.ReadToken() + switch err { + case io.EOF: + return nil + case nil: + return errors.New("unexpected data after the top-level object") + } + return err +} + +func objectKey(dec *jsontext.Decoder) (string, error) { + tok, err := dec.ReadToken() + if err != nil { + return "", err + } + if tok.Kind() != '"' { + return "", fmt.Errorf("npm metadata: object key is %v, not a string", tok.Kind()) + } + return tok.String(), nil +} + +// decodeValue reads the next value into v, as encoding/json decodes it. +func decodeValue(dec *jsontext.Decoder, v any) error { + raw, err := dec.ReadValue() + if err != nil { + return err + } + return json.Unmarshal(raw, v) +} + +// objectKeys reads a value and returns its keys when it is an object. +func objectKeys(dec *jsontext.Decoder) ([]string, bool, error) { + kind := dec.PeekKind() + if kind != '{' && kind != '[' { + return nil, false, dec.SkipValue() + } + if _, err := dec.ReadToken(); err != nil { + return nil, false, err + } + var keys []string + for next := dec.PeekKind(); next != '}' && next != ']'; next = dec.PeekKind() { + if kind == '{' { + key, err := objectKey(dec) + if err != nil { + return nil, false, err + } + keys = append(keys, key) + } + if err := dec.SkipValue(); err != nil { + return nil, false, err + } + } + if _, err := dec.ReadToken(); err != nil { + return nil, false, err + } + return keys, kind == '{', nil +} + +// VersionStream is Version for a packument too large to hold in memory. scan +// is the result of ScanPackument over the bytes r reads again; the second +// pass only looks for the one version entry it serves. For a document +// without a versions object it returns ErrNotStreamable. +func VersionStream(packageName, specifier string, scan *Scan, r io.Reader, options Options) ([]byte, error) { + if !scan.versionsObject || len(options.LocalVersions) > 0 { + return nil, ErrNotStreamable + } + h := &transformer{options} + f := scan.filter(h, packageName) + + target := specifier + if tag, ok := f.distTags[specifier].(string); ok { + target = tag + } + if options.DeniedVersions[target] { + return nil, ErrVersionDenied + } + if _, kept := f.versions[target]; !kept { + return nil, ErrVersionNotFound + } + entry, err := LookupVersion(r, target) + if err != nil { + return nil, err + } + if entry.Entry == nil { + return nil, ErrVersionNotFound + } + var out bytes.Buffer + h.writeNPMVersion(&out, packageName, target, entry.Entry) + return out.Bytes(), nil +} + +// VersionEntry is what a packument holds for one version. +type VersionEntry struct { + // Entry is versions[version], or nil when there is none. + Entry json.RawMessage + // Published is time[version], or "" when it is missing or not a string. + Published string + // Abbreviated is set for an abbreviated packument (see Abbreviated). + Abbreviated bool +} + +// LookupVersion reads a packument once and returns what it holds for +// version, keeping no other version's entry. Of repeated keys the last one +// counts, as with JSON.parse. +func LookupVersion(r io.Reader, version string) (VersionEntry, error) { + var e VersionEntry + var hasTime, hasModified bool + dec := newDecoder(r) + if err := expectDelim(dec, '{'); err != nil { + return e, err + } + for dec.PeekKind() != '}' { + key, err := objectKey(dec) + if err != nil { + return e, err + } + switch key { + case "versions": + e.Entry, err = objectMember(dec, version) + case "time": + hasTime = true + var raw json.RawMessage + raw, err = objectMember(dec, version) + e.Published = "" + if err == nil && raw != nil { + _ = json.Unmarshal(raw, &e.Published) + } + default: + hasModified = hasModified || key == "modified" + err = dec.SkipValue() + } + if err != nil { + return e, err + } + } + if err := expectDelim(dec, '}'); err != nil { + return e, err + } + if err := expectEnd(dec); err != nil { + return e, err + } + e.Abbreviated = hasModified && !hasTime + return e, nil +} + +// objectMember reads a value and returns its member key when it is an object +// that has one, the last if repeated, or nil. +func objectMember(dec *jsontext.Decoder, key string) (json.RawMessage, error) { + kind := dec.PeekKind() + if kind != '{' && kind != '[' { + return nil, dec.SkipValue() + } + if _, err := dec.ReadToken(); err != nil { + return nil, err + } + var found json.RawMessage + for next := dec.PeekKind(); next != '}' && next != ']'; next = dec.PeekKind() { + k := "" + if kind == '{' { + var err error + if k, err = objectKey(dec); err != nil { + return nil, err + } + } + if kind == '{' && k == key { + raw, err := dec.ReadValue() + if err != nil { + return nil, err + } + // ReadValue's bytes are only valid until the next read. + found = bytes.Clone(raw) + continue + } + if err := dec.SkipValue(); err != nil { + return nil, err + } + } + if _, err := dec.ReadToken(); err != nil { + return nil, err + } + return found, nil +} diff --git a/internal/metadata/npm/stream_bench_test.go b/internal/metadata/npm/stream_bench_test.go new file mode 100644 index 0000000..12d04d8 --- /dev/null +++ b/internal/metadata/npm/stream_bench_test.go @@ -0,0 +1,59 @@ +package npm + +import ( + "bytes" + "io" + "os" + "testing" + + "github.com/git-pkgs/proxy/internal/metadata/npm/npmbench" +) + +func BenchmarkScanPackument(b *testing.B) { + body := npmbench.Packument(5000) + b.SetBytes(int64(len(body))) + b.ReportAllocs() + for b.Loop() { + if _, err := ScanPackument(bytes.NewReader(body)); err != nil { + b.Fatal(err) + } + } +} + +func BenchmarkLookupVersion(b *testing.B) { + body := npmbench.Packument(5000) + b.SetBytes(int64(len(body))) + b.ReportAllocs() + for b.Loop() { + entry, err := LookupVersion(bytes.NewReader(body), "1.0.2500") + if err != nil || entry.Entry == nil || entry.Published == "" { + b.Fatalf("LookupVersion = %+v, %v", entry, err) + } + } +} + +// BenchmarkRewriteStream times RewriteStream's second pass, the copy, over +// the 5,000-version packument, or the one NPM_PACKUMENT_BENCH names. +func BenchmarkRewriteStream(b *testing.B) { + body := npmbench.Packument(5000) + name := "big" + if path := os.Getenv("NPM_PACKUMENT_BENCH"); path != "" { + var err error + if body, err = os.ReadFile(path); err != nil { + b.Fatal(err) + } + name = os.Getenv("NPM_PACKUMENT_BENCH_NAME") + } + scan, err := ScanPackument(bytes.NewReader(body)) + if err != nil { + b.Fatal(err) + } + options := Options{ProxyURL: "http://proxy.example"} + b.SetBytes(int64(len(body))) + b.ReportAllocs() + for b.Loop() { + if _, err := RewriteStream(name, scan, bytes.NewReader(body), io.Discard, options); err != nil { + b.Fatal(err) + } + } +} diff --git a/internal/metadata/npm/stream_test.go b/internal/metadata/npm/stream_test.go new file mode 100644 index 0000000..620882d --- /dev/null +++ b/internal/metadata/npm/stream_test.go @@ -0,0 +1,254 @@ +package npm + +import ( + "bytes" + "encoding/json" + "errors" + "fmt" + "reflect" + "slices" + "strings" + "testing" + "time" + + "github.com/git-pkgs/cooldown" +) + +// rewriteStream runs both passes of RewriteStream over body. +func rewriteStream(packageName string, body []byte, options Options) ([]byte, []string, error) { + scan, err := ScanPackument(bytes.NewReader(body)) + if err != nil { + return nil, nil, err + } + var out bytes.Buffer + kept, err := RewriteStream(packageName, scan, bytes.NewReader(body), &out, options) + return out.Bytes(), kept, err +} + +// streamCases returns packuments with the filtered members in either +// order, duplicates and values Rewrite copies verbatim, and the options to +// rewrite them with. +func streamCases() (map[string]string, map[string]Options) { + now := time.Date(2026, 10, 18, 12, 0, 0, 0, time.UTC) + ts := func(age time.Duration) string { return now.Add(-age).Format(time.RFC3339) } + version := func(v string) string { + return fmt.Sprintf(`%q:{"version":%q,"dist":{"tarball":"https://registry.npmjs.org/demo/-/demo-%s.tgz"}}`, v, v, v) + } + versions := `"versions":{` + version("1.0.0") + `,` + version("2.0.0") + `,` + version("3.0.0") + `}` + times := `"time":{"created":"` + ts(1000*time.Hour) + `","1.0.0":"` + ts(900*time.Hour) + `","2.0.0":"` + ts(800*time.Hour) + `","3.0.0":"` + ts(time.Hour) + `"}` + tags := `"dist-tags":{"latest":"3.0.0","beta":"2.0.0","next":"1.0.0"}` + + docs := map[string]string{ + "testdata": string(packument), + "tags, versions, time": `{"name":"demo",` + tags + `,` + versions + `,` + times + `}`, + "time first": `{` + times + `,"name":"demo",` + versions + `,` + tags + `}`, + "no time": `{"name":"demo",` + tags + `,` + versions + `}`, + "time null": `{"time":null,` + tags + `,` + versions + `}`, + "tags not an object": `{"dist-tags":"x",` + versions + `,` + times + `}`, + "duplicates": `{"versions":{` + version("9.0.0") + `},` + tags + `,"time":{"9.0.0":"` + ts(time.Hour) + `"},` + + versions + `,` + times + `,"dist-tags":{"latest":"3.0.0"}}`, + "verbatim values": `{"_big":12345678901234567890,"readme":"&","nested":{"a":[1, 2 ,{"b":null}]},` + versions + `}`, + "unusual entries": `{"versions":{"1.0.0":"not an object","2.0.0":{"dist":"x"},"3.0.0":{"dist":{"tarball":7}},` + + `"4.0.0":{"dist":{"tarball":"https://registry.npmjs.org/demo/-/renamed.tgz"}},"5.0.0":{"dist":{}}}}`, + "whitespace": "{ \"name\" : \"demo\" ,\n\t\"versions\" : {\n \"1.0.0\" : { \"dist\" : { \"tarball\" : \"https://registry.npmjs.org/demo/-/demo-1.0.0.tgz\" } } } }", + "empty versions": `{"name":"demo","versions":{}}`, + } + options := map[string]Options{ + "plain": {ProxyURL: "http://proxy"}, + "cooldown": {ProxyURL: "http://proxy", Cooldown: &cooldown.Config{Default: "3d"}, EvaluatedAt: now}, + "denylist": {ProxyURL: "http://proxy", DeniedVersions: map[string]bool{"2.0.0": true}}, + "both": {ProxyURL: "http://proxy", Cooldown: &cooldown.Config{Default: "3d"}, EvaluatedAt: now, + DeniedVersions: map[string]bool{"1.0.0": true}}, + } + return docs, options +} + +// TestRewriteStreamMatchesRewrite checks that the streamed rewrite writes the +// same bytes and keeps the same versions as Rewrite, over documents with the +// filtered members in either order, duplicates, and values Rewrite copies +// verbatim. +func TestRewriteStreamMatchesRewrite(t *testing.T) { + docs, options := streamCases() + for docName, doc := range docs { + for optName, opts := range options { + t.Run(docName+"/"+optName, func(t *testing.T) { + want, wantKept, err := Rewrite("demo", []byte(doc), opts) + if err != nil { + t.Fatalf("Rewrite: %v", err) + } + got, gotKept, err := rewriteStream("demo", []byte(doc), opts) + if err != nil { + t.Fatalf("RewriteStream: %v", err) + } + // Rewrite keeps the whitespace inside the members of a + // filtered time map, which the stream doesn't see. + if !bytes.Equal(compact(t, got), compact(t, want)) { + t.Errorf("RewriteStream =\n%s\nRewrite =\n%s", got, want) + } + if docName == "verbatim values" && !bytes.Contains(got, []byte(`"_big":12345678901234567890,"readme":"&","nested":{"a":[1, 2 ,{"b":null}]}`)) { + t.Errorf("values not copied verbatim: %s", got) + } + slices.Sort(gotKept) + slices.Sort(wantKept) + if !slices.Equal(gotKept, wantKept) { + t.Errorf("kept %v, Rewrite kept %v", gotKept, wantKept) + } + }) + } + } +} + +func compact(t *testing.T, doc []byte) []byte { + t.Helper() + var out bytes.Buffer + if err := json.Compact(&out, doc); err != nil { + t.Fatalf("output is not JSON: %v\n%s", err, doc) + } + return out.Bytes() +} + +func TestRewriteStreamCallbacks(t *testing.T) { + var filtered []string + var rewritten []int + options := Options{ProxyURL: "http://proxy", Cooldown: &cooldown.Config{Default: "7d"}, + EvaluatedAt: time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC), + OnCooldownFilter: func(version, _ string) { filtered = append(filtered, version) }, + OnTarballsRewritten: func(count int) { rewritten = append(rewritten, count) }, + } + if _, _, err := rewriteStream("@example/widgets", packument, options); err != nil { + t.Fatal(err) + } + if !slices.Equal(filtered, []string{"3.0.0"}) || !slices.Equal(rewritten, []int{2}) { + t.Errorf("filtered %v, rewritten %v; want [3.0.0] and [2]", filtered, rewritten) + } +} + +func TestRewriteStreamNotStreamable(t *testing.T) { + for name, tc := range map[string]struct { + doc string + options Options + }{ + "single version": {`{"name":"demo","version":"1.0.0","dist":{"tarball":"t"}}`, Options{}}, + "versions array": {`{"name":"demo","versions":[{"a":1}]}`, Options{}}, + "versions null": {`{"name":"demo","versions":null}`, Options{}}, + "pushed versions": {`{"versions":{}}`, Options{LocalVersions: []LocalVersion{{Version: "1.0.0", Entry: []byte(`{}`)}}}}, + } { + t.Run(name, func(t *testing.T) { + var out bytes.Buffer + scan, err := ScanPackument(strings.NewReader(tc.doc)) + if err != nil { + t.Fatal(err) + } + if _, err := RewriteStream("demo", scan, strings.NewReader(tc.doc), &out, tc.options); !errors.Is(err, ErrNotStreamable) { + t.Errorf("err = %v, want ErrNotStreamable", err) + } + if out.Len() != 0 { + t.Errorf("wrote %q before refusing", out.String()) + } + }) + } +} + +func TestScanPackument(t *testing.T) { + for _, body := range []string{`{"versions": {}`, `[1]`, `{"versions": {}} trailing`, `{"a":}`, ``} { + if _, err := ScanPackument(strings.NewReader(body)); err == nil { + t.Errorf("ScanPackument(%q): expected an error", body) + } + } + for body, want := range map[string]bool{ + `{"name":"demo","modified":"2024-01-01T00:00:00Z","versions":{}}`: true, + `{"name":"demo","modified":"2024-01-01T00:00:00Z","time":{},"versions":{}}`: false, + `{"name":"demo","versions":{}}`: false, + } { + scan, err := ScanPackument(strings.NewReader(body)) + if err != nil { + t.Fatal(err) + } + if scan.Abbreviated() != want || Abbreviated([]byte(body)) != want { + t.Errorf("Abbreviated(%s) = %v, want %v", body, scan.Abbreviated(), want) + } + } +} + +// TestVersionStreamMatchesVersion checks that a single version resolved from +// the stream is the one Version serves, with the same errors. +func TestVersionStreamMatchesVersion(t *testing.T) { + docs, options := streamCases() + specifiers := []string{"latest", "beta", "next", "old", "1.0.0", "2.0.0", "3.0.0", "9.0.0", "missing"} + for docName, doc := range docs { + scan, err := ScanPackument(strings.NewReader(doc)) + if err != nil { + t.Fatalf("%s: %v", docName, err) + } + for optName, opts := range options { + for _, spec := range specifiers { + want, wantErr := Version("demo", spec, []byte(doc), opts) + got, gotErr := VersionStream("demo", spec, scan, strings.NewReader(doc), opts) + name := docName + "/" + optName + "/" + spec + switch { + case wantErr != nil || gotErr != nil: + if !errors.Is(gotErr, ErrVersionDenied) == errors.Is(wantErr, ErrVersionDenied) || + !errors.Is(gotErr, ErrVersionNotFound) == errors.Is(wantErr, ErrVersionNotFound) || + (gotErr == nil) != (wantErr == nil) { + t.Errorf("%s: error %v, Version gave %v", name, gotErr, wantErr) + } + case !bytes.Equal(got, want): + t.Errorf("%s:\n%s\nVersion:\n%s", name, got, want) + } + } + } + } +} + +func TestLookupVersion(t *testing.T) { + doc := `{"modified":"x","versions":{"1.0.0":{"a":1}},"time":{"1.0.0":"2020-01-01T00:00:00Z","2.0.0":7},` + + `"versions":{"1.0.0":{"a":2},"2.0.0":{"b":1}}}` + for version, want := range map[string]VersionEntry{ + "1.0.0": {Entry: json.RawMessage(`{"a":2}`), Published: "2020-01-01T00:00:00Z"}, + "2.0.0": {Entry: json.RawMessage(`{"b":1}`)}, + "3.0.0": {}, + } { + got, err := LookupVersion(strings.NewReader(doc), version) + if err != nil { + t.Fatal(err) + } + if string(got.Entry) != string(want.Entry) || got.Published != want.Published || got.Abbreviated { + t.Errorf("LookupVersion(%s) = %+v, want %+v", version, got, want) + } + } + got, err := LookupVersion(strings.NewReader(`{"modified":"x","versions":{}}`), "1.0.0") + if err != nil || !got.Abbreviated { + t.Errorf("abbreviated packument: %+v, %v", got, err) + } + if _, err := LookupVersion(strings.NewReader(`{"versions":{}`), "1.0.0"); err == nil { + t.Error("expected an error for truncated JSON") + } +} + +// TestStreamReadsJSONAsEncodingJSON checks what the streaming readers accept +// matches what Rewrite's encoding/json does: names repeated at any depth, +// invalid UTF-8 in strings, and a version entry's bytes kept as they are. +func TestStreamReadsJSONAsEncodingJSON(t *testing.T) { + entry := "{ \"name\" : \"demo\",\n \"x\":1, \"x\":2, \"note\":\"caf\xe9\" }" + doc := "{\"readme\":\"bad \xff byte\",\"meta\":{\"k\":1,\"k\":2},\"dist-tags\":{\"latest\":\"0.9.0\",\"latest\":\"1.0.0\"}," + + "\"versions\":{\"1.0.0\":" + entry + "},\"time\":{\"1.0.0\":\"2020-01-01T00:00:00Z\"}}\n" + if !json.Valid([]byte(strings.ToValidUTF8(doc, "?"))) { + t.Fatal("test document isn't JSON") + } + + scan, err := ScanPackument(strings.NewReader(doc)) + if err != nil { + t.Fatalf("ScanPackument: %v", err) + } + if !slices.Equal(scan.versions, []string{"1.0.0"}) || !reflect.DeepEqual(scan.distTags, map[string]any{"latest": "1.0.0"}) { + t.Errorf("scan versions %v, dist-tags %v", scan.versions, scan.distTags) + } + + got, err := LookupVersion(strings.NewReader(doc), "1.0.0") + if err != nil { + t.Fatalf("LookupVersion: %v", err) + } + if string(got.Entry) != entry || got.Published != "2020-01-01T00:00:00Z" { + t.Errorf("entry %q, published %q; want the entry's bytes %q", got.Entry, got.Published, entry) + } +} diff --git a/internal/metrics/failures.go b/internal/metrics/failures.go index 425ba8e..a5f276b 100644 --- a/internal/metrics/failures.go +++ b/internal/metrics/failures.go @@ -82,15 +82,6 @@ func recordFailure(name string, labels map[string]string, detail FailureDetail) recentFailures.series[key] = stored } -// ResetRecentFailures empties the recent failure history. The history is -// process-wide, so tests that record or read failures call it to start from a -// known state and to leave none behind. -func ResetRecentFailures() { - recentFailures.Lock() - defer recentFailures.Unlock() - recentFailures.series = make(map[string][]Failure) -} - func failureKey(name string, labels map[string]string) string { return name + "{" + labelKey(labels) + "}" } diff --git a/internal/metrics/failures_test.go b/internal/metrics/failures_test.go index 3d6ab88..2301f8b 100644 --- a/internal/metrics/failures_test.go +++ b/internal/metrics/failures_test.go @@ -14,8 +14,13 @@ import ( // reach its assertions. func isolateRecentFailures(t *testing.T) { t.Helper() - ResetRecentFailures() - t.Cleanup(ResetRecentFailures) + reset := func() { + recentFailures.Lock() + defer recentFailures.Unlock() + recentFailures.series = make(map[string][]Failure) + } + reset() + t.Cleanup(reset) } func TestRecentFailuresNewestFirst(t *testing.T) { diff --git a/internal/metrics/metrics.go b/internal/metrics/metrics.go index 5e9e1a6..85eeef4 100644 --- a/internal/metrics/metrics.go +++ b/internal/metrics/metrics.go @@ -35,15 +35,23 @@ var ( CacheHits = prometheus.NewCounterVec( prometheus.CounterOpts{ Name: "proxy_cache_hits_total", - Help: "Total number of cache hits by ecosystem", + Help: "Total number of cache hits by ecosystem and kind (artifact or metadata)", }, - []string{"ecosystem"}, + []string{"ecosystem", "kind"}, ) CacheMisses = prometheus.NewCounterVec( prometheus.CounterOpts{ Name: "proxy_cache_misses_total", - Help: "Total number of cache misses by ecosystem", + Help: "Total number of cache misses by ecosystem and kind (artifact or metadata)", + }, + []string{"ecosystem", "kind"}, + ) + + MetadataServedBytes = prometheus.NewCounterVec( + prometheus.CounterOpts{ + Name: "proxy_metadata_cache_served_bytes_total", + Help: "Total metadata bytes served from the metadata cache, by ecosystem", }, []string{"ecosystem"}, ) @@ -70,6 +78,30 @@ var ( []string{"reason", "ecosystem"}, ) + MetadataEvicted = prometheus.NewCounterVec( + prometheus.CounterOpts{ + Name: "proxy_metadata_evicted_total", + Help: "Total number of cached metadata documents evicted by the size limit, by ecosystem", + }, + []string{"ecosystem"}, + ) + + MetadataExpiredByChangeFeed = prometheus.NewCounterVec( + prometheus.CounterOpts{ + Name: "proxy_metadata_expired_by_change_feed_total", + Help: "Cached metadata documents set to revalidate because an upstream change feed listed them, by ecosystem", + }, + []string{"ecosystem"}, + ) + + FetchLeaseWaits = prometheus.NewCounterVec( + prometheus.CounterOpts{ + Name: "proxy_fetch_lease_waits_total", + Help: "Cache misses that waited for another instance's upstream fetch, by kind (artifact or metadata)", + }, + []string{"kind"}, + ) + // Upstream metrics UpstreamFetchDuration = prometheus.NewHistogramVec( prometheus.HistogramOpts{ @@ -139,6 +171,14 @@ var ( }, ) + ArtifactsServedUncached = prometheus.NewCounterVec( + prometheus.CounterOpts{ + Name: "proxy_artifacts_served_uncached_total", + Help: "Artifacts sent to the client on a cache miss that could not be cached, such as when storage is full", + }, + []string{"ecosystem"}, + ) + IntegrityFailures = prometheus.NewCounterVec( prometheus.CounterOpts{ Name: "proxy_integrity_failures_total", @@ -206,6 +246,24 @@ var ( []string{"ecosystem"}, ) + // Metadata cache gauges, derived from the metadata_cache table on the + // same tick as the per-ecosystem gauges above. + MetadataCacheSize = prometheus.NewGaugeVec( + prometheus.GaugeOpts{ + Name: "proxy_metadata_cache_size_bytes", + Help: "Size of cached metadata documents per ecosystem in bytes", + }, + []string{"ecosystem"}, + ) + + MetadataCacheEntries = prometheus.NewGaugeVec( + prometheus.GaugeOpts{ + Name: "proxy_metadata_cache_entries", + Help: "Number of cached metadata documents per ecosystem", + }, + []string{"ecosystem"}, + ) + ResponseBytes = prometheus.NewCounterVec( prometheus.CounterOpts{ Name: "proxy_response_bytes_total", @@ -264,9 +322,13 @@ func init() { RequestDuration, CacheHits, CacheMisses, + MetadataServedBytes, CacheSize, CachedArtifacts, ArtifactsEvicted, + MetadataEvicted, + MetadataExpiredByChangeFeed, + FetchLeaseWaits, UpstreamFetchDuration, UpstreamErrors, CircuitBreakerState, @@ -274,6 +336,7 @@ func init() { UpstreamRateLimitHolds, StorageOperationDuration, StorageErrors, + ArtifactsServedUncached, ActiveRequests, IntegrityFailures, HealthProbeFailures, @@ -283,6 +346,8 @@ func init() { EcosystemCachedArtifacts, EcosystemPackages, EcosystemVersions, + MetadataCacheSize, + MetadataCacheEntries, ResponseBytes, ClientRequests, ClientResponseBytes, @@ -322,9 +387,27 @@ func RecordResponse(ecosystem, client string, bytes int64) { ClientResponseBytes.WithLabelValues(client).Add(float64(bytes)) } -// RecordCacheHit increments cache hit counter. -func RecordCacheHit(ecosystem string) { - CacheHits.WithLabelValues(purl.NormalizeEcosystem(ecosystem)).Inc() +// Values of the kind label on proxy_cache_hits_total and +// proxy_cache_misses_total. Artifacts and metadata are separate caches with +// very different costs, so a hit on one says nothing about the other. +const ( + CacheKindArtifact = "artifact" + CacheKindMetadata = "metadata" +) + +// RecordArtifactCacheHit counts an artifact served from storage. +func RecordArtifactCacheHit(ecosystem string) { + CacheHits.WithLabelValues(purl.NormalizeEcosystem(ecosystem), CacheKindArtifact).Inc() +} + +// RecordMetadataCacheHit counts a metadata document served from the metadata +// cache, along with the bytes it served. +func RecordMetadataCacheHit(ecosystem string, bytes int) { + ecosystem = purl.NormalizeEcosystem(ecosystem) + CacheHits.WithLabelValues(ecosystem, CacheKindMetadata).Inc() + if bytes > 0 { + MetadataServedBytes.WithLabelValues(ecosystem).Add(float64(bytes)) + } } // RecordArtifactEvicted counts one evicted artifact. ecosystem is the @@ -337,9 +420,34 @@ func RecordArtifactEvicted(reason, ecosystem string) { ArtifactsEvicted.WithLabelValues(reason, purl.NormalizeEcosystem(ecosystem)).Inc() } -// RecordCacheMiss increments cache miss counter. -func RecordCacheMiss(ecosystem string) { - CacheMisses.WithLabelValues(purl.NormalizeEcosystem(ecosystem)).Inc() +// RecordMetadataEvicted counts one metadata document evicted by the size +// limit. ecosystem is the metadata cache's, normalized like the cache hit +// counter. +func RecordMetadataEvicted(ecosystem string) { + MetadataEvicted.WithLabelValues(purl.NormalizeEcosystem(ecosystem)).Inc() +} + +// RecordMetadataExpiredByChangeFeed counts n metadata documents an upstream +// change feed listed as changed. ecosystem is the metadata cache's, +// normalized like the cache hit counter. +func RecordMetadataExpiredByChangeFeed(ecosystem string, n int) { + MetadataExpiredByChangeFeed.WithLabelValues(purl.NormalizeEcosystem(ecosystem)).Add(float64(n)) +} + +// RecordFetchLeaseWait counts a cache miss that found another instance +// sharing the database already fetching it. +func RecordFetchLeaseWait(kind string) { + FetchLeaseWaits.WithLabelValues(kind).Inc() +} + +// RecordArtifactCacheMiss counts an artifact that had to be fetched upstream. +func RecordArtifactCacheMiss(ecosystem string) { + CacheMisses.WithLabelValues(purl.NormalizeEcosystem(ecosystem), CacheKindArtifact).Inc() +} + +// RecordMetadataCacheMiss counts a metadata lookup the cache could not serve. +func RecordMetadataCacheMiss(ecosystem string) { + CacheMisses.WithLabelValues(purl.NormalizeEcosystem(ecosystem), CacheKindMetadata).Inc() } // RecordUpstreamFetch tracks upstream fetch duration. @@ -382,6 +490,14 @@ func RecordStorageError(operation string, detail FailureDetail) { recordFailure("proxy_storage_errors_total", map[string]string{"operation": operation}, detail) } +// RecordArtifactServedUncached counts an artifact a client got on a cache +// miss although storing it failed, and keeps the detail for /ui/analytics. +func RecordArtifactServedUncached(ecosystem string, detail FailureDetail) { + ecosystem = purl.NormalizeEcosystem(ecosystem) + ArtifactsServedUncached.WithLabelValues(ecosystem).Inc() + recordFailure("proxy_artifacts_served_uncached_total", map[string]string{"ecosystem": ecosystem}, detail) +} + // RecordScanResult tracks a completed pre-cache scan call. func RecordScanResult(ecosystem, scannerName string, allowed bool, duration time.Duration) { ecosystem = purl.NormalizeEcosystem(ecosystem) @@ -423,6 +539,8 @@ type EcosystemStats struct { var ( publishedMu sync.Mutex publishedEcosystems = map[string]bool{} + // publishedMetadataEcosystems does the same for the metadata cache gauges. + publishedMetadataEcosystems = map[string]bool{} ) // UpdateEcosystemStats republishes the per-ecosystem gauges from a fresh snapshot. @@ -480,6 +598,48 @@ func UpdateEcosystemStats(stats []EcosystemStats) { } } +// MetadataCacheStats is one ecosystem's share of the metadata cache. +type MetadataCacheStats struct { + Ecosystem string + Entries int64 + Size int64 +} + +// UpdateMetadataCacheStats republishes the metadata cache gauges from a fresh +// snapshot. Like UpdateEcosystemStats it sums rows by normalized label, sets +// each series in place and deletes only labels that have disappeared. +func UpdateMetadataCacheStats(stats []MetadataCacheStats) { + totals := make(map[string]MetadataCacheStats, len(stats)) + for _, s := range stats { + ecosystem := purl.NormalizeEcosystem(s.Ecosystem) + t := totals[ecosystem] + t.Entries += s.Entries + t.Size += s.Size + totals[ecosystem] = t + } + + for ecosystem, t := range totals { + MetadataCacheEntries.WithLabelValues(ecosystem).Set(float64(t.Entries)) + MetadataCacheSize.WithLabelValues(ecosystem).Set(float64(t.Size)) + } + + publishedMu.Lock() + defer publishedMu.Unlock() + + for ecosystem := range publishedMetadataEcosystems { + if _, still := totals[ecosystem]; still { + continue + } + MetadataCacheEntries.DeleteLabelValues(ecosystem) + MetadataCacheSize.DeleteLabelValues(ecosystem) + } + + publishedMetadataEcosystems = make(map[string]bool, len(totals)) + for ecosystem := range totals { + publishedMetadataEcosystems[ecosystem] = true + } +} + // UpdateCircuitBreakerState updates circuit breaker state gauge. // state: 0=closed, 1=half-open, 2=open func UpdateCircuitBreakerState(registry string, state int) { diff --git a/internal/metrics/metrics_test.go b/internal/metrics/metrics_test.go index 8259d3e..25ae1cd 100644 --- a/internal/metrics/metrics_test.go +++ b/internal/metrics/metrics_test.go @@ -21,10 +21,11 @@ func TestRecordRequest(t *testing.T) { } func TestRecordCacheOperations(t *testing.T) { - RecordCacheHit("npm") - RecordCacheHit("npm") - RecordCacheMiss("npm") - RecordCacheMiss("pypi") + RecordArtifactCacheHit("npm") + RecordArtifactCacheHit("npm") + RecordArtifactCacheMiss("npm") + RecordMetadataCacheHit("pypi", 128) + RecordMetadataCacheMiss("pypi") // No panics = success } @@ -114,9 +115,9 @@ func TestMetricsAreRegistered(t *testing.T) { func TestCacheHitRatio(t *testing.T) { // Reset by recording some hits and misses - RecordCacheHit("test") - RecordCacheHit("test") - RecordCacheMiss("test") + RecordArtifactCacheHit("test") + RecordArtifactCacheHit("test") + RecordArtifactCacheMiss("test") // Collect metrics hits := getMetricValue(t, CacheHits, "test") @@ -179,7 +180,7 @@ func getMetricValue(t *testing.T, collector prometheus.Collector, labelValue str func TestMetricsEndpointOutput(t *testing.T) { // Record some test metrics RecordRequest("npm", 200, 50*time.Millisecond) - RecordCacheHit("npm") + RecordArtifactCacheHit("npm") UpdateCacheStats(1024*1024, 10) // Get the handler and check it produces output @@ -207,7 +208,7 @@ func TestMetricsLabeling(t *testing.T) { for _, eco := range ecosystems { RecordRequest(eco.input, 200, 10*time.Millisecond) - RecordCacheHit(eco.input) + RecordArtifactCacheHit(eco.input) } // Verify each ecosystem has metrics @@ -220,18 +221,93 @@ func TestMetricsLabeling(t *testing.T) { } func TestCacheMetricLabelsAreNormalized(t *testing.T) { - rubyHitsBefore := testutil.ToFloat64(CacheHits.WithLabelValues("rubygems")) - composerMissesBefore := testutil.ToFloat64(CacheMisses.WithLabelValues("packagist")) + rubyHitsBefore := testutil.ToFloat64(CacheHits.WithLabelValues("rubygems", CacheKindArtifact)) + composerMissesBefore := testutil.ToFloat64(CacheMisses.WithLabelValues("packagist", CacheKindArtifact)) + goMetadataHitsBefore := testutil.ToFloat64(CacheHits.WithLabelValues("golang", CacheKindMetadata)) + goServedBefore := testutil.ToFloat64(MetadataServedBytes.WithLabelValues("golang")) - RecordCacheHit("gem") - RecordCacheMiss("composer") + RecordArtifactCacheHit("gem") + RecordArtifactCacheMiss("composer") + RecordMetadataCacheHit("go", 10) - if diff := testutil.ToFloat64(CacheHits.WithLabelValues("rubygems")) - rubyHitsBefore; diff != 1 { + if diff := testutil.ToFloat64(CacheHits.WithLabelValues("rubygems", CacheKindArtifact)) - rubyHitsBefore; diff != 1 { t.Errorf("rubygems cache hits delta = %.0f, want 1", diff) } - if diff := testutil.ToFloat64(CacheMisses.WithLabelValues("packagist")) - composerMissesBefore; diff != 1 { + if diff := testutil.ToFloat64(CacheMisses.WithLabelValues("packagist", CacheKindArtifact)) - composerMissesBefore; diff != 1 { t.Errorf("packagist cache misses delta = %.0f, want 1", diff) } + if diff := testutil.ToFloat64(CacheHits.WithLabelValues("golang", CacheKindMetadata)) - goMetadataHitsBefore; diff != 1 { + t.Errorf("golang metadata hits delta = %.0f, want 1", diff) + } + if diff := testutil.ToFloat64(MetadataServedBytes.WithLabelValues("golang")) - goServedBefore; diff != 10 { + t.Errorf("golang metadata served bytes delta = %.0f, want 10", diff) + } +} + +// TestCacheKindsAreCountedApart checks an artifact hit and a metadata hit land +// in different series. Only metadata hits add served bytes. +func TestCacheKindsAreCountedApart(t *testing.T) { + const eco = "kind-test" + artifactHits := func() float64 { return testutil.ToFloat64(CacheHits.WithLabelValues(eco, CacheKindArtifact)) } + metadataHits := func() float64 { return testutil.ToFloat64(CacheHits.WithLabelValues(eco, CacheKindMetadata)) } + artifactMisses := func() float64 { return testutil.ToFloat64(CacheMisses.WithLabelValues(eco, CacheKindArtifact)) } + metadataMisses := func() float64 { return testutil.ToFloat64(CacheMisses.WithLabelValues(eco, CacheKindMetadata)) } + served := func() float64 { return testutil.ToFloat64(MetadataServedBytes.WithLabelValues(eco)) } + + aHits, mHits, aMisses, mMisses, bytes := artifactHits(), metadataHits(), artifactMisses(), metadataMisses(), served() + + RecordArtifactCacheHit(eco) + RecordMetadataCacheHit(eco, 300) + RecordMetadataCacheHit(eco, 0) + RecordMetadataCacheMiss(eco) + + checks := []struct { + name string + got, want float64 + }{ + {"artifact hits", artifactHits() - aHits, 1}, + {"metadata hits", metadataHits() - mHits, 2}, + {"artifact misses", artifactMisses() - aMisses, 0}, + {"metadata misses", metadataMisses() - mMisses, 1}, + {"metadata served bytes", served() - bytes, 300}, + } + for _, c := range checks { + if c.got != c.want { + t.Errorf("%s delta = %.0f, want %.0f", c.name, c.got, c.want) + } + } +} + +func TestUpdateMetadataCacheStats(t *testing.T) { + UpdateMetadataCacheStats([]MetadataCacheStats{ + {Ecosystem: "gem", Entries: 2, Size: 100}, + {Ecosystem: "rubygems", Entries: 3, Size: 50}, + {Ecosystem: "npm", Entries: 1, Size: 10}, + }) + + if got := testutil.ToFloat64(MetadataCacheEntries.WithLabelValues("rubygems")); got != 5 { + t.Errorf("rubygems entries = %.0f, want 5 (aliases summed)", got) + } + if got := testutil.ToFloat64(MetadataCacheSize.WithLabelValues("rubygems")); got != 150 { + t.Errorf("rubygems size = %.0f, want 150 (aliases summed)", got) + } + if got := testutil.CollectAndCount(MetadataCacheSize); got != 2 { + t.Errorf("size series = %d, want 2", got) + } + + UpdateMetadataCacheStats([]MetadataCacheStats{{Ecosystem: "npm", Entries: 4, Size: 40}}) + + if got := testutil.CollectAndCount(MetadataCacheSize); got != 1 { + t.Errorf("size series after rubygems disappeared = %d, want 1", got) + } + if got := testutil.CollectAndCount(MetadataCacheEntries); got != 1 { + t.Errorf("entry series after rubygems disappeared = %d, want 1", got) + } + if got := testutil.ToFloat64(MetadataCacheSize.WithLabelValues("npm")); got != 40 { + t.Errorf("npm size = %.0f, want 40", got) + } + + UpdateMetadataCacheStats(nil) } func TestMetricNames(t *testing.T) { @@ -241,6 +317,9 @@ func TestMetricNames(t *testing.T) { "proxy_request_duration_seconds", "proxy_cache_hits_total", "proxy_cache_misses_total", + "proxy_metadata_cache_served_bytes_total", + "proxy_metadata_cache_size_bytes", + "proxy_metadata_cache_entries", "proxy_upstream_fetch_duration_seconds", "proxy_upstream_errors_total", "proxy_storage_operation_duration_seconds", diff --git a/internal/metrics/snapshot.go b/internal/metrics/snapshot.go index 6ac66fb..2c96dff 100644 --- a/internal/metrics/snapshot.go +++ b/internal/metrics/snapshot.go @@ -94,20 +94,6 @@ func sampleOf(m *dto.Metric) Sample { return s } -// Names returns the name of every metric family in the snapshot, sorted. -func (s *Snapshot) Names() []string { - if s == nil { - return nil - } - - names := make([]string, 0, len(s.families)) - for name := range s.families { - names = append(names, name) - } - sort.Strings(names) - return names -} - // Samples returns every series of a metric, or nil when it has never been // observed. Series are ordered by their label values so that rendering is // stable between scrapes. diff --git a/internal/metrics/snapshot_test.go b/internal/metrics/snapshot_test.go index 1a20906..5b6c7fd 100644 --- a/internal/metrics/snapshot_test.go +++ b/internal/metrics/snapshot_test.go @@ -125,7 +125,7 @@ func TestSnapshotMissingMetric(t *testing.T) { // come back. This is the check that a newly added metric is reachable by the UI. func TestGatherSeesRegisteredMetrics(t *testing.T) { isolateRecentFailures(t) - RecordCacheHit("npm") + RecordArtifactCacheHit("npm") RecordScanError("npm", "clamav", "timeout", FailureDetail{}) snap, err := Gather() diff --git a/internal/mirror/apk.go b/internal/mirror/apk.go new file mode 100644 index 0000000..30a9771 --- /dev/null +++ b/internal/mirror/apk.go @@ -0,0 +1,154 @@ +package mirror + +import ( + "context" + "errors" + "fmt" + "regexp" + "strings" + "sync" + "time" + + "github.com/git-pkgs/proxy/internal/handler" + "github.com/git-pkgs/registries" +) + +// apkIndexTTL is how long a repository's APKINDEX is reused, so mirroring +// the packages of an image reads each index once. +const apkIndexTTL = 5 * time.Minute + +var ( + // apkDistroPattern takes the release from syft's distro qualifier, such + // as alpine-3.20.3 for v3.20. Edge, as alpine-3.21.0_alpha20240807, + // isn't a release and doesn't match. + apkDistroPattern = regexp.MustCompile(`^alpine-(\d+)\.(\d+)(?:\.\d+)?$`) + apkArchPattern = regexp.MustCompile(`^[a-z0-9_]+$`) + // apkComponents are the repositories of a release a package is looked + // up in, in order. + apkComponents = []string{"main", "community"} +) + +// apkIndexes keeps one registries client per repository directory, which +// holds the parsed APKINDEX. +type apkIndexes struct { + mu sync.Mutex + regs map[string]apkIndex +} + +type apkIndex struct { + reg registries.Registry + fetched time.Time +} + +// mirrorAPK mirrors an Alpine package under the path the handler caches it +// at, {repository}/v{release}/{component}/{arch}/{file}. The PURL namespace +// names the upstream.apk repository; the distro and arch qualifiers give +// the release and architecture, and the package is looked up in the main +// and community indexes of that release. +func (m *Mirror) mirrorAPK(ctx context.Context, pv PackageVersion, tracker *progressTracker) { + fail := func(err error) { m.recordFailure(tracker, pv, err) } + repository, name := pv.Namespace, pv.Name + if repository == "" { + repository = "alpine" + } + repositoryURL, ok := handler.APKRepositories(m.APKRepositories)[repository] + if !ok { + fail(fmt.Errorf("unknown APK repository %q: it isn't in upstream.apk", repository)) + return + } + match := apkDistroPattern.FindStringSubmatch(pv.Qualifiers["distro"]) + if match == nil { + fail(fmt.Errorf("apk packages need a distro qualifier with the Alpine release, such as distro=alpine-3.20.3, not %q", pv.Qualifiers["distro"])) + return + } + release := "v" + match[1] + "." + match[2] + arch := pv.Qualifiers["arch"] + if !apkArchPattern.MatchString(arch) { + fail(fmt.Errorf("apk packages need an arch qualifier, such as arch=x86_64, not %q", arch)) + return + } + + for _, component := range apkComponents { + dir := release + "/" + component + "/" + arch + artifact, found, err := m.apkArtifact(ctx, repositoryURL+"/"+dir, name, pv.Version) + if err != nil { + fail(fmt.Errorf("reading %s %s/APKINDEX.tar.gz: %w", repository, dir, err)) + return + } + if !found { + continue + } + cacheFilename := handler.APKCacheFilename(repository, dir+"/"+artifact.Filename) + result, err := m.proxy.GetOrFetchArtifactFromURL(ctx, pv.Ecosystem, name, pv.Version, cacheFilename, artifact.URL) + if err != nil { + fail(err) + return + } + m.recordResult(tracker, pv, result) + return + } + fail(fmt.Errorf("%s %s isn't in %s of %s %s for %s", name, pv.Version, strings.Join(apkComponents, " or "), repository, release, arch)) +} + +// apkArtifact returns the file of version of name that the index in dirURL +// lists, and whether it lists one. +func (m *Mirror) apkArtifact(ctx context.Context, dirURL, name, version string) (registries.Artifact, bool, error) { + reg, err := m.apkRegistry(dirURL) + if err != nil { + return registries.Artifact{}, false, err + } + versions, err := reg.FetchVersions(ctx, name) + if isNotFound(err) { + return registries.Artifact{}, false, nil + } + if err != nil { + m.apk.forget(dirURL) + return registries.Artifact{}, false, err + } + for _, v := range versions { + if v.Number == version && len(v.Artifacts) > 0 { + return v.Artifacts[0], true, nil + } + } + return registries.Artifact{}, false, nil +} + +// apkRegistry returns the client for the repository directory at dirURL, +// reusing it, and the index it read, for apkIndexTTL. +func (m *Mirror) apkRegistry(dirURL string) (registries.Registry, error) { //nolint:ireturn // registries.New returns the interface + m.apk.mu.Lock() + defer m.apk.mu.Unlock() + if idx, ok := m.apk.regs[dirURL]; ok && time.Since(idx.fetched) < apkIndexTTL { + return idx.reg, nil + } + r, _ := m.Versions.(RegistryVersions) + // Naming the v2 index reads it also where Packages.adb is served beside + // it, which the client would try first and refuse. + reg, err := registries.New("apk", dirURL+"/APKINDEX.tar.gz", r.client()) + if err != nil { + return nil, err + } + if m.apk.regs == nil { + m.apk.regs = map[string]apkIndex{} + } + m.apk.regs[dirURL] = apkIndex{reg: reg, fetched: time.Now()} + return reg, nil +} + +// forget drops the client for dirURL, so an index that failed to load is +// read again next time. +func (a *apkIndexes) forget(dirURL string) { + a.mu.Lock() + defer a.mu.Unlock() + delete(a.regs, dirURL) +} + +// isNotFound reports whether err means a package or index doesn't exist, +// such as a release without a community repository for an architecture. +func isNotFound(err error) bool { + if errors.Is(err, registries.ErrNotFound) { + return true + } + var httpErr *registries.HTTPError + return errors.As(err, &httpErr) && httpErr.IsNotFound() +} diff --git a/internal/mirror/brew_test.go b/internal/mirror/brew_test.go new file mode 100644 index 0000000..80e5a26 --- /dev/null +++ b/internal/mirror/brew_test.go @@ -0,0 +1,95 @@ +package mirror + +import ( + "context" + "errors" + "strings" + "sync" + "testing" + + "github.com/git-pkgs/proxy/internal/handler" +) + +// fakeBottles resolves every formula version to homebrew/core/ tagged +// -1, like a formula whose bottles were rebuilt once. +type fakeBottles struct { + err error +} + +func (f fakeBottles) BottleImage(_ context.Context, formula, version string) (handler.ImageRef, error) { + if f.err != nil { + return handler.ImageRef{}, f.err + } + return handler.ImageRef{Name: "homebrew/core/" + formula, References: []string{version + "-1"}}, nil +} + +// platformImages records the images mirrored and the platforms asked for. +type platformImages struct { + mu sync.Mutex + refs []handler.ImageRef + platforms [][]handler.Platform +} + +func (p *platformImages) MirrorImage(_ context.Context, ref handler.ImageRef, platforms []handler.Platform) (handler.ImageResult, error) { + p.mu.Lock() + defer p.mu.Unlock() + p.refs = append(p.refs, ref) + p.platforms = append(p.platforms, platforms) + return handler.ImageResult{Fetched: 2, Bytes: 10}, nil +} + +type stubVersions map[string][]string + +func (s stubVersions) ListVersions(_ context.Context, ecosystem, name string) ([]string, error) { + return s[ecosystem+"/"+name], nil +} + +func TestMirrorBrewMirrorsBottleImage(t *testing.T) { + m := setupTestMirror(t, 1) + images := &platformImages{} + m.Images, m.Bottles = images, fakeBottles{} + + source := &PURLSource{ + PURLs: []string{"pkg:brew/hello@2.12.3", "pkg:brew/jq"}, + Platforms: []string{"linux/arm64"}, + Versions: stubVersions{"brew/jq": {"1.8.1"}}, + } + progress, err := m.Run(context.Background(), source) + if err != nil { + t.Fatal(err) + } + if progress.Completed != 2 || progress.Failed != 0 { + t.Fatalf("progress = %+v, errors %v", progress, progress.Errors) + } + got := map[string]string{} + for i, ref := range images.refs { + if len(images.platforms[i]) != 1 || images.platforms[i][0].OS != "linux" || images.platforms[i][0].Architecture != "arm64" { + t.Errorf("%s: platforms = %+v, want linux/arm64", ref.Name, images.platforms[i]) + } + got[ref.Name] = strings.Join(ref.References, ",") + } + if got["homebrew/core/hello"] != "2.12.3-1" || got["homebrew/core/jq"] != "1.8.1-1" { + t.Errorf("images = %v", got) + } +} + +func TestMirrorBrewFailures(t *testing.T) { + m := setupTestMirror(t, 1) + progress, err := m.Run(context.Background(), &PURLSource{PURLs: []string{"pkg:brew/hello@2.12.3"}}) + if err != nil { + t.Fatal(err) + } + if progress.Failed != 1 || len(progress.Errors) != 1 || !strings.Contains(progress.Errors[0].Error, "isn't available") { + t.Errorf("without a bottle resolver: %+v", progress) + } + + images := &platformImages{} + m.Images, m.Bottles = images, fakeBottles{err: errors.New(`homebrew/core has no formula "nope"`)} + progress, err = m.Run(context.Background(), &PURLSource{PURLs: []string{"pkg:brew/nope@1.0"}}) + if err != nil { + t.Fatal(err) + } + if progress.Failed != 1 || len(images.refs) != 0 { + t.Errorf("unknown formula: %+v, mirrored %v", progress, images.refs) + } +} diff --git a/internal/mirror/cran.go b/internal/mirror/cran.go new file mode 100644 index 0000000..02d26bd --- /dev/null +++ b/internal/mirror/cran.go @@ -0,0 +1,191 @@ +package mirror + +import ( + "bufio" + "bytes" + "compress/gzip" + "context" + "fmt" + "io" + "net/url" + "regexp" + "strings" + "sync" + "time" + + "github.com/git-pkgs/registries" +) + +const ( + cranDefaultURL = "https://cloud.r-project.org" + // cranIndexTTL is how long a fetched src/contrib/PACKAGES is reused, so + // mirroring many packages, or every version of one, reads it once. + cranIndexTTL = 5 * time.Minute + // cranMaxIndexSize limits the decompressed PACKAGES. + // CRAN's PACKAGES is about 7 MB. + cranMaxIndexSize = 64 << 20 + // cranMaxLine limits a line of PACKAGES. + cranMaxLine = 1 << 20 +) + +var ( + cranNamePattern = regexp.MustCompile(`^[A-Za-z][A-Za-z0-9.]*$`) + cranVersionPattern = regexp.MustCompile(`^[0-9]+[0-9.-]*$`) +) + +// cranIndex caches the MD5 sums src/contrib/PACKAGES lists for the current +// source packages of a CRAN repository, by file name. +type cranIndex struct { + mu sync.Mutex + baseURL string + fetched time.Time + md5s map[string]string +} + +// mirrorCRAN mirrors a CRAN source package under ("cran", name, version, +// name_version.tar.gz), the one entry the handler serves for both +// src/contrib and src/contrib/Archive. +func (m *Mirror) mirrorCRAN(ctx context.Context, pv PackageVersion, tracker *progressTracker) { + fail := func(err error) { m.recordFailure(tracker, pv, err) } + if !cranNamePattern.MatchString(pv.Name) { + fail(fmt.Errorf("invalid CRAN package name %q", pv.Name)) + return + } + if !cranVersionPattern.MatchString(pv.Version) { + fail(fmt.Errorf("invalid CRAN version %q", pv.Version)) + return + } + baseURL, client, err := m.cranRepository(pv.Name) + if err != nil { + fail(err) + return + } + filename := pv.Name + "_" + pv.Version + ".tar.gz" + + current, err := m.cranCurrentMD5s(ctx, baseURL, client) + if err != nil { + fail(fmt.Errorf("reading src/contrib/PACKAGES: %w", err)) + return + } + downloadURL := baseURL + "/src/contrib/" + filename + sum, ok := current[filename] + if !ok { + downloadURL = baseURL + "/src/contrib/Archive/" + url.PathEscape(pv.Name) + "/" + filename + } + var declared string + if sum != "" { + declared = "md5-" + sum + } + result, err := m.proxy.GetOrFetchArtifactFromURLWithIntegrity(ctx, pv.Ecosystem, pv.Name, pv.Version, filename, downloadURL, declared) + if err != nil { + fail(err) + return + } + m.recordResult(tracker, pv, result) +} + +// cranRepository returns the repository to mirror a CRAN package from and +// the client to read its indexes with: those Versions lists versions with, +// which come from upstream.cran, or the public CRAN. +func (m *Mirror) cranRepository(name string) (string, *registries.Client, error) { + r, _ := m.Versions.(RegistryVersions) + baseURL := cranDefaultURL + if r.URL != nil { + configured, err := r.URL("cran", name) + if err != nil { + return "", nil, err + } + if configured != "" { + baseURL = strings.TrimSuffix(configured, "/") + } + } + client := r.Client + if client == nil { + client = registries.DefaultClient() + } + return baseURL, client, nil +} + +// cranCurrentMD5s returns the MD5 sums of the current source packages of the +// repository at baseURL, reading src/contrib/PACKAGES.gz unless it was read +// within cranIndexTTL. +func (m *Mirror) cranCurrentMD5s(ctx context.Context, baseURL string, client *registries.Client) (map[string]string, error) { + m.cran.mu.Lock() + defer m.cran.mu.Unlock() + if m.cran.md5s != nil && m.cran.baseURL == baseURL && time.Since(m.cran.fetched) < cranIndexTTL { + return m.cran.md5s, nil + } + body, err := client.GetBody(ctx, baseURL+"/src/contrib/PACKAGES.gz") + if err != nil { + return nil, err + } + data, err := gunzipLimited(body) + if err != nil { + return nil, err + } + sums, err := parseCRANPackages(data) + if err != nil { + return nil, err + } + m.cran.md5s = sums + m.cran.baseURL = baseURL + m.cran.fetched = time.Now() + return m.cran.md5s, nil +} + +// gunzipLimited decompresses data, or returns it as is when it isn't +// gzipped. +func gunzipLimited(data []byte) ([]byte, error) { + if !bytes.HasPrefix(data, []byte{0x1f, 0x8b}) { + return data, nil + } + zr, err := gzip.NewReader(bytes.NewReader(data)) + if err != nil { + return nil, err + } + defer func() { _ = zr.Close() }() + out, err := io.ReadAll(io.LimitReader(zr, cranMaxIndexSize+1)) + if err != nil { + return nil, err + } + if len(out) > cranMaxIndexSize { + return nil, fmt.Errorf("index is larger than %d bytes", cranMaxIndexSize) + } + return out, nil +} + +// parseCRANPackages returns the MD5sum of each source package a PACKAGES +// file lists, by file name. Entries without one are listed with "". +func parseCRANPackages(data []byte) (map[string]string, error) { + sums := map[string]string{} + var name, version, sum string + flush := func() { + if name != "" && version != "" { + sums[name+"_"+version+".tar.gz"] = sum + } + name, version, sum = "", "", "" + } + scanner := bufio.NewScanner(bytes.NewReader(data)) + scanner.Buffer(nil, cranMaxLine) + for scanner.Scan() { + line := scanner.Text() + if strings.TrimSpace(line) == "" { + flush() + continue + } + key, value, ok := strings.Cut(line, ":") + if !ok || strings.HasPrefix(line, " ") || strings.HasPrefix(line, "\t") { + continue + } + switch value = strings.TrimSpace(value); key { + case "Package": + name = value + case "Version": + version = value + case "MD5sum": + sum = value + } + } + flush() + return sums, scanner.Err() +} diff --git a/internal/mirror/cran_test.go b/internal/mirror/cran_test.go new file mode 100644 index 0000000..3eae797 --- /dev/null +++ b/internal/mirror/cran_test.go @@ -0,0 +1,27 @@ +package mirror + +import ( + "maps" + "testing" +) + +func TestParseCRANPackages(t *testing.T) { + data := []byte(`Package: A3 +Version: 1.0.0 +Depends: R (>= 2.15.0), xtable, + pbapply +MD5sum: 027ebdd8affce8f0effaecfcd5f5ade2 +NeedsCompilation: no + +Package: abc +Version: 2.2.1 +NeedsCompilation: no +`) + want := map[string]string{ + "A3_1.0.0.tar.gz": "027ebdd8affce8f0effaecfcd5f5ade2", + "abc_2.2.1.tar.gz": "", + } + if got, err := parseCRANPackages(data); err != nil || !maps.Equal(got, want) { + t.Errorf("parseCRANPackages = %v, %v, want %v", got, err, want) + } +} diff --git a/internal/mirror/files.go b/internal/mirror/files.go new file mode 100644 index 0000000..ab6bafd --- /dev/null +++ b/internal/mirror/files.go @@ -0,0 +1,206 @@ +package mirror + +import ( + "fmt" + "path" + "regexp" + "slices" + "strings" + + "github.com/git-pkgs/proxy/internal/handler" + "github.com/git-pkgs/registries" +) + +// fileEcosystem describes an ecosystem whose versions publish several files, +// each mirrored on its own. +type fileEcosystem struct { + // qualifiers are the PURL qualifiers that select files. A file is + // mirrored when each one given matches the value attrs reports for it. + qualifiers []string + attrs func(file registries.Artifact) map[string]string + // cacheKey returns the name, version and filename the download handler + // caches file under, or false when the handler would not cache it. + cacheKey func(pv PackageVersion, file registries.Artifact) (name, version, filename string, ok bool) + // check refuses a package the ecosystem can't mirror, before its files + // are listed. + check func(pv PackageVersion) error + // variants name the kinds of a file, such as each tag combination of a + // wheel or a conda package's platform, so a refresh mirrors the same + // kinds of files of a new version as were cached of an old one. + // cachedVariants names them for the filename cacheKey returns. + variants func(file registries.Artifact) []string + cachedVariants func(cacheFilename string) []string +} + +var fileEcosystems = map[string]fileEcosystem{ + "pypi": { + qualifiers: []string{"file_name"}, + attrs: func(file registries.Artifact) map[string]string { + return map[string]string{"file_name": file.Filename} + }, + cacheKey: func(pv PackageVersion, file registries.Artifact) (string, string, string, bool) { + name, version := handler.PyPIFilenameIdentity(file.Filename) + if name == "" { + name, version = pv.Name, pv.Version + } + return name, version, file.Filename, true + }, + variants: func(file registries.Artifact) []string { return pypiVariants(file.Filename) }, + cachedVariants: pypiVariants, + }, + "conda": { + qualifiers: []string{"subdir", "build", "type"}, + attrs: func(file registries.Artifact) map[string]string { + subdir, _ := file.Metadata["subdir"].(string) + build, _ := file.Metadata["build"].(string) + return map[string]string{"subdir": subdir, "build": build, "type": condaFileType(file.Filename)} + }, + cacheKey: func(pv PackageVersion, file registries.Artifact) (string, string, string, bool) { + channel, _, _ := strings.Cut(pv.Name, "/") + subdir, _ := file.Metadata["subdir"].(string) + name, version := handler.CondaFilenameIdentity(file.Filename) + if name == "" || subdir == "" || condaFileType(file.Filename) == "" { + return "", "", "", false + } + return channel + "/" + name, version, subdir + "/" + file.Filename, true + }, + check: func(pv PackageVersion) error { + if !strings.Contains(pv.Name, "/") { + return fmt.Errorf("conda packages need a channel, such as pkg:conda/conda-forge/%s", pv.Name) + } + return nil + }, + variants: func(file registries.Artifact) []string { + subdir, _ := file.Metadata["subdir"].(string) + return []string{condaVariant(subdir, file.Filename)} + }, + cachedVariants: func(cacheFilename string) []string { + subdir, filename := path.Split(cacheFilename) + return []string{condaVariant(strings.TrimSuffix(subdir, "/"), filename)} + }, + }, +} + +// pypiVariants names a wheel by each combination of its python, ABI and +// platform tags, which are alternatives where a tag lists several joined by +// dots, with the platform reduced to OS and architecture. Every sdist is +// one variant. +func pypiVariants(filename string) []string { + stem, wheel := strings.CutSuffix(filename, ".whl") + if !wheel { + return []string{"sdist"} + } + parts := strings.Split(stem, "-") + if len(parts) < 5 { //nolint:mnd // name, version and three tags + return []string{stem} + } + tags := parts[len(parts)-3:] + var variants []string + for _, python := range strings.Split(tags[0], ".") { + for _, abi := range strings.Split(tags[1], ".") { + for _, platform := range strings.Split(tags[2], ".") { + v := wheelPython(python, abi) + "-" + abi + "-" + wheelPlatform(platform) + if !slices.Contains(variants, v) { + variants = append(variants, v) + } + } + } + } + return variants +} + +// wheelPython reduces the python tag of an abi3 wheel, a minimum such as +// cp39, to its interpreter, so cp38-abi3 and cp311-abi3 wheels are the same +// kind. +func wheelPython(python, abi string) string { + if abi != "abi3" { + return python + } + return strings.TrimRight(python, "0123456789") +} + +// wheelPlatformMinimum matches the glibc, musl or macOS minimum version in a +// platform tag, such as the 2_17 in manylinux_2_17_x86_64 or the 2014 in +// manylinux2014_x86_64. +var wheelPlatformMinimum = regexp.MustCompile(`^(manylinux|musllinux|macosx)_?(?:\d+_\d+|1|2010|2014)_`) + +// wheelPlatform reduces a platform tag to OS and architecture, so +// manylinux_2_17_x86_64 and manylinux_2_28_x86_64 name the same platform. +func wheelPlatform(tag string) string { + return wheelPlatformMinimum.ReplaceAllString(tag, "${1}_") +} + +// condaBuildHash matches the hash and build number in a conda build string, +// such as h8753938_0 in py312h8753938_0 or h5f976f7_0 in +// h5f976f7_0_cpython. +var condaBuildHash = regexp.MustCompile(`h[0-9a-f]{7}_\d+`) + +// condaVariant names a conda package file by its subdir, its build string +// without the hash, such as py312 or _cpython, and its type. +func condaVariant(subdir, filename string) string { + fileType := condaFileType(filename) + stem := strings.TrimSuffix(strings.TrimSuffix(filename, ".conda"), ".tar.bz2") + build := stem[strings.LastIndex(stem, "-")+1:] + build = condaBuildHash.ReplaceAllString(build, "") + return subdir + "/" + build + "/" + fileType +} + +// condaFileType returns the PURL type qualifier of a conda package file. +func condaFileType(filename string) string { + switch { + case strings.HasSuffix(filename, ".conda"): + return "conda" + case strings.HasSuffix(filename, ".tar.bz2"): + return "tar.bz2" + default: + return "" + } +} + +// selection returns the qualifiers of pv that select files, as +// "key=value" pairs, for error messages. +func (e fileEcosystem) selection(pv PackageVersion) string { + if pv.variants != nil { + return "the kinds of files cached of earlier versions" + } + var pairs []string + for _, key := range e.qualifiers { + if value := pv.Qualifiers[key]; value != "" { + pairs = append(pairs, key+"="+value) + } + } + return strings.Join(pairs, " ") +} + +// selects reports whether file matches every selecting qualifier of pv. +func (e fileEcosystem) selects(pv PackageVersion, file registries.Artifact) bool { + if pv.variants != nil && !slices.ContainsFunc(e.variants(file), func(v string) bool { return pv.variants[v] }) { + return false + } + attrs := e.attrs(file) + for _, key := range e.qualifiers { + if want := pv.Qualifiers[key]; want != "" && attrs[key] != want { + return false + } + } + return true +} + +// fileQualifiers keeps the qualifiers of a PURL that select files of its +// ecosystem, or returns nil. +func fileQualifiers(ecosystem string, qualifiers map[string]string) map[string]string { + e, ok := fileEcosystems[ecosystem] + if !ok { + return nil + } + var kept map[string]string + for key, value := range qualifiers { + if value != "" && slices.Contains(e.qualifiers, key) { + if kept == nil { + kept = map[string]string{} + } + kept[key] = value + } + } + return kept +} diff --git a/internal/mirror/files_test.go b/internal/mirror/files_test.go new file mode 100644 index 0000000..d84af72 --- /dev/null +++ b/internal/mirror/files_test.go @@ -0,0 +1,38 @@ +package mirror + +import ( + "reflect" + "testing" +) + +func TestPURLSourceCondaChannelAndQualifiers(t *testing.T) { + versions := &fakeVersions{versions: []string{"1.0", "1.1"}} + source := &PURLSource{ + PURLs: []string{ + "pkg:conda/conda-forge/numpy@2.1.0?subdir=linux-64&build=py312h_0&type=conda", + "pkg:conda/numpy@2.1.0?channel=conda-forge&repository_url=https://example.com", + "pkg:conda/numpy@2.1.0", + "pkg:conda/numpy", + "pkg:conda/numpy?channel=bioconda&subdir=noarch", + }, + Versions: versions, + } + + got := enumerate(t, source) + + want := []PackageVersion{ + {Ecosystem: "conda", Name: "conda-forge/numpy", Version: "2.1.0", + Qualifiers: map[string]string{"subdir": "linux-64", "build": "py312h_0", "type": "conda"}}, + {Ecosystem: "conda", Name: "conda-forge/numpy", Version: "2.1.0"}, + {Ecosystem: "conda", Name: "numpy", Version: "2.1.0"}, + {Ecosystem: "conda", Name: "numpy"}, + {Ecosystem: "conda", Name: "bioconda/numpy", Version: "1.0", Qualifiers: map[string]string{"subdir": "noarch"}}, + {Ecosystem: "conda", Name: "bioconda/numpy", Version: "1.1", Qualifiers: map[string]string{"subdir": "noarch"}}, + } + if !reflect.DeepEqual(got, want) { + t.Errorf("items = %+v\nwant %+v", got, want) + } + if !reflect.DeepEqual(versions.asked, []string{"conda/bioconda/numpy"}) { + t.Errorf("listed versions of %v, want only the package with a channel", versions.asked) + } +} diff --git a/internal/mirror/git.go b/internal/mirror/git.go new file mode 100644 index 0000000..e9c04ff --- /dev/null +++ b/internal/mirror/git.go @@ -0,0 +1,49 @@ +package mirror + +import ( + "context" + "errors" + + "github.com/git-pkgs/proxy/internal/gitcache" +) + +// GitMirrorer caches Git repositories for pkg:git items. location is the +// repository's host and path, such as codeberg.org/forgejo/forgejo, and +// version a full commit ID or a tag, or empty to cache the repository's +// branches and tags only. +type GitMirrorer interface { + Mirror(ctx context.Context, location, version string) (gitcache.MirrorResult, error) +} + +// UnavailableGit fails every pkg:git item with Reason. +type UnavailableGit struct { + Reason string +} + +func (u UnavailableGit) Mirror(context.Context, string, string) (gitcache.MirrorResult, error) { + return gitcache.MirrorResult{}, errors.New(u.Reason) +} + +var errNoGitUpstream = errors.New("git repositories are mirrored from upstream.git, and none is configured") + +// mirrorGit caches a pkg:git repository, and the commit its version names +// with the submodules it pins, in the cache /git serves clones from. +func (m *Mirror) mirrorGit(ctx context.Context, pv PackageVersion, tracker *progressTracker) { + if m.Git == nil { + m.recordFailure(tracker, pv, errNoGitUpstream) + return + } + result, err := m.Git.Mirror(ctx, pv.Name, pv.Version) + if err != nil { + m.recordFailure(tracker, pv, err) + return + } + if result.Cached { + tracker.skipped.Add(1) + m.logger.Debug("already cached", "ecosystem", pv.Ecosystem, "name", pv.Name, "version", pv.Version) + return + } + tracker.completed.Add(1) + tracker.bytes.Add(result.Bytes) + m.logger.Info("mirrored", "ecosystem", pv.Ecosystem, "name", pv.Name, "version", pv.Version, "size", result.Bytes) +} diff --git a/internal/mirror/git_test.go b/internal/mirror/git_test.go new file mode 100644 index 0000000..aa3aed4 --- /dev/null +++ b/internal/mirror/git_test.go @@ -0,0 +1,92 @@ +package mirror + +import ( + "context" + "errors" + "sync" + "testing" + + "github.com/git-pkgs/proxy/internal/gitcache" +) + +type gitCall struct{ location, commit string } + +type fakeGit struct { + mu sync.Mutex + calls []gitCall + result gitcache.MirrorResult + err error +} + +func (f *fakeGit) Mirror(_ context.Context, location, commit string) (gitcache.MirrorResult, error) { + f.mu.Lock() + defer f.mu.Unlock() + f.calls = append(f.calls, gitCall{location, commit}) + return f.result, f.err +} + +const gitTestCommit = "a72d2c07cfca03b55371089de6aa230d8c951fa0" + +func TestMirrorRunCountsGitRepositories(t *testing.T) { + tests := []struct { + name string + result gitcache.MirrorResult + err error + wantCompleted, wantSkipped, wantFailed int64 + }{ + {name: "fetched", result: gitcache.MirrorResult{Bytes: 42}, wantCompleted: 1}, + {name: "cached", result: gitcache.MirrorResult{Cached: true}, wantSkipped: 1}, + {name: "failed", err: errors.New("boom"), wantFailed: 1}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + m := setupTestMirror(t, 1) + git := &fakeGit{result: tt.result, err: tt.err} + m.Git = git + progress, err := m.Run(context.Background(), &PURLSource{PURLs: []string{"pkg:git/codeberg.org/forgejo/forgejo@" + gitTestCommit}}) + if err != nil { + t.Fatalf("Run: %v", err) + } + if progress.Completed != tt.wantCompleted || progress.Skipped != tt.wantSkipped || progress.Failed != tt.wantFailed { + t.Errorf("progress = %+v", progress) + } + if progress.Bytes != tt.result.Bytes { + t.Errorf("bytes = %d, want %d", progress.Bytes, tt.result.Bytes) + } + want := gitCall{"codeberg.org/forgejo/forgejo", gitTestCommit} + if len(git.calls) != 1 || git.calls[0] != want { + t.Errorf("calls = %+v, want %+v", git.calls, want) + } + }) + } +} + +// TestMirrorRunGitRepositoryWithoutCommit checks a pkg:git PURL without a +// version mirrors the repository instead of listing versions. +func TestMirrorRunGitRepositoryWithoutCommit(t *testing.T) { + m := setupTestMirror(t, 1) + git := &fakeGit{} + m.Git = git + versions := &fakeVersions{err: errors.New("listed versions")} + progress, err := m.Run(context.Background(), &PURLSource{PURLs: []string{"pkg:git/codeberg.org/forgejo/forgejo"}, Versions: versions}) + if err != nil { + t.Fatalf("Run: %v", err) + } + if len(versions.asked) != 0 { + t.Errorf("listed versions of %v", versions.asked) + } + if progress.Failed != 0 || len(git.calls) != 1 || git.calls[0] != (gitCall{"codeberg.org/forgejo/forgejo", ""}) { + t.Errorf("progress = %+v, calls = %+v", progress, git.calls) + } +} + +func TestMirrorRunGitWithoutUpstream(t *testing.T) { + m := setupTestMirror(t, 1) + progress, err := m.Run(context.Background(), &PURLSource{PURLs: []string{"pkg:git/codeberg.org/forgejo/forgejo@" + gitTestCommit}}) + if err != nil { + t.Fatalf("Run: %v", err) + } + if progress.Failed != 1 { + t.Errorf("progress = %+v, want one failure", progress) + } +} diff --git a/internal/mirror/helm.go b/internal/mirror/helm.go new file mode 100644 index 0000000..bda16dd --- /dev/null +++ b/internal/mirror/helm.go @@ -0,0 +1,40 @@ +package mirror + +import ( + "context" + "errors" + "strings" + + "github.com/git-pkgs/proxy/internal/handler" +) + +// ChartMirrorer caches Helm charts from the configured repositories the way +// the Helm handler serves them. +type ChartMirrorer interface { + MirrorChart(ctx context.Context, repository, chart, version string) (*handler.CacheResult, error) +} + +var ( + errHelmNoRepository = errors.New("helm charts need the upstream.helm repository as the namespace, such as pkg:helm/{repository}/{chart}@{version}") + errHelmUnavailable = errors.New("mirroring Helm charts isn't available here") +) + +// mirrorHelm mirrors a chart release. The PURL namespace names the +// upstream.helm repository, since the handler caches charts per repository. +func (m *Mirror) mirrorHelm(ctx context.Context, pv PackageVersion, tracker *progressTracker) { + repository, chart, ok := strings.Cut(pv.Name, "/") + if !ok || repository == "" || chart == "" { + m.recordFailure(tracker, pv, errHelmNoRepository) + return + } + if m.Charts == nil { + m.recordFailure(tracker, pv, errHelmUnavailable) + return + } + result, err := m.Charts.MirrorChart(ctx, repository, chart, pv.Version) + if err != nil { + m.recordFailure(tracker, pv, err) + return + } + m.recordResult(tracker, pv, result) +} diff --git a/internal/mirror/image.go b/internal/mirror/image.go index bc21937..5116f26 100644 --- a/internal/mirror/image.go +++ b/internal/mirror/image.go @@ -27,6 +27,18 @@ func isImageEcosystem(ecosystem string) bool { return ecosystem == "docker" || ecosystem == "oci" } +// BottleResolver resolves a Homebrew formula version to the image its +// bottles are published under. +type BottleResolver interface { + BottleImage(ctx context.Context, formula, version string) (handler.ImageRef, error) +} + +// takesPlatforms reports whether --platform applies to an ecosystem: images, +// and Homebrew bottles, which are published as images. +func takesPlatforms(ecosystem string) bool { + return isImageEcosystem(ecosystem) || ecosystem == "brew" +} + // ParsePlatforms parses os/architecture[/variant] values. func ParsePlatforms(values []string) ([]handler.Platform, error) { var platforms []handler.Platform @@ -64,6 +76,13 @@ func imageRef(pv PackageVersion) (handler.ImageRef, []handler.Platform, error) { ref.References = []string{pv.Version} } repositoryURL := pv.Qualifiers["repository_url"] + if pv.Ecosystem == "docker" && repositoryURL == "" { + host, repository, found := strings.Cut(pv.Name, "/") + if found && (strings.ContainsAny(host, ".:") || host == "localhost") { + ref.Registry = host + ref.Name = repository + } + } if pv.Ecosystem == "oci" { if repositoryURL == "" { return ref, nil, errors.New("pkg:oci needs a repository_url qualifier") @@ -91,20 +110,40 @@ func imageRef(pv PackageVersion) (handler.ImageRef, []handler.Platform, error) { } func (m *Mirror) mirrorImage(ctx context.Context, pv PackageVersion, tracker *progressTracker) { + ref, platforms, err := imageRef(pv) + m.mirrorImageRef(ctx, pv, ref, platforms, err, tracker) +} + +// mirrorBrew mirrors the bottles of a Homebrew formula version, which brew +// pulls as an image from homebrew/core on its artifact domain. +func (m *Mirror) mirrorBrew(ctx context.Context, pv PackageVersion, tracker *progressTracker) { + if m.Images == nil || m.Bottles == nil { + m.recordFailure(tracker, pv, errors.New("mirroring Homebrew bottles isn't available here")) + return + } + platforms, err := ParsePlatforms(pv.Platforms) + if err != nil { + m.recordFailure(tracker, pv, err) + return + } + ref, err := m.Bottles.BottleImage(ctx, pv.Name, pv.Version) + m.mirrorImageRef(ctx, pv, ref, platforms, err, tracker) +} + +// mirrorImageRef mirrors the image ref for pv, or records refErr, the error +// resolving it. +func (m *Mirror) mirrorImageRef(ctx context.Context, pv PackageVersion, ref handler.ImageRef, platforms []handler.Platform, refErr error, tracker *progressTracker) { fail := func(err error) { tracker.failed.Add(1) tracker.addError(pv.Ecosystem, pv.Name, pv.Version, err.Error()) m.logger.Warn("mirror failed", "ecosystem", pv.Ecosystem, "name", pv.Name, "version", pv.Version, "error", err) } - // pv.String keeps the namespace separator, which MakeString escapes for - // docker names. if m.proxy != nil && m.proxy.Denylist.Denied(pv.String()) { fail(fmt.Errorf("%w: %s", handler.ErrVersionDenied, pv)) return } - ref, platforms, err := imageRef(pv) - if err != nil { - fail(err) + if refErr != nil { + fail(refErr) return } result, err := m.Images.MirrorImage(ctx, ref, platforms) diff --git a/internal/mirror/image_test.go b/internal/mirror/image_test.go index 339e86c..c38ddf7 100644 --- a/internal/mirror/image_test.go +++ b/internal/mirror/image_test.go @@ -25,6 +25,22 @@ func TestImageRefFromPURL(t *testing.T) { purl: "pkg:docker/library/alpine@3.20", wantRef: handler.ImageRef{Name: "library/alpine", References: []string{"3.20"}}, }, + { + purl: "pkg:docker/ghcr.io/team/app@1.0", + wantRef: handler.ImageRef{Registry: "ghcr.io", Name: "team/app", References: []string{"1.0"}}, + }, + { + purl: "pkg:docker/registry.example:5000/team/app@" + digest, + wantRef: handler.ImageRef{Registry: "registry.example:5000", Name: "team/app", References: []string{digest}}, + }, + { + purl: "pkg:docker/localhost/app@1.0", + wantRef: handler.ImageRef{Registry: "localhost", Name: "app", References: []string{"1.0"}}, + }, + { + purl: "pkg:docker/localhost:5000/team/app@1.0", + wantRef: handler.ImageRef{Registry: "localhost:5000", Name: "team/app", References: []string{"1.0"}}, + }, { purl: "pkg:docker/alpine@3.20?repository_url=ghcr.io", platforms: []string{"linux/arm64/v8"}, diff --git a/internal/mirror/job.go b/internal/mirror/job.go index 3d82966..841c7c9 100644 --- a/internal/mirror/job.go +++ b/internal/mirror/job.go @@ -42,6 +42,8 @@ type JobRequest struct { // Platforms limit which platforms of container images are mirrored, // as os/architecture[/variant]. Platforms []string `json:"platforms,omitempty"` + // Latest mirrors only the newest version of PURLs without a version. + Latest bool `json:"latest,omitempty"` } // JobStore manages in-memory mirror jobs. @@ -50,6 +52,8 @@ type JobStore struct { jobs map[string]*Job mirror *Mirror parentCtx context.Context + // running counts the jobs whose goroutine has not returned yet. + running sync.WaitGroup } // NewJobStore creates a new job store. The parent context is used as the base @@ -83,7 +87,7 @@ func (js *JobStore) Create(req JobRequest) (string, error) { js.jobs[id] = job js.mu.Unlock() - go js.runJob(ctx, cancel, job, source) + js.running.Go(func() { js.runJob(ctx, cancel, job, source) }) return id, nil } @@ -125,6 +129,12 @@ func (js *JobStore) Cancel(id string) bool { return true } +// Wait blocks until every job has returned. Cancel the parent context first +// to stop running jobs. +func (js *JobStore) Wait() { + js.running.Wait() +} + // Cleanup removes completed/failed/canceled jobs older than jobTTL. func (js *JobStore) Cleanup() { js.mu.Lock() @@ -201,9 +211,9 @@ func (js *JobStore) sourceFromRequest(req JobRequest) (Source, error) { //nolint case len(req.PURLs) > 0 && len(req.SBOM) > 0: return nil, fmt.Errorf("request must include only one of purls or sbom") case len(req.PURLs) > 0: - return &PURLSource{PURLs: req.PURLs, Platforms: req.Platforms}, nil + return &PURLSource{PURLs: req.PURLs, Versions: js.mirror.Versions, Latest: req.Latest, Platforms: req.Platforms}, nil case len(req.SBOM) > 0: - return &SBOMSource{Data: req.SBOM, Platforms: req.Platforms}, nil + return &SBOMSource{Data: req.SBOM, Versions: js.mirror.Versions, Latest: req.Latest, Platforms: req.Platforms}, nil case req.Registry != "": return nil, fmt.Errorf("registry mirroring is not yet implemented; use purls instead") default: diff --git a/internal/mirror/job_test.go b/internal/mirror/job_test.go index c0ac3f1..7b4c88e 100644 --- a/internal/mirror/job_test.go +++ b/internal/mirror/job_test.go @@ -7,9 +7,22 @@ import ( "time" ) -func TestJobStoreCreateAndGet(t *testing.T) { +// newTestJobStore returns a job store whose jobs are stopped and waited for +// before the test's database and directories are removed. +func newTestJobStore(t *testing.T) *JobStore { + t.Helper() m := setupTestMirror(t, 1) - js := NewJobStore(context.Background(), m) + ctx, cancel := context.WithCancel(context.Background()) + js := NewJobStore(ctx, m) + t.Cleanup(func() { + cancel() + js.Wait() + }) + return js +} + +func TestJobStoreCreateAndGet(t *testing.T) { + js := newTestJobStore(t) id, err := js.Create(JobRequest{ PURLs: []string{"pkg:npm/lodash@4.17.21"}, @@ -35,8 +48,7 @@ func TestJobStoreCreateAndGet(t *testing.T) { } func TestJobStoreGetNotFound(t *testing.T) { - m := setupTestMirror(t, 1) - js := NewJobStore(context.Background(), m) + js := newTestJobStore(t) job := js.Get("nonexistent") if job != nil { @@ -45,8 +57,7 @@ func TestJobStoreGetNotFound(t *testing.T) { } func TestJobStoreCancelNotFound(t *testing.T) { - m := setupTestMirror(t, 1) - js := NewJobStore(context.Background(), m) + js := newTestJobStore(t) if js.Cancel("nonexistent") { t.Error("expected Cancel to return false for nonexistent job") @@ -54,8 +65,7 @@ func TestJobStoreCancelNotFound(t *testing.T) { } func TestJobStoreCreateInvalidRequest(t *testing.T) { - m := setupTestMirror(t, 1) - js := NewJobStore(context.Background(), m) + js := newTestJobStore(t) _, err := js.Create(JobRequest{}) if err == nil { @@ -64,8 +74,7 @@ func TestJobStoreCreateInvalidRequest(t *testing.T) { } func TestJobStoreMultipleJobs(t *testing.T) { - m := setupTestMirror(t, 1) - js := NewJobStore(context.Background(), m) + js := newTestJobStore(t) id1, err := js.Create(JobRequest{PURLs: []string{"pkg:npm/lodash@4.17.21"}}) if err != nil { @@ -89,8 +98,7 @@ func TestJobStoreMultipleJobs(t *testing.T) { } func TestSourceFromRequestPURLs(t *testing.T) { - m := setupTestMirror(t, 1) - js := NewJobStore(context.Background(), m) + js := newTestJobStore(t) source, err := js.sourceFromRequest(JobRequest{PURLs: []string{"pkg:npm/lodash@1.0.0"}}) if err != nil { @@ -102,8 +110,7 @@ func TestSourceFromRequestPURLs(t *testing.T) { } func TestSourceFromRequestSBOM(t *testing.T) { - m := setupTestMirror(t, 1) - js := NewJobStore(context.Background(), m) + js := newTestJobStore(t) sbom := json.RawMessage(`{"bomFormat":"CycloneDX","components":[]}`) source, err := js.sourceFromRequest(JobRequest{SBOM: sbom}) @@ -120,8 +127,7 @@ func TestSourceFromRequestSBOM(t *testing.T) { } func TestSourceFromRequestRejectsPURLsAndSBOM(t *testing.T) { - m := setupTestMirror(t, 1) - js := NewJobStore(context.Background(), m) + js := newTestJobStore(t) _, err := js.sourceFromRequest(JobRequest{ PURLs: []string{"pkg:npm/lodash@4.17.21"}, @@ -133,8 +139,7 @@ func TestSourceFromRequestRejectsPURLsAndSBOM(t *testing.T) { } func TestSourceFromRequestRegistryRejected(t *testing.T) { - m := setupTestMirror(t, 1) - js := NewJobStore(context.Background(), m) + js := newTestJobStore(t) _, err := js.sourceFromRequest(JobRequest{Registry: "npm"}) if err == nil { @@ -143,8 +148,7 @@ func TestSourceFromRequestRegistryRejected(t *testing.T) { } func TestJobStoreCleanup(t *testing.T) { - m := setupTestMirror(t, 1) - js := NewJobStore(context.Background(), m) + js := newTestJobStore(t) // Add a completed job with old CreatedAt js.mu.Lock() @@ -179,8 +183,7 @@ func TestJobStoreCleanup(t *testing.T) { } func TestJobStoreCancelPreservesStateAfterRunJob(t *testing.T) { - m := setupTestMirror(t, 1) - js := NewJobStore(context.Background(), m) + js := newTestJobStore(t) // Create a job with a PURL that will fail (no real upstream in test) id, err := js.Create(JobRequest{PURLs: []string{"pkg:npm/nonexistent-pkg@0.0.0"}}) diff --git a/internal/mirror/julia.go b/internal/mirror/julia.go new file mode 100644 index 0000000..613ba76 --- /dev/null +++ b/internal/mirror/julia.go @@ -0,0 +1,84 @@ +package mirror + +import ( + "context" + "errors" + "fmt" + "strings" + + "github.com/git-pkgs/proxy/internal/handler" + "github.com/git-pkgs/registries" +) + +// PackageFinder finds a package's registry entry, which for Julia gives the +// UUID the package is registered under. +type PackageFinder interface { + FindPackage(ctx context.Context, ecosystem, name string) (*registries.Package, error) +} + +// FindPackage implements PackageFinder. +func (r RegistryVersions) FindPackage(ctx context.Context, ecosystem, name string) (*registries.Package, error) { + reg, err := r.registry(ecosystem, name) + if err != nil { + return nil, err + } + return reg.FetchPackage(ctx, name) +} + +// mirrorJulia fetches the tarball unchecked because Pkg checks the tree hash +// of what it extracts. +func (m *Mirror) mirrorJulia(ctx context.Context, pv PackageVersion, tracker *progressTracker) { + fail := func(err error) { m.recordFailure(tracker, pv, err) } + uuid := strings.ToLower(pv.Qualifiers["uuid"]) + if uuid == "" { + fail(fmt.Errorf("julia packages need a uuid qualifier, such as pkg:julia/%s@%s?uuid=", pv.Name, pv.Version)) + return + } + + pkg, err := m.packageFinder().FindPackage(ctx, pv.Ecosystem, pv.Name) + if err != nil { + fail(err) + return + } + registered, _ := pkg.Metadata["uuid"].(string) + if !strings.EqualFold(registered, uuid) { + fail(fmt.Errorf("%s in the General registry has uuid %s, not %s; only General packages can be mirrored", pv.Name, registered, uuid)) + return + } + // The handler names packages as the registry does. + name := pkg.Name + if name == "" { + name = pv.Name + } + + v, err := m.versionFinder().FindVersion(ctx, pv.Ecosystem, name, pv.Version) + if err != nil { + fail(err) + return + } + treeHash, _ := v.Metadata["git-tree-sha1"].(string) + if treeHash == "" { + fail(errors.New("the registry lists no tree hash for this version")) + return + } + url, filename, err := handler.JuliaPackageDownload(m.JuliaUpstream, uuid, treeHash) + if err != nil { + fail(err) + return + } + result, err := m.proxy.GetOrFetchArtifactFromURL(ctx, pv.Ecosystem, name, treeHash, filename, url) + if err != nil { + fail(err) + return + } + m.recordResult(tracker, pv, result) +} + +// packageFinder finds packages where Versions lists versions, so both come +// from the same registry. +func (m *Mirror) packageFinder() PackageFinder { //nolint:ireturn // any finder will do + if finder, ok := m.Versions.(PackageFinder); ok { + return finder + } + return RegistryVersions{} +} diff --git a/internal/mirror/latest_test.go b/internal/mirror/latest_test.go new file mode 100644 index 0000000..8135116 --- /dev/null +++ b/internal/mirror/latest_test.go @@ -0,0 +1,127 @@ +package mirror + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "reflect" + "testing" +) + +func TestPURLSourceLatestMirrorsNewestVersion(t *testing.T) { + versions := &fakeVersions{versions: []string{"1.0.0", "1.10.0", "1.2.0"}} + source := &PURLSource{PURLs: []string{"pkg:npm/left-pad", "pkg:npm/is-odd@3.0.0"}, Versions: versions, Latest: true} + + items := enumerate(t, source) + + want := []PackageVersion{ + {Ecosystem: "npm", Name: "left-pad", Version: "1.10.0"}, + {Ecosystem: "npm", Name: "is-odd", Version: "3.0.0"}, + } + if !reflect.DeepEqual(items, want) { + t.Errorf("items = %v, want %v", items, want) + } +} + +func TestPURLSourceLatestWithoutVersions(t *testing.T) { + source := &PURLSource{PURLs: []string{"pkg:npm/left-pad"}, Versions: &fakeVersions{}, Latest: true} + if items := enumerate(t, source); len(items) != 0 { + t.Errorf("items = %v, want none", items) + } +} + +func TestSBOMSourceLatest(t *testing.T) { + bom := map[string]any{ + "bomFormat": "CycloneDX", + "specVersion": "1.4", + "components": []map[string]any{{"type": "library", "name": "left-pad", "purl": "pkg:npm/left-pad"}}, + } + source := &SBOMSource{Data: marshalJSON(t, bom), Versions: &fakeVersions{versions: []string{"1.0.0", "1.3.0"}}, Latest: true} + + items := enumerate(t, source) + + if len(items) != 1 || items[0].Version != "1.3.0" { + t.Errorf("items = %v, want only left-pad@1.3.0", items) + } +} + +// TestRegistryVersionsLatestSkipsYanked checks that without an advertised +// latest version the newest version by publish time that isn't yanked wins. +func TestRegistryVersionsLatestSkipsYanked(t *testing.T) { + registry := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/api/v1/crates/demo" { + http.NotFound(w, r) + return + } + _ = json.NewEncoder(w).Encode(map[string]any{ + "crate": map[string]any{"name": "demo"}, + "versions": []map[string]any{ + {"num": "1.3.0", "yanked": true, "created_at": "2026-03-01T00:00:00Z"}, + {"num": "1.2.0", "created_at": "2026-02-01T00:00:00Z"}, + {"num": "1.10.0-alpha.1", "created_at": "2026-01-01T00:00:00Z"}, + }, + }) + })) + defer registry.Close() + versions := RegistryVersions{URL: func(string, string) (string, error) { return registry.URL, nil }} + + got, err := versions.LatestVersion(context.Background(), "cargo", "demo") + if err != nil { + t.Fatalf("LatestVersion() error = %v", err) + } + if got != "1.2.0" { + t.Errorf("LatestVersion() = %q, want 1.2.0", got) + } +} + +// TestRegistryVersionsLatestPrefersAdvertised checks that the version the +// registry advertises as latest wins over a higher one, here a 4.0.0 +// published by mistake and deprecated. +func TestRegistryVersionsLatestPrefersAdvertised(t *testing.T) { + registry := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/left-pad" { + http.NotFound(w, r) + return + } + _ = json.NewEncoder(w).Encode(map[string]any{ + "name": "left-pad", + "dist-tags": map[string]any{"latest": "3.4.0"}, + "versions": map[string]any{ + "3.4.0": map[string]any{"name": "left-pad", "version": "3.4.0"}, + "4.0.0": map[string]any{"name": "left-pad", "version": "4.0.0", "deprecated": "published by mistake"}, + }, + "time": map[string]any{"3.4.0": "2026-01-01T00:00:00Z", "4.0.0": "2026-02-01T00:00:00Z"}, + }) + })) + defer registry.Close() + versions := RegistryVersions{URL: func(string, string) (string, error) { return registry.URL, nil }} + + got, err := versions.LatestVersion(context.Background(), "npm", "left-pad") + if err != nil { + t.Fatalf("LatestVersion() error = %v", err) + } + if got != "3.4.0" { + t.Errorf("LatestVersion() = %q, want the advertised 3.4.0", got) + } +} + +func TestSourceFromRequestPassesLatest(t *testing.T) { + js := NewJobStore(context.Background(), setupTestMirror(t, 1)) + + source, err := js.sourceFromRequest(JobRequest{PURLs: []string{"pkg:npm/left-pad"}, Latest: true}) + if err != nil { + t.Fatalf("sourceFromRequest() error = %v", err) + } + if !source.(*PURLSource).Latest { + t.Error("PURL source mirrors every version, want only the newest") + } + + source, err = js.sourceFromRequest(JobRequest{SBOM: json.RawMessage(`{"bomFormat":"CycloneDX","components":[]}`), Latest: true}) + if err != nil { + t.Fatalf("sourceFromRequest() error = %v", err) + } + if !source.(*SBOMSource).Latest { + t.Error("SBOM source mirrors every version, want only the newest") + } +} diff --git a/internal/mirror/mirror.go b/internal/mirror/mirror.go index fb98c11..1dded24 100644 --- a/internal/mirror/mirror.go +++ b/internal/mirror/mirror.go @@ -3,8 +3,10 @@ package mirror import ( "context" + "errors" "fmt" "log/slog" + "strings" "sync" "sync/atomic" "time" @@ -26,6 +28,37 @@ type Mirror struct { // Images mirrors docker and oci items. Without it they fail like any // other unsupported ecosystem. Images ImageMirrorer + + // Charts mirrors helm charts. Without it they fail. + Charts ChartMirrorer + + // Git mirrors pkg:git repositories into the upstream.git cache. Without + // it they fail. + Git GitMirrorer + + // Bottles resolves Homebrew formula versions to the images their + // bottles are published under, which Images mirrors. Without it brew + // PURLs fail. + Bottles BottleResolver + + // Versions lists the versions of unversioned PURLs in mirror jobs and + // schedules. Nil lists them from the public registries. + Versions VersionLister + + // JuliaUpstream is the Pkg server Julia packages are fetched from. Empty + // uses https://pkg.julialang.org. + JuliaUpstream string + + // APKRepositories are the upstream.apk repositories by name. Nil uses + // the official Alpine mirror as "alpine". + APKRepositories map[string]string + + // RefusePackages, when set, fails every item Images does not take with + // this reason instead of fetching it, so nothing is cached. + RefusePackages string + + cran cranIndex + apk apkIndexes } // New creates a new Mirror with the given dependencies. @@ -167,16 +200,8 @@ func (m *Mirror) Run(ctx context.Context, source Source, onProgress ...ProgressF g.SetLimit(m.workers) for _, item := range items { - g.Go(func() (err error) { - defer func() { - if r := recover(); r != nil { - m.logger.Error("panic in mirror worker", "recover", r, - "ecosystem", item.Ecosystem, "name", item.Name, "version", item.Version) - tracker.failed.Add(1) - tracker.addError(item.Ecosystem, item.Name, item.Version, fmt.Sprintf("panic: %v", r)) - } - }() - m.mirrorOne(gctx, item, tracker) + g.Go(func() error { + m.mirrorRecovered(gctx, item, tracker) return nil // never fail the group; errors are tracked }) } @@ -206,20 +231,95 @@ func (m *Mirror) RunDryRun(ctx context.Context, source Source) ([]PackageVersion return items, err } +// mirrorRecovered is mirrorOne, counting a panic as a failure. +func (m *Mirror) mirrorRecovered(ctx context.Context, item PackageVersion, tracker *progressTracker) { + defer func() { + if r := recover(); r != nil { + m.logger.Error("panic in mirror worker", "recover", r, + "ecosystem", item.Ecosystem, "name", item.Name, "version", item.Version) + tracker.failed.Add(1) + tracker.addError(item.Ecosystem, item.Name, item.Version, fmt.Sprintf("panic: %v", r)) + } + }() + m.mirrorOne(ctx, item, tracker) +} + func (m *Mirror) mirrorOne(ctx context.Context, pv PackageVersion, tracker *progressTracker) { if isImageEcosystem(pv.Ecosystem) && m.Images != nil { m.mirrorImage(ctx, pv, tracker) return } - result, err := m.proxy.GetOrFetchArtifact(ctx, pv.Ecosystem, pv.Name, pv.Version, "") - if err != nil { - tracker.failed.Add(1) - tracker.addError(pv.Ecosystem, pv.Name, pv.Version, err.Error()) - m.logger.Warn("mirror failed", - "ecosystem", pv.Ecosystem, "name", pv.Name, "version", pv.Version, "error", err) + if pv.Ecosystem == "brew" { + m.mirrorBrew(ctx, pv, tracker) return } + if m.RefusePackages != "" { + tracker.failed.Add(1) + tracker.addError(pv.Ecosystem, pv.Name, pv.Version, m.RefusePackages) + m.logger.Warn("mirror refused", + "ecosystem", pv.Ecosystem, "name", pv.Name, "version", pv.Version, "reason", m.RefusePackages) + return + } + if pv.fileURL != "" { + result, err := m.proxy.GetOrFetchArtifactFromURLWithDigest(ctx, pv.Ecosystem, pv.Name, pv.Version, pv.cacheFilename, pv.fileURL, pv.digest) + if err != nil { + m.recordFailure(tracker, pv, err) + return + } + m.recordResult(tracker, pv, result) + return + } + if eco, ok := fileEcosystems[pv.Ecosystem]; ok { + m.mirrorFiles(ctx, pv, eco, tracker) + return + } + if pv.Ecosystem == "composer" { + m.mirrorComposer(ctx, pv, tracker) + return + } + if pv.Ecosystem == "helm" { + m.mirrorHelm(ctx, pv, tracker) + return + } + if pv.Ecosystem == "julia" { + m.mirrorJulia(ctx, pv, tracker) + return + } + if pv.Ecosystem == "swift" { + m.mirrorSwift(ctx, pv, tracker) + return + } + if pv.Ecosystem == "cran" { + m.mirrorCRAN(ctx, pv, tracker) + return + } + if pv.Ecosystem == "alpine" { + m.mirrorAPK(ctx, pv, tracker) + return + } + if pv.Ecosystem == "git" { + m.mirrorGit(ctx, pv, tracker) + return + } + result, err := m.proxy.GetOrFetchArtifact(ctx, pv.Ecosystem, pv.Name, pv.Version, "") + if err != nil { + m.recordFailure(tracker, pv, err) + return + } + m.recordResult(tracker, pv, result) +} +// recordFailure counts and logs a package that could not be mirrored. +func (m *Mirror) recordFailure(tracker *progressTracker, pv PackageVersion, err error) { + tracker.failed.Add(1) + tracker.addError(pv.Ecosystem, pv.Name, pv.Version, err.Error()) + m.logger.Warn("mirror failed", + "ecosystem", pv.Ecosystem, "name", pv.Name, "version", pv.Version, "error", err) +} + +// recordResult closes the fetched artifact and counts it as mirrored, or as +// skipped when it was already cached. +func (m *Mirror) recordResult(tracker *progressTracker, pv PackageVersion, result *handler.CacheResult) { if result.Reader != nil { _ = result.Reader.Close() } @@ -236,3 +336,113 @@ func (m *Mirror) mirrorOne(ctx context.Context, pv PackageVersion, tracker *prog "size", result.Artifact.Size) } } + +// mirrorComposer mirrors the archive of a tagged Composer release under the +// file name the Composer handler serves it as, checked against the listed +// shasum, and records the release's publish time, which the handler needs to +// serve the archive from the cache without the metadata. +func (m *Mirror) mirrorComposer(ctx context.Context, pv PackageVersion, tracker *progressTracker) { + // Packagist names are lowercase, and so are the paths Composer requests. + name := strings.ToLower(pv.Name) + v, err := m.versionFinder().FindVersion(ctx, pv.Ecosystem, name, pv.Version) + if err != nil { + m.recordFailure(tracker, pv, err) + return + } + distURL, _ := v.Metadata["dist_url"].(string) + distType, _ := v.Metadata["dist_type"].(string) + filename, declared, err := handler.ComposerReleaseArchive(v.Number, distURL, distType, strings.TrimPrefix(v.Integrity, "sha1-")) + if err != nil { + m.recordFailure(tracker, pv, err) + return + } + result, err := m.proxy.GetOrFetchArtifactFromURLWithIntegrity(ctx, pv.Ecosystem, name, v.Number, filename, distURL, declared) + if err != nil { + m.recordFailure(tracker, pv, err) + return + } + if err := m.proxy.RecordComposerPublishTime(name, v.Number, v.PublishedAt); err != nil { + m.logger.Warn("failed to store composer publish time", + "name", name, "version", v.Number, "error", err) + } + m.recordResult(tracker, pv, result) +} + +// mirrorFiles mirrors every file of a version, or those its qualifiers +// select. Each file is cached under the name and version the download +// handler reads from its filename, so clients are served it. +func (m *Mirror) mirrorFiles(ctx context.Context, pv PackageVersion, eco fileEcosystem, tracker *progressTracker) { + fail := func(err error) { m.recordFailure(tracker, pv, err) } + if eco.check != nil { + if err := eco.check(pv); err != nil { + fail(err) + return + } + } + v, err := m.versionFinder().FindVersion(ctx, pv.Ecosystem, pv.Name, pv.Version) + if err != nil { + fail(fmt.Errorf("listing files: %w", err)) + return + } + var matched, fetched int + var size int64 + for _, file := range v.Artifacts { + if !eco.selects(pv, file) { + continue + } + name, version, filename, ok := eco.cacheKey(pv, file) + if !ok { + continue + } + matched++ + result, err := m.proxy.GetOrFetchArtifactFromURLWithDigest(ctx, pv.Ecosystem, name, version, filename, file.URL, fileDigest(file.Integrity)) + if err != nil { + fail(fmt.Errorf("%s: %w", file.Filename, err)) + return + } + if result.Reader != nil { + _ = result.Reader.Close() + } + if !result.Cached { + fetched++ + size += result.Artifact.Size + } + } + switch selection := eco.selection(pv); { + case matched == 0 && selection != "": + fail(fmt.Errorf("no file matches %s", selection)) + case matched == 0: + fail(errors.New("version has no files")) + case fetched == 0: + tracker.skipped.Add(1) + m.logger.Debug("already cached", + "ecosystem", pv.Ecosystem, "name", pv.Name, "version", pv.Version) + default: + tracker.completed.Add(1) + tracker.bytes.Add(size) + m.logger.Info("mirrored", + "ecosystem", pv.Ecosystem, "name", pv.Name, "version", pv.Version, + "files", fetched, "size", size) + } +} + +// fileDigest returns the SHA-256 of one file as a digest, which is checked +// against that file alone. The integrity GetOrFetchArtifactFromURLWithIntegrity +// takes is kept with the version instead, and the files of a version that +// share a name and version would overwrite each other's. Other checksums are +// not checked, as the download handlers don't check them either. +func fileDigest(integrity string) string { + if sum, ok := strings.CutPrefix(integrity, "sha256-"); ok { + return "sha256:" + sum + } + return "" +} + +// versionFinder finds versions where Versions lists them, so both come from +// the configured upstream. +func (m *Mirror) versionFinder() VersionFinder { //nolint:ireturn // any finder will do + if finder, ok := m.Versions.(VersionFinder); ok { + return finder + } + return RegistryVersions{} +} diff --git a/internal/mirror/mirror_test.go b/internal/mirror/mirror_test.go index 45dd6f3..6852687 100644 --- a/internal/mirror/mirror_test.go +++ b/internal/mirror/mirror_test.go @@ -3,10 +3,12 @@ package mirror import ( "context" "database/sql" + "errors" "log/slog" "net/http" "os" "strings" + "sync" "testing" "time" @@ -261,3 +263,90 @@ func TestNewMirrorDefaultWorkers(t *testing.T) { t.Errorf("workers = %d, want 1 (minimum)", m.workers) } } + +// recordingFetcher fails every fetch and records the URLs it was asked for, so +// a test can show nothing reached upstream. +type recordingFetcher struct { + mu sync.Mutex + urls []string +} + +func (f *recordingFetcher) record(url string) error { + f.mu.Lock() + defer f.mu.Unlock() + f.urls = append(f.urls, url) + return errors.New("recordingFetcher: no upstream in this test") +} + +func (f *recordingFetcher) Fetch(_ context.Context, url string) (*fetch.Artifact, error) { + return nil, f.record(url) +} + +func (f *recordingFetcher) FetchWithHeaders(_ context.Context, url string, _ http.Header) (*fetch.Artifact, error) { + return nil, f.record(url) +} + +func (f *recordingFetcher) Head(_ context.Context, url string) (int64, string, error) { + return 0, "", f.record(url) +} + +func (f *recordingFetcher) fetched() []string { + f.mu.Lock() + defer f.mu.Unlock() + return append([]string(nil), f.urls...) +} + +func TestMirrorRunRefusesPackages(t *testing.T) { + m := setupTestMirror(t, 2) + fetcher := &recordingFetcher{} + m.proxy.Fetcher = fetcher + const reason = "packages cannot be mirrored here" + m.RefusePackages = reason + + source := &PURLSource{PURLs: []string{"pkg:npm/lodash@4.17.21", "pkg:cargo/serde@1.0.0"}} + progress, err := m.Run(context.Background(), source) + if err != nil { + t.Fatalf("Run: %v", err) + } + + if progress.Failed != 2 || progress.Completed != 0 || progress.Skipped != 0 { + t.Errorf("progress = %d failed, %d completed, %d skipped; want 2 failed only", + progress.Failed, progress.Completed, progress.Skipped) + } + if len(progress.Errors) != 2 { + t.Fatalf("errors = %+v, want one per package", progress.Errors) + } + for _, e := range progress.Errors { + if e.Error != reason { + t.Errorf("%s/%s error = %q, want %q", e.Ecosystem, e.Name, e.Error, reason) + } + } + if urls := fetcher.fetched(); len(urls) != 0 { + t.Errorf("refused packages were fetched from upstream: %v", urls) + } + + stats, err := m.db.GetCacheStats() + if err != nil { + t.Fatalf("GetCacheStats: %v", err) + } + if stats.TotalArtifacts != 0 { + t.Errorf("cached artifacts = %d, want 0", stats.TotalArtifacts) + } +} + +// Images keep their own refusal, so a mirror refusing packages still hands +// docker and oci items to Images. +func TestMirrorRefusePackagesLeavesImagesToImages(t *testing.T) { + m := setupTestMirror(t, 1) + m.proxy.Fetcher = &recordingFetcher{} + m.RefusePackages = "packages refused" + m.Images = UnavailableImages{Reason: "images refused"} + + progress, err := m.Run(context.Background(), &PURLSource{PURLs: []string{"pkg:docker/library/alpine@3.20"}}) + if err != nil { + t.Fatalf("Run: %v", err) + } + if len(progress.Errors) != 1 || progress.Errors[0].Error != "images refused" { + t.Errorf("errors = %+v, want the image refusal", progress.Errors) + } +} diff --git a/internal/mirror/refresh.go b/internal/mirror/refresh.go new file mode 100644 index 0000000..3c2e094 --- /dev/null +++ b/internal/mirror/refresh.go @@ -0,0 +1,179 @@ +package mirror + +import ( + "context" + "fmt" + "slices" + "time" + + "github.com/git-pkgs/proxy/internal/database" + "github.com/git-pkgs/proxy/internal/handler" + "github.com/git-pkgs/purl" + "github.com/git-pkgs/registries" +) + +// Refresh mirrors new releases of the packages clients download most, so +// they are cached before the first client asks for them. +type Refresh struct { + // Top is how many packages per ecosystem are refreshed. + Top int + // Since is how recently a package must have been downloaded. + Since time.Duration + // MaxVersions stops a run after mirroring this many versions. 0 means + // no cap. + MaxVersions int + // MaxBytes stops a run once it has downloaded this much. It is checked + // before each version, so the last one may go over it. 0 means no cap. + MaxBytes int64 +} + +func (r Refresh) spent(tracker *progressTracker) bool { + return (r.MaxVersions > 0 && tracker.completed.Load() >= int64(r.MaxVersions)) || + (r.MaxBytes > 0 && tracker.bytes.Load() >= r.MaxBytes) +} + +// ReleaseLister lists every release of a package, with its publish time and +// status, for refreshes. +type ReleaseLister interface { + ListReleases(ctx context.Context, ecosystem, name string) ([]registries.Version, error) +} + +// ListReleases implements ReleaseLister. +func (r RegistryVersions) ListReleases(ctx context.Context, ecosystem, name string) ([]registries.Version, error) { + return r.fetchVersions(ctx, ecosystem, name) +} + +// releaseLister lists releases where Versions lists versions, so both come +// from the configured upstream. +func (m *Mirror) releaseLister() ReleaseLister { //nolint:ireturn // any lister will do + if lister, ok := m.Versions.(ReleaseLister); ok { + return lister + } + return RegistryVersions{} +} + +// Refresh mirrors, for each of the most used packages, the newest release +// of each major line it has a version cached on, as clients would be served +// it: releases within cooldown or on the denylist are left out. Packages it +// can't list are counted as failed. +func (m *Mirror) Refresh(ctx context.Context, r Refresh) (*Progress, error) { + ctx = handler.MirrorFetch(ctx) + cutoff := time.Now().Add(-r.Since) + packages, err := m.db.MostUsedPackages(cutoff, r.Top) + if err != nil { + return nil, fmt.Errorf("listing the most used packages: %w", err) + } + tracker := newProgressTracker() + tracker.phase.Store("downloading") + run := func(items []PackageVersion) bool { + for _, item := range items { + if ctx.Err() != nil { + return false + } + if r.spent(tracker) { + m.logger.Info("mirror refresh reached its cap for one run", + "mirrored", tracker.completed.Load(), "bytes", tracker.bytes.Load()) + return false + } + tracker.total.Add(1) + m.mirrorRecovered(ctx, item, tracker) + } + return true + } + for _, group := range byEcosystem(packages) { + if ix, ok := osIndexes[group[0].Ecosystem]; ok { + items, errs := m.indexRefreshItems(ctx, ix, group, cutoff) + for _, err := range errs { + m.recordFailure(tracker, PackageVersion{Ecosystem: ix.ecosystem}, err) + } + if !run(items) { + break + } + continue + } + done := true + for _, pkg := range group { + items, err := m.refreshItems(ctx, pkg) + if err != nil { + m.recordFailure(tracker, PackageVersion{Ecosystem: pkg.Ecosystem, Name: pkg.Name}, err) + continue + } + if done = run(items); !done { + break + } + } + if !done { + break + } + } + tracker.phase.Store("complete") + p := tracker.snapshot() + return &p, nil +} + +// byEcosystem splits packages, ordered by ecosystem, into one group per +// ecosystem. +func byEcosystem(packages []database.UsedPackage) [][]database.UsedPackage { + var groups [][]database.UsedPackage + for i, pkg := range packages { + if i == 0 || pkg.Ecosystem != packages[i-1].Ecosystem { + groups = append(groups, nil) + } + groups[len(groups)-1] = append(groups[len(groups)-1], pkg) + } + return groups +} + +// refreshItems returns the versions to mirror for a used package. +func (m *Mirror) refreshItems(ctx context.Context, pkg database.UsedPackage) ([]PackageVersion, error) { + p, err := purl.Parse(pkg.PURL) + if err != nil { + return nil, err + } + ecosystem, name, _ := mirrorTarget(p) + if !refreshable(ecosystem) { + return nil, nil + } + releases, err := m.releaseLister().ListReleases(ctx, ecosystem, name) + if err != nil { + return nil, fmt.Errorf("listing releases: %w", err) + } + + var cached []string + seen := map[string]bool{} + for _, f := range pkg.Files { + if !seen[f.Version] { + seen[f.Version] = true + cached = append(cached, f.Version) + } + } + allowed := func(v registries.Version) bool { + return m.proxy == nil || m.proxy.ReleaseAllowed(pkg.Ecosystem, pkg.Name, v.Number, v.PublishedAt) + } + + var items []PackageVersion + for _, version := range newestPerCachedLine(ecosystem, cached, releases, allowed) { + pv := PackageVersion{Ecosystem: ecosystem, Name: name, Version: version} + if eco, ok := fileEcosystems[ecosystem]; ok { + pv.variants = map[string]bool{} + for _, f := range pkg.Files { + for _, v := range eco.cachedVariants(f.Filename) { + pv.variants[v] = true + } + } + } + items = append(items, pv) + } + return items, nil +} + +// refreshable reports whether a refresh lists the releases of an +// ecosystem's packages. Images follow mirror.schedules, OS packages their +// repository indexes, and Julia files are cached by tree hash rather than by +// version. +func refreshable(ecosystem string) bool { + if isImageEcosystem(ecosystem) || osIndexes[ecosystem].ecosystem != "" || ecosystem == "julia" { + return false + } + return slices.Contains(registries.SupportedEcosystems(), purl.EcosystemToPURLType(ecosystem)) +} diff --git a/internal/mirror/refresh_harden_test.go b/internal/mirror/refresh_harden_test.go new file mode 100644 index 0000000..0af855d --- /dev/null +++ b/internal/mirror/refresh_harden_test.go @@ -0,0 +1,438 @@ +package mirror + +import ( + "context" + "net/http" + "reflect" + "slices" + "strings" + "testing" + "time" + + "github.com/git-pkgs/proxy/internal/denylist" + "github.com/git-pkgs/proxy/internal/handler" + "github.com/git-pkgs/registries" + "github.com/git-pkgs/registries/fetch" +) + +// debCurlPackages returns a Packages index listing curl at version. +func debCurlPackages(t *testing.T, version string) []byte { + t.Helper() + return gzipped(t, "Package: curl\nVersion: "+version+"\nArchitecture: amd64\nFilename: pool/main/c/curl/curl_"+version+"_amd64.deb\n\n") +} + +// TestRefreshDebianIndexPerSuite checks that suites sharing a pool are +// refreshed each on its own: a newer curl cached from trixie must not keep +// bookworm's security update from being mirrored. +func TestRefreshDebianIndexPerSuite(t *testing.T) { + m, fetcher, idx := setupIndexRefresh(t) + release := []byte("SHA256:\n 0000 1 main/binary-amd64/Packages.gz\n") + pool := idx.URL + "/debian/pool/main/c/curl/" + for suite, version := range map[string]string{"bookworm": "7.88.1-10", "trixie": "8.14.1-2"} { + idx.set("/debian/dists/"+suite+"/InRelease", release) + idx.set("/debian/dists/"+suite+"/main/binary-amd64/Packages.gz", debCurlPackages(t, version)) + clientFetchesCurl(t, m, "debian", idx.URL+"/debian/dists/"+suite+"/InRelease", + "deb", version, "curl_"+version+"_amd64.deb", pool+"curl_"+version+"_amd64.deb") + } + + idx.set("/debian/dists/bookworm/main/binary-amd64/Packages.gz", debCurlPackages(t, "7.88.1-10+deb12u8")) + idx.set("/debian/dists/trixie/main/binary-amd64/Packages.gz", debCurlPackages(t, "8.14.1-2+deb13u1")) + fetcher.reset() + progress := refreshOnce(t, m) + + want := []string{pool + "curl_7.88.1-10+deb12u8_amd64.deb", pool + "curl_8.14.1-2+deb13u1_amd64.deb"} + got := fetcher.fetched() + slices.Sort(got) + if !slices.Equal(got, want) || progress.Completed != 2 { + t.Errorf("progress = %+v, fetched %v; want %v", progress, got, want) + } +} + +// TestRefreshDebianIndexSkipsOtherSuite checks that a suite's version of a +// package is not mirrored when only a newer one is cached: clients of that +// suite never fetched the package. +func TestRefreshDebianIndexSkipsOtherSuite(t *testing.T) { + m, fetcher, idx := setupIndexRefresh(t) + release := []byte("SHA256:\n 0000 1 main/binary-amd64/Packages.gz\n") + pool := idx.URL + "/debian/pool/main/c/curl/" + idx.set("/debian/dists/trixie/InRelease", release) + idx.set("/debian/dists/trixie/main/binary-amd64/Packages.gz", debCurlPackages(t, "8.14.1-2")) + clientFetchesCurl(t, m, "debian", idx.URL+"/debian/dists/trixie/InRelease", + "deb", "8.14.1-2", "curl_8.14.1-2_amd64.deb", pool+"curl_8.14.1-2_amd64.deb") + // A bookworm client fetched its index but never curl. + idx.set("/debian/dists/bookworm/InRelease", release) + idx.set("/debian/dists/bookworm/main/binary-amd64/Packages.gz", debCurlPackages(t, "7.88.1-10+deb12u8")) + if _, _, err := m.proxy.FetchOrCacheMetadata(t.Context(), "debian", "key:bookworm", idx.URL+"/debian/dists/bookworm/InRelease", "*/*"); err != nil { + t.Fatal(err) + } + fetcher.reset() + + if progress := refreshOnce(t, m); progress.Completed != 0 || len(fetcher.fetched()) != 0 { + t.Errorf("progress = %+v, fetched %v; want nothing", progress, fetcher.fetched()) + } +} + +// TestRefreshRPMIndexListingSeveralVersions checks that a repository +// listing old versions next to the newest mirrors only the newest, and +// nothing once it is cached. +func TestRefreshRPMIndexListingSeveralVersions(t *testing.T) { + m, fetcher, idx := setupIndexRefresh(t) + base := "/fedora/updates/40/Everything/x86_64" + primary := func(rels ...string) []byte { + var pkgs string + for _, rel := range rels { + pkgs += `curlx86_64` + } + return gzipped(t, ``+pkgs+``) + } + idx.set(base+"/repodata/repomd.xml", []byte(``)) + idx.set(base+"/repodata/primary.xml.gz", primary("10")) + clientFetchesCurl(t, m, "rpm", idx.URL+base+"/repodata/repomd.xml", + "rpm", "8.6.0-10.fc40", "curl-8.6.0-10.fc40.x86_64.rpm", idx.URL+base+"/Packages/c/curl-8.6.0-10.fc40.x86_64.rpm") + + idx.set(base+"/repodata/primary.xml.gz", primary("10", "12", "11")) + fetcher.reset() + progress := refreshOnce(t, m) + want := []string{idx.URL + base + "/Packages/c/curl-8.6.0-12.fc40.x86_64.rpm"} + if !slices.Equal(fetcher.fetched(), want) || progress.Completed != 1 { + t.Fatalf("progress = %+v, fetched %v; want %v", progress, fetcher.fetched(), want) + } + + fetcher.reset() + if progress := refreshOnce(t, m); progress.Completed != 0 || len(fetcher.fetched()) != 0 { + t.Errorf("second run: progress = %+v, fetched %v; want nothing", progress, fetcher.fetched()) + } +} + +// TestRefreshIndexFailureDoesNotStopRun checks that an index that can't be +// read is counted as failed and the other indexes are still refreshed. +func TestRefreshIndexFailureDoesNotStopRun(t *testing.T) { + m, fetcher, idx := setupIndexRefresh(t) + release := []byte("SHA256:\n 0000 1 main/binary-amd64/Packages.gz\n") + pool := idx.URL + "/debian/pool/main/c/curl/" + for suite, version := range map[string]string{"bookworm": "7.88.1-10", "trixie": "8.14.1-2"} { + idx.set("/debian/dists/"+suite+"/InRelease", release) + idx.set("/debian/dists/"+suite+"/main/binary-amd64/Packages.gz", debCurlPackages(t, version)) + clientFetchesCurl(t, m, "debian", idx.URL+"/debian/dists/"+suite+"/InRelease", + "deb", version, "curl_"+version+"_amd64.deb", pool+"curl_"+version+"_amd64.deb") + } + idx.set("/debian/dists/bookworm/main/binary-amd64/Packages.gz", []byte("not gzip")) + idx.set("/debian/dists/trixie/main/binary-amd64/Packages.gz", debCurlPackages(t, "8.14.1-2+deb13u1")) + fetcher.reset() + + progress := refreshOnce(t, m) + want := []string{pool + "curl_8.14.1-2+deb13u1_amd64.deb"} + if !slices.Equal(fetcher.fetched(), want) || progress.Completed != 1 || progress.Failed != 1 { + t.Errorf("progress = %+v, fetched %v; want %v and one failure", progress, fetcher.fetched(), want) + } +} + +func TestNewestPerCachedLineGo(t *testing.T) { + allowAll := func(registries.Version) bool { return true } + for _, tt := range []struct { + name string + cached []string + releases []registries.Version + want []string + }{ + {"v prefix", []string{"v1.2.3"}, releases("v1.2.3", "v1.3.0"), []string{"v1.3.0"}}, + {"incompatible is its own line", []string{"v1.2.3"}, releases("v1.2.3", "v2.0.0+incompatible"), nil}, + {"pseudo-versions are prereleases", []string{"v1.2.3"}, releases("v1.2.3", "v1.2.4-0.20260101000000-abcdefabcdef"), nil}, + } { + t.Run(tt.name, func(t *testing.T) { + if got := newestPerCachedLine("golang", tt.cached, tt.releases, allowAll); !reflect.DeepEqual(got, tt.want) { + t.Errorf("newestPerCachedLine = %v, want %v", got, tt.want) + } + }) + } +} + +func TestRefreshScopedNPMPackage(t *testing.T) { + m, fetcher := setupRefreshMirror(t, "tarball") + cacheNPM(t, m, "@babel/core", "7.24.0") + m.Versions = stubReleases{"npm/@babel/core": oldReleases("7.24.0", "7.25.2")} + fetcher.reset() + + progress := refreshOnce(t, m) + if urls := fetcher.fetched(); progress.Completed != 1 || len(fetchedMatching(urls, "core-7.25.2.tgz")) != 1 { + t.Errorf("progress = %+v, fetched %v; want @babel/core 7.25.2", progress, urls) + } +} + +func TestRefreshSkipsDeniedRelease(t *testing.T) { + m, fetcher := setupRefreshMirror(t, "tarball") + cacheNPM(t, m, "lodash", "4.17.20") + m.Versions = stubReleases{"npm/lodash": oldReleases("4.17.20", "4.17.21", "4.17.22")} + policy, err := denylist.New([]string{"pkg:npm/lodash@4.17.22"}) + if err != nil { + t.Fatal(err) + } + m.proxy.Denylist = policy + fetcher.reset() + + progress := refreshOnce(t, m) + if urls := fetcher.fetched(); progress.Completed != 1 || len(fetchedMatching(urls, "lodash-4.17.21.tgz")) != 1 || len(fetchedMatching(urls, "4.17.22")) != 0 { + t.Errorf("progress = %+v, fetched %v; want 4.17.21, not the denied 4.17.22", progress, urls) + } +} + +func TestRefreshListingFailureDoesNotStopOthers(t *testing.T) { + m, fetcher := setupRefreshMirror(t, "tarball") + cacheNPM(t, m, "lodash", "4.17.20") + cacheNPM(t, m, "react", "18.3.0") + m.Versions = stubReleases{"npm/react": oldReleases("18.3.0", "18.3.1")} + fetcher.reset() + + progress := refreshOnce(t, m) + if urls := fetcher.fetched(); progress.Completed != 1 || progress.Failed != 1 || len(fetchedMatching(urls, "react-18.3.1.tgz")) != 1 { + t.Errorf("progress = %+v, fetched %v; want react refreshed and lodash failed", progress, urls) + } +} + +func TestRefreshStopsWhenCancelled(t *testing.T) { + m, fetcher := setupRefreshMirror(t, "tarball") + cacheNPM(t, m, "lodash", "4.17.20") + m.Versions = stubReleases{"npm/lodash": oldReleases("4.17.20", "4.17.21")} + fetcher.reset() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + progress, err := m.Refresh(ctx, Refresh{Top: 10, Since: time.Hour}) + if err != nil { + t.Fatalf("Refresh: %v", err) + } + if progress.Completed != 0 || len(fetcher.fetched()) != 0 { + t.Errorf("progress = %+v, fetched %v; want nothing after cancelling", progress, fetcher.fetched()) + } +} + +// TestRefreshDebianArchitectureAll checks that a package for every +// architecture, listed in each binary-* index rather than one of its own, +// is refreshed. +func TestRefreshDebianArchitectureAll(t *testing.T) { + m, fetcher, idx := setupIndexRefresh(t) + packages := func(version string) []byte { + return gzipped(t, "Package: ca-certificates\nVersion: "+version+"\nArchitecture: all\nFilename: pool/main/c/ca-certificates/ca-certificates_"+version+"_all.deb\n\n") + } + idx.set("/debian/dists/bookworm/InRelease", []byte("SHA256:\n 0000 1 main/binary-amd64/Packages.gz\n")) + idx.set("/debian/dists/bookworm/main/binary-amd64/Packages.gz", packages("20230311")) + pool := idx.URL + "/debian/pool/main/c/ca-certificates/" + if _, _, err := m.proxy.FetchOrCacheMetadata(t.Context(), "debian", "key:bookworm", idx.URL+"/debian/dists/bookworm/InRelease", "*/*"); err != nil { + t.Fatal(err) + } + result, err := m.proxy.GetOrFetchArtifactFromURL(t.Context(), "deb", "ca-certificates", "20230311", "ca-certificates_20230311_all.deb", pool+"ca-certificates_20230311_all.deb") + if err != nil { + t.Fatal(err) + } + _ = result.Reader.Close() + + idx.set("/debian/dists/bookworm/main/binary-amd64/Packages.gz", packages("20230311+deb12u1")) + fetcher.reset() + progress := refreshOnce(t, m) + if want := []string{pool + "ca-certificates_20230311+deb12u1_all.deb"}; !slices.Equal(fetcher.fetched(), want) || progress.Completed != 1 { + t.Errorf("progress = %+v, fetched %v; want %v", progress, fetcher.fetched(), want) + } +} + +// TestRefreshSkipsIndexPathsOutsideTheRepository checks that an index entry +// whose path leaves the repository base is not fetched. +func TestRefreshSkipsIndexPathsOutsideTheRepository(t *testing.T) { + for _, filename := range []string{ + "../other/pool/main/c/curl/curl_7.88.1-10+deb12u8_amd64.deb", + "pool/main/../../../other/curl_7.88.1-10+deb12u8_amd64.deb", + "/other/curl_7.88.1-10+deb12u8_amd64.deb", + } { + t.Run(filename, func(t *testing.T) { + m, fetcher, idx := setupIndexRefresh(t) + release := []byte("SHA256:\n 0000 1 main/binary-amd64/Packages.gz\n") + pool := idx.URL + "/debian/pool/main/c/curl/" + idx.set("/debian/dists/bookworm/InRelease", release) + idx.set("/debian/dists/bookworm/main/binary-amd64/Packages.gz", debCurlPackages(t, "7.88.1-10")) + clientFetchesCurl(t, m, "debian", idx.URL+"/debian/dists/bookworm/InRelease", + "deb", "7.88.1-10", "curl_7.88.1-10_amd64.deb", pool+"curl_7.88.1-10_amd64.deb") + + idx.set("/debian/dists/bookworm/main/binary-amd64/Packages.gz", gzipped(t, + "Package: curl\nVersion: 7.88.1-10+deb12u8\nArchitecture: amd64\nFilename: "+filename+"\n\n")) + fetcher.reset() + + if progress := refreshOnce(t, m); progress.Completed != 0 || len(fetcher.fetched()) != 0 { + t.Errorf("progress = %+v, fetched %v; want nothing", progress, fetcher.fetched()) + } + }) + } +} + +// TestRefreshRefusesIndexesOverTheSizeLimit checks that an index that +// decompresses to more than maxIndexBytes fails instead of being parsed in +// full. +func TestRefreshRefusesIndexesOverTheSizeLimit(t *testing.T) { + limit := maxIndexBytes + maxIndexBytes = 4 << 10 + t.Cleanup(func() { maxIndexBytes = limit }) + + m, fetcher, idx := setupIndexRefresh(t) + idx.set("/debian/dists/bookworm/InRelease", []byte("SHA256:\n 0000 1 main/binary-amd64/Packages.gz\n")) + idx.set("/debian/dists/bookworm/main/binary-amd64/Packages.gz", debCurlPackages(t, "7.88.1-10")) + clientFetchesCurl(t, m, "debian", idx.URL+"/debian/dists/bookworm/InRelease", + "deb", "7.88.1-10", "curl_7.88.1-10_amd64.deb", idx.URL+"/debian/pool/main/c/curl/curl_7.88.1-10_amd64.deb") + + padding := strings.Repeat("Package: filler\nVersion: 1\nArchitecture: amd64\nFilename: pool/main/f/filler/filler_1_amd64.deb\n\n", 100) + idx.set("/debian/dists/bookworm/main/binary-amd64/Packages.gz", gzipped(t, + "Package: curl\nVersion: 7.88.1-10+deb12u8\nArchitecture: amd64\nFilename: pool/main/c/curl/curl_7.88.1-10+deb12u8_amd64.deb\n\n"+padding)) + fetcher.reset() + + progress := refreshOnce(t, m) + if progress.Failed != 1 || len(progress.Errors) != 1 || !strings.Contains(progress.Errors[0].Error, "larger than") || len(fetcher.fetched()) != 0 { + t.Errorf("progress = %+v, fetched %v; want the index failing for its size", progress, fetcher.fetched()) + } +} + +// TestRefreshRefusesAPKIndexesOverTheSizeLimit checks that the limit also +// covers APKINDEX.tar.gz, which comes from the metadata cache rather than +// readIndex. +func TestRefreshRefusesAPKIndexesOverTheSizeLimit(t *testing.T) { + limit := maxIndexBytes + maxIndexBytes = 4 << 10 + t.Cleanup(func() { maxIndexBytes = limit }) + + m, fetcher, idx := setupIndexRefresh(t) + dir := "/alpine/v3.20/main/aarch64" + idx.set(dir+"/APKINDEX.tar.gz", apkIndexArchive(t, "P:curl\nV:8.9.0-r0\nA:aarch64\n\n")) + clientFetchesCurl(t, m, "alpine", idx.URL+dir+"/APKINDEX.tar.gz", + "alpine", "8.9.0-r0", "edge/v3.20/main/aarch64/curl-8.9.0-r0.apk", idx.URL+dir+"/curl-8.9.0-r0.apk") + + padding := strings.Repeat("P:filler\nV:1-r0\nA:aarch64\n\n", 400) + idx.set(dir+"/APKINDEX.tar.gz", apkIndexArchive(t, "P:curl\nV:8.9.1-r0\nA:aarch64\n\n"+padding)) + fetcher.reset() + + progress := refreshOnce(t, m) + if progress.Failed != 1 || len(progress.Errors) != 1 || !strings.Contains(progress.Errors[0].Error, "larger than") || len(fetcher.fetched()) != 0 { + t.Errorf("progress = %+v, fetched %v; want the index failing for its size", progress, fetcher.fetched()) + } +} + +// TestRefreshRefusesIndexDocumentsOverTheMetadataLimit checks that an +// InRelease larger than a metadata document may be fails its index. +func TestRefreshRefusesIndexDocumentsOverTheMetadataLimit(t *testing.T) { + m, fetcher, idx := setupIndexRefresh(t) + release := "SHA256:\n 0000 1 main/binary-amd64/Packages.gz\n" + idx.set("/debian/dists/bookworm/InRelease", []byte(release)) + idx.set("/debian/dists/bookworm/main/binary-amd64/Packages.gz", debCurlPackages(t, "7.88.1-10+deb12u8")) + clientFetchesCurl(t, m, "debian", idx.URL+"/debian/dists/bookworm/InRelease", + "deb", "7.88.1-10", "curl_7.88.1-10_amd64.deb", idx.URL+"/debian/pool/main/c/curl/curl_7.88.1-10_amd64.deb") + + m.proxy.MetadataMaxSize = int64(len(release)) + idx.set("/debian/dists/bookworm/InRelease", []byte(release+" 0000 1 contrib/binary-amd64/Packages.gz\n")) + fetcher.reset() + + progress := refreshOnce(t, m) + if progress.Failed != 1 || len(progress.Errors) != 1 || !strings.Contains(progress.Errors[0].Error, handler.ErrMetadataTooLarge.Error()) || len(fetcher.fetched()) != 0 { + t.Errorf("progress = %+v, fetched %v; want the index failing for its size", progress, fetcher.fetched()) + } +} + +// TestRefreshDebianSecurityPool checks the security archive's layout, whose +// pool is pool/updates/main while its InRelease lists main/binary-*. +func TestRefreshDebianSecurityPool(t *testing.T) { + m, fetcher, idx := setupIndexRefresh(t) + pool := idx.URL + "/debian-security/pool/updates/main/c/curl/" + packages := func(version string) []byte { + return gzipped(t, "Package: curl\nVersion: "+version+"\nArchitecture: amd64\nFilename: pool/updates/main/c/curl/curl_"+version+"_amd64.deb\n\n") + } + idx.set("/debian-security/dists/bookworm-security/InRelease", []byte("SHA256:\n 0000 1 main/binary-amd64/Packages.gz\n")) + idx.set("/debian-security/dists/bookworm-security/main/binary-amd64/Packages.gz", packages("7.88.1-10+deb12u7")) + clientFetchesCurl(t, m, "debian", idx.URL+"/debian-security/dists/bookworm-security/InRelease", + "deb", "7.88.1-10+deb12u7", "curl_7.88.1-10+deb12u7_amd64.deb", pool+"curl_7.88.1-10+deb12u7_amd64.deb") + + idx.set("/debian-security/dists/bookworm-security/main/binary-amd64/Packages.gz", packages("7.88.1-10+deb12u8")) + fetcher.reset() + progress := refreshOnce(t, m) + + want := []string{pool + "curl_7.88.1-10+deb12u8_amd64.deb"} + if !slices.Equal(fetcher.fetched(), want) || progress.Completed != 1 || progress.Failed != 0 { + t.Errorf("progress = %+v, fetched %v; want %v", progress, fetcher.fetched(), want) + } +} + +// TestRefreshDownloadsDoNotCountAsUse checks that a package nobody fetched +// within since drops out even though the refresh itself downloaded it. +func TestRefreshDownloadsDoNotCountAsUse(t *testing.T) { + m, _ := setupRefreshMirror(t, "tarball") + cacheNPM(t, m, "lodash", "4.17.20") + m.Versions = stubReleases{"npm/lodash": oldReleases("4.17.20", "4.17.21")} + if progress := refreshOnce(t, m); progress.Completed != 1 { + t.Fatalf("progress = %+v, want 4.17.21 mirrored", progress) + } + old := time.Now().Add(-48 * time.Hour).UTC() + if _, err := m.db.Exec(m.db.Rebind("UPDATE artifacts SET fetched_at = ? WHERE filename = ?"), old, "lodash-4.17.20.tgz"); err != nil { + t.Fatal(err) + } + + used, err := m.db.MostUsedPackages(time.Now().Add(-24*time.Hour), 10) + if err != nil { + t.Fatal(err) + } + if len(used) != 0 { + t.Errorf("MostUsedPackages = %+v, want none: only the refresh fetched lodash within since", used) + } +} + +// TestRefreshIndexReadIsNotAClientAccess checks that a refresh reading an +// index again doesn't keep it among those clients fetched within since. +func TestRefreshIndexReadIsNotAClientAccess(t *testing.T) { + m, _, idx := setupIndexRefresh(t) + dir := "/alpine/v3.20/main/aarch64" + idx.set(dir+"/APKINDEX.tar.gz", apkIndexArchive(t, "P:curl\nV:8.9.0-r0\nA:aarch64\n\n")) + clientFetchesCurl(t, m, "alpine", idx.URL+dir+"/APKINDEX.tar.gz", + "alpine", "8.9.0-r0", "edge/v3.20/main/aarch64/curl-8.9.0-r0.apk", idx.URL+dir+"/curl-8.9.0-r0.apk") + old := time.Now().Add(-2 * time.Hour).UTC() + if _, err := m.db.Exec(m.db.Rebind("UPDATE metadata_cache SET last_accessed_at = ?, updated_at = ?"), old, old); err != nil { + t.Fatal(err) + } + + if _, err := m.Refresh(context.Background(), Refresh{Top: 10, Since: 3 * time.Hour}); err != nil { + t.Fatal(err) + } + docs, err := m.db.RecentMetadataDocuments("alpine", time.Now().Add(-time.Hour)) + if err != nil { + t.Fatal(err) + } + if len(docs) != 0 { + t.Errorf("recent indexes = %+v, want none: only the refresh read the index", docs) + } +} + +// panickingFetcher serves files like servingFetcher but panics on URLs +// containing panicOn. +type panickingFetcher struct { + *servingFetcher + panicOn string +} + +func (f *panickingFetcher) Fetch(ctx context.Context, url string) (*fetch.Artifact, error) { + return f.FetchWithHeaders(ctx, url, nil) +} + +func (f *panickingFetcher) FetchWithHeaders(ctx context.Context, url string, h http.Header) (*fetch.Artifact, error) { + if strings.Contains(url, f.panicOn) { + panic("fetcher bug") + } + return f.servingFetcher.FetchWithHeaders(ctx, url, h) +} + +func TestRefreshRecoversFromPanic(t *testing.T) { + m, fetcher := setupRefreshMirror(t, "tarball") + cacheNPM(t, m, "lodash", "4.17.20") + cacheNPM(t, m, "react", "18.3.0") + m.Versions = stubReleases{ + "npm/lodash": oldReleases("4.17.20", "4.17.21"), + "npm/react": oldReleases("18.3.0", "18.3.1"), + } + m.proxy.Fetcher = &panickingFetcher{servingFetcher: fetcher, panicOn: "lodash-4.17.21"} + fetcher.reset() + + progress := refreshOnce(t, m) + if progress.Failed != 1 || progress.Completed != 1 || len(fetchedMatching(fetcher.fetched(), "react-18.3.1.tgz")) != 1 { + t.Errorf("progress = %+v, fetched %v; want lodash failed and react mirrored", progress, fetcher.fetched()) + } +} diff --git a/internal/mirror/refresh_index.go b/internal/mirror/refresh_index.go new file mode 100644 index 0000000..c54224e --- /dev/null +++ b/internal/mirror/refresh_index.go @@ -0,0 +1,350 @@ +package mirror + +import ( + "bytes" + "context" + "fmt" + "io" + "net/http" + "path" + "strings" + "time" + + "github.com/git-pkgs/proxy/internal/database" + "github.com/git-pkgs/proxy/internal/handler" + "github.com/git-pkgs/vers" +) + +// A Debian, Alpine or RPM client finds new versions in a repository index +// rather than in metadata per package. A refresh reads the indexes clients +// fetched again, from the URLs the metadata cache recorded, and mirrors the +// newer files they list of the packages downloaded most. + +// osIndex describes the repository index of one ecosystem. +type osIndex struct { + // ecosystem is what package files are cached under, metaEcosystem what + // the index documents are cached under. + ecosystem, metaEcosystem string + // scheme orders versions. + scheme string + // base returns the repository base package paths are relative to, for + // the URL of an index document a refresh starts from, or false for + // other documents. + base func(indexURL string) (string, bool) + // files lists the package files of the index document body fetched + // from indexURL. cached are the files of the most used packages under + // the repository base, for indexes that list their files in parts. + files func(ctx context.Context, m *Mirror, indexURL string, body []byte, cached []cachedOSFile) ([]indexFile, error) +} + +var osIndexes = map[string]osIndex{ + "alpine": { + ecosystem: "alpine", metaEcosystem: "alpine", scheme: "alpine", + base: func(u string) (string, bool) { + return strings.CutSuffix(u, "/APKINDEX.tar.gz") + }, + files: func(_ context.Context, _ *Mirror, indexURL string, body []byte, _ []cachedOSFile) ([]indexFile, error) { + return parseAPKIndex(bytes.NewReader(body), indexURL) + }, + }, + "deb": { + ecosystem: "deb", metaEcosystem: "debian", scheme: "deb", + base: func(u string) (string, bool) { + if !strings.HasSuffix(u, "/InRelease") && !strings.HasSuffix(u, "/Release") { + return "", false + } + base, _, ok := strings.Cut(u, "/dists/") + return base, ok + }, + files: debIndexFiles, + }, + "rpm": { + ecosystem: "rpm", metaEcosystem: "rpm", scheme: "rpm", + base: func(u string) (string, bool) { + return strings.CutSuffix(u, "/repodata/repomd.xml") + }, + files: rpmIndexFiles, + }, +} + +// cachedOSFile is a cached file of a most used package, by its path below a +// repository base. +type cachedOSFile struct { + file database.UsedFile + rel string + name, version, arch string +} + +func (f cachedOSFile) key() string { return f.name + "\x00" + f.arch } + +// indexRefreshItems returns the newer files the recently fetched indexes of +// an ecosystem list for packages, and an error per index it couldn't read. +func (m *Mirror) indexRefreshItems(ctx context.Context, ix osIndex, packages []database.UsedPackage, cutoff time.Time) ([]PackageVersion, []error) { + docs, err := m.db.RecentMetadataDocuments(ix.metaEcosystem, cutoff) + if err != nil { + return nil, []error{fmt.Errorf("listing %s indexes: %w", ix.metaEcosystem, err)} + } + var items []PackageVersion + var errs []error + seenIndex := map[string]bool{} + seenFile := map[string]bool{} + for _, doc := range docs { + base, ok := ix.base(doc.UpstreamURL) + if !ok || seenIndex[urlDir(doc.UpstreamURL)] { + continue + } + cached := cachedUnder(ix.ecosystem, base, packages) + if len(cached) == 0 { + continue + } + seenIndex[urlDir(doc.UpstreamURL)] = true + body, err := m.readIndexDocument(ctx, doc.UpstreamURL) + if err != nil { + errs = append(errs, fmt.Errorf("%s: %w", doc.UpstreamURL, err)) + continue + } + files, err := ix.files(ctx, m, doc.UpstreamURL, body, cached) + if err != nil { + errs = append(errs, fmt.Errorf("%s: %w", doc.UpstreamURL, err)) + continue + } + for _, item := range m.newerIndexFiles(ix, base, cached, files) { + if !seenFile[item.fileURL] { + seenFile[item.fileURL] = true + items = append(items, item) + } + } + } + return items, errs +} + +// cachedUnder returns the cached files of packages below base. +func cachedUnder(ecosystem, base string, packages []database.UsedPackage) []cachedOSFile { + var cached []cachedOSFile + for _, pkg := range packages { + for _, f := range pkg.Files { + rel, ok := strings.CutPrefix(f.UpstreamURL, base+"/") + if !ok { + continue + } + name, version, arch := handler.OSPackageIdentity(ecosystem, rel) + if name != "" { + cached = append(cached, cachedOSFile{file: f, rel: rel, name: name, version: version, arch: arch}) + } + } + } + return cached +} + +// newerIndexFiles returns, per package and architecture cached below base, +// the newest file the index lists when it isn't cached and an older version +// is. Suites sharing a pool are told apart that way: a newer version cached +// from another suite doesn't hide an update to this one, and a package only +// cached in a newer version than this suite has isn't mirrored for it. +func (m *Mirror) newerIndexFiles(ix osIndex, base string, cached []cachedOSFile, files []indexFile) []PackageVersion { + cachedByKey := map[string][]cachedOSFile{} + for _, c := range cached { + cachedByKey[c.key()] = append(cachedByKey[c.key()], c) + } + type candidate struct { + file indexFile + name, version string + } + newest := map[string]candidate{} + var order []string + for _, f := range files { + if !confinedIndexPath(f.Path) { + continue + } + name, version, arch := handler.OSPackageIdentity(ix.ecosystem, f.Path) + key := name + "\x00" + arch + if name == "" || len(cachedByKey[key]) == 0 { + continue + } + if m.proxy != nil && !m.proxy.ReleaseAllowed(ix.ecosystem, name, version, time.Time{}) { + continue + } + current, seen := newest[key] + if !seen { + order = append(order, key) + } + if !seen || vers.CompareWithScheme(version, current.version, ix.scheme) > 0 { + newest[key] = candidate{file: f, name: name, version: version} + } + } + + items := make([]PackageVersion, 0, len(order)) + for _, key := range order { + n := newest[key] + var older *cachedOSFile + for i, c := range cachedByKey[key] { + cmp := vers.CompareWithScheme(n.version, c.version, ix.scheme) + if cmp == 0 { + older = nil + break + } + if cmp > 0 && older == nil { + older = &cachedByKey[key][i] + } + } + if older == nil { + continue + } + cacheFilename := path.Base(n.file.Path) + if dir := path.Dir(older.file.Filename); dir != "." { + cacheFilename = dir + "/" + cacheFilename + } + items = append(items, PackageVersion{ + Ecosystem: ix.ecosystem, Name: n.name, Version: n.version, + fileURL: base + "/" + n.file.Path, cacheFilename: cacheFilename, digest: n.file.Digest, + }) + } + return items +} + +// confinedIndexPath reports whether an index entry's path is relative and +// stays below the repository base. +func confinedIndexPath(p string) bool { + return p != "" && !path.IsAbs(p) && path.Clean(p) == p && p != ".." && !strings.HasPrefix(p, "../") +} + +// debIndexFiles reads the Packages indexes an InRelease or Release file +// lists for the components and architectures of the cached files. +func debIndexFiles(ctx context.Context, m *Mirror, indexURL string, body []byte, cached []cachedOSFile) ([]indexFile, error) { + indexes := debPackagesIndexes(body) + wanted := map[string]bool{} + for _, c := range cached { + component, ok := debComponent(c.rel, indexes) + if !ok { + continue + } + if dir := component + "/binary-" + c.arch; indexes[dir] != "" { + wanted[dir] = true + continue + } + // Files for every architecture are listed in each binary-* index. + for dir := range indexes { + if strings.HasPrefix(dir, component+"/binary-") { + wanted[dir] = true + break + } + } + } + suite := urlDir(indexURL) + var files []indexFile + for dir := range wanted { + listed, err := m.readIndex(ctx, suite+"/"+indexes[dir], parseDebPackages) + if err != nil { + return nil, err + } + files = append(files, listed...) + } + return files, nil +} + +// debComponent returns the component of a pool file that the release file +// lists indexes for. It is the first segment after pool/, or the second, as +// in the security archive's pool/updates/main. +func debComponent(rel string, indexes map[string]string) (string, bool) { + rest, ok := strings.CutPrefix(rel, "pool/") + if !ok { + return "", false + } + first, rest, _ := strings.Cut(rest, "/") + second, _, _ := strings.Cut(rest, "/") + for _, component := range []string{first, second} { + for dir := range indexes { + if strings.HasPrefix(dir, component+"/binary-") { + return component, true + } + } + } + return "", false +} + +// rpmIndexFiles reads the primary metadata a repomd.xml points at. +func rpmIndexFiles(ctx context.Context, m *Mirror, indexURL string, body []byte, _ []cachedOSFile) ([]indexFile, error) { + primary, err := repomdPrimary(body) + if err != nil { + return nil, err + } + base := strings.TrimSuffix(indexURL, "/repodata/repomd.xml") + return m.readIndex(ctx, base+"/"+primary, parseRPMPrimary) +} + +// readIndexDocument reads the index document a refresh starts from directly +// from upstream. Read through the metadata cache it would count as a client +// fetching it, and the suite would never age out of since. It is held in +// memory, so it is limited like any metadata document. +func (m *Mirror) readIndexDocument(ctx context.Context, indexURL string) ([]byte, error) { + body, err := m.openIndex(ctx, indexURL) + if err != nil { + return nil, err + } + defer func() { _ = body.Close() }() + return m.proxy.ReadMetadata(body) +} + +// openIndex starts reading an index from upstream. +func (m *Mirror) openIndex(ctx context.Context, indexURL string) (io.ReadCloser, error) { + req, err := http.NewRequestWithContext(ctx, http.MethodGet, indexURL, nil) + if err != nil { + return nil, err + } + resp, err := m.proxy.HTTPClient.Do(req) + if err != nil { + return nil, err + } + if resp.StatusCode != http.StatusOK { + _ = resp.Body.Close() + return nil, fmt.Errorf("%s: upstream returned %d", indexURL, resp.StatusCode) + } + return resp.Body, nil +} + +// readIndex streams an index from upstream through parse, decompressed as +// its name says and limited to maxIndexBytes. It is read directly rather than through the metadata +// cache, since it can be far larger than a metadata document may be. +func (m *Mirror) readIndex(ctx context.Context, indexURL string, parse func(io.Reader) ([]indexFile, error)) ([]indexFile, error) { + body, err := m.openIndex(ctx, indexURL) + if err != nil { + return nil, err + } + defer func() { _ = body.Close() }() + r, err := decompressByName(indexURL, body) + if err != nil { + return nil, err + } + defer func() { _ = r.Close() }() + return parse(&indexLimitReader{r: r, url: indexURL, remaining: maxIndexBytes}) +} + +// maxIndexBytes bounds an index once decompressed. Debian's largest +// Packages files are under 100 MB and Fedora's primary.xml under 200 MB. +var maxIndexBytes int64 = 512 << 20 + +// indexLimitReader fails once more than maxIndexBytes have been read, so an +// oversized index fails rather than looking complete. +type indexLimitReader struct { + r io.Reader + url string + remaining int64 +} + +func (l *indexLimitReader) Read(p []byte) (int, error) { + if int64(len(p)) > l.remaining+1 { + p = p[:l.remaining+1] + } + n, err := l.r.Read(p) + if int64(n) > l.remaining { + return int(l.remaining), fmt.Errorf("%s: index larger than %d bytes", l.url, maxIndexBytes) + } + l.remaining -= int64(n) + return n, err +} + +// urlDir returns a URL without its last path segment. path.Dir would fold +// the slashes after the scheme. +func urlDir(u string) string { + return u[:strings.LastIndex(u, "/")] +} diff --git a/internal/mirror/refresh_index_limit_test.go b/internal/mirror/refresh_index_limit_test.go new file mode 100644 index 0000000..7512fc5 --- /dev/null +++ b/internal/mirror/refresh_index_limit_test.go @@ -0,0 +1,20 @@ +package mirror + +import ( + "io" + "strings" + "testing" +) + +func TestIndexLimitReaderAllowsExactlyTheLimit(t *testing.T) { + limit := maxIndexBytes + maxIndexBytes = 8 + t.Cleanup(func() { maxIndexBytes = limit }) + + if _, err := io.ReadAll(&indexLimitReader{r: strings.NewReader("12345678"), remaining: maxIndexBytes}); err != nil { + t.Errorf("index of exactly the limit: %v", err) + } + if _, err := io.ReadAll(&indexLimitReader{r: strings.NewReader("123456789"), remaining: maxIndexBytes}); err == nil { + t.Error("index one byte over the limit read without an error") + } +} diff --git a/internal/mirror/refresh_index_parse.go b/internal/mirror/refresh_index_parse.go new file mode 100644 index 0000000..9b0cd27 --- /dev/null +++ b/internal/mirror/refresh_index_parse.go @@ -0,0 +1,239 @@ +package mirror + +import ( + "archive/tar" + "bufio" + "compress/bzip2" + "compress/gzip" + "encoding/xml" + "errors" + "fmt" + "io" + "strings" + + "github.com/klauspost/compress/zstd" + "github.com/ulikunitz/xz" +) + +// indexFile is a package file a repository index lists: its path below the +// repository base and, where the index gives one, its SHA-256 digest. +type indexFile struct { + Path string + Digest string +} + +// maxIndexLine bounds one line of a Debian or Alpine index. +const maxIndexLine = 1 << 20 + +// parseAPKIndex reads the files an APKINDEX.tar.gz lists, limited to +// maxIndexBytes once decompressed. Its checksums cover only the control +// section of a package, so no digest is returned. +func parseAPKIndex(r io.Reader, indexURL string) ([]indexFile, error) { + gz, err := gzip.NewReader(r) + if err != nil { + return nil, err + } + defer func() { _ = gz.Close() }() + // An APKINDEX.tar.gz may be several gzip streams: the signature, then the + // index. Reading on across them finds the index whichever comes first. + tr := tar.NewReader(&indexLimitReader{r: gz, url: indexURL, remaining: maxIndexBytes}) + for { + hdr, err := tr.Next() + if errors.Is(err, io.EOF) { + return nil, errors.New("APKINDEX.tar.gz has no APKINDEX") + } + if err != nil { + return nil, err + } + if hdr.Name == "APKINDEX" { + return parseAPKIndexText(tr) + } + } +} + +func parseAPKIndexText(r io.Reader) ([]indexFile, error) { + var files []indexFile + var name, version string + flush := func() { + if name != "" && version != "" { + files = append(files, indexFile{Path: name + "-" + version + ".apk"}) + } + name, version = "", "" + } + scanner := bufio.NewScanner(r) + scanner.Buffer(nil, maxIndexLine) + for scanner.Scan() { + line := scanner.Text() + switch { + case line == "": + flush() + case strings.HasPrefix(line, "P:"): + name = line[2:] + case strings.HasPrefix(line, "V:"): + version = line[2:] + } + } + flush() + return files, scanner.Err() +} + +// debIndexPreference ranks the compressions of a Packages index, best first. +var debIndexPreference = []string{".xz", ".gz", ".bz2", ""} + +// debPackagesIndexes returns, per component/binary-arch directory, the path +// of the Packages index a Release or InRelease file lists, in the best +// compression it offers. +func debPackagesIndexes(release []byte) map[string]string { + listed := map[string]bool{} + inSHA256 := false + for _, line := range strings.Split(string(release), "\n") { + line = strings.TrimRight(line, "\r") + if !strings.HasPrefix(line, " ") { + inSHA256 = line == "SHA256:" + continue + } + if !inSHA256 { + continue + } + fields := strings.Fields(line) + if len(fields) == 3 { //nolint:mnd // checksum, size, path + listed[fields[2]] = true + } + } + indexes := map[string]string{} + for path := range listed { + dir, file, ok := strings.Cut(path, "/Packages") + if !ok || !strings.Contains(dir, "/binary-") || strings.Contains(file, "/") { + continue + } + for _, ext := range debIndexPreference { + if listed[dir+"/Packages"+ext] { + indexes[dir] = dir + "/Packages" + ext + break + } + } + } + return indexes +} + +// parseDebPackages reads the files a Packages index lists. +func parseDebPackages(r io.Reader) ([]indexFile, error) { + var files []indexFile + var current indexFile + flush := func() { + if current.Path != "" { + files = append(files, current) + } + current = indexFile{} + } + scanner := bufio.NewScanner(r) + scanner.Buffer(nil, maxIndexLine) + for scanner.Scan() { + line := scanner.Text() + if line == "" { + flush() + continue + } + key, value, ok := strings.Cut(line, ": ") + if !ok || strings.HasPrefix(line, " ") { + continue + } + switch key { + case "Filename": + current.Path = value + case "SHA256": + current.Digest = "sha256:" + value + } + } + flush() + return files, scanner.Err() +} + +// repomdPrimary returns the location of the primary metadata a repomd.xml +// points at. +func repomdPrimary(body []byte) (string, error) { + var doc struct { + Data []struct { + Type string `xml:"type,attr"` + Location struct { + Href string `xml:"href,attr"` + } `xml:"location"` + } `xml:"data"` + } + if err := xml.Unmarshal(body, &doc); err != nil { + return "", err + } + for _, d := range doc.Data { + if d.Type == "primary" && d.Location.Href != "" { + return d.Location.Href, nil + } + } + return "", errors.New("repomd.xml lists no primary metadata") +} + +// parseRPMPrimary reads the binary packages a primary.xml lists, one at a +// time. Source packages are left out. +func parseRPMPrimary(r io.Reader) ([]indexFile, error) { + dec := xml.NewDecoder(r) + var files []indexFile + for { + tok, err := dec.Token() + if errors.Is(err, io.EOF) { + return files, nil + } + if err != nil { + return nil, err + } + start, ok := tok.(xml.StartElement) + if !ok || start.Name.Local != "package" { + continue + } + var pkg struct { + Arch string `xml:"arch"` + Checksum struct { + Type string `xml:"type,attr"` + Value string `xml:",chardata"` + } `xml:"checksum"` + Location struct { + Href string `xml:"href,attr"` + } `xml:"location"` + } + if err := dec.DecodeElement(&pkg, &start); err != nil { + return nil, err + } + if pkg.Arch == "src" || pkg.Location.Href == "" { + continue + } + file := indexFile{Path: pkg.Location.Href} + if pkg.Checksum.Type == "sha256" { + file.Digest = "sha256:" + strings.TrimSpace(pkg.Checksum.Value) + } + files = append(files, file) + } +} + +// decompressByName returns r decompressed as the extension of name says. +func decompressByName(name string, r io.Reader) (io.ReadCloser, error) { + switch { + case strings.HasSuffix(name, ".gz"): + return gzip.NewReader(r) + case strings.HasSuffix(name, ".xz"): + x, err := xz.NewReader(r) + if err != nil { + return nil, err + } + return io.NopCloser(x), nil + case strings.HasSuffix(name, ".zst"): + z, err := zstd.NewReader(r) + if err != nil { + return nil, err + } + return z.IOReadCloser(), nil + case strings.HasSuffix(name, ".bz2"): + return io.NopCloser(bzip2.NewReader(r)), nil + case strings.HasSuffix(name, ".xml"), !strings.Contains(name[strings.LastIndex(name, "/")+1:], "."): + return io.NopCloser(r), nil + default: + return nil, fmt.Errorf("unsupported compression: %s", name) + } +} diff --git a/internal/mirror/refresh_index_parse_test.go b/internal/mirror/refresh_index_parse_test.go new file mode 100644 index 0000000..934256e --- /dev/null +++ b/internal/mirror/refresh_index_parse_test.go @@ -0,0 +1,188 @@ +package mirror + +import ( + "archive/tar" + "bytes" + "compress/gzip" + "reflect" + "strings" + "testing" + + "github.com/klauspost/compress/zstd" +) + +// apkIndexArchive packs an APKINDEX into the tar.gz Alpine serves. +func apkIndexArchive(t *testing.T, index string) []byte { + t.Helper() + var buf bytes.Buffer + gz := gzip.NewWriter(&buf) + tw := tar.NewWriter(gz) + for name, body := range map[string]string{"DESCRIPTION": "v3.20.3-1-g0000000", "APKINDEX": index} { + if err := tw.WriteHeader(&tar.Header{Name: name, Mode: 0o644, Size: int64(len(body))}); err != nil { + t.Fatal(err) + } + if _, err := tw.Write([]byte(body)); err != nil { + t.Fatal(err) + } + } + if err := tw.Close(); err != nil { + t.Fatal(err) + } + if err := gz.Close(); err != nil { + t.Fatal(err) + } + return buf.Bytes() +} + +func TestParseAPKIndex(t *testing.T) { + index := "C:Q1abc=\nP:curl\nV:8.9.1-r0\nA:aarch64\nS:100\n\nC:Q1def=\nP:busybox\nV:1.36.1-r29\nA:aarch64\n\n" + got, err := parseAPKIndex(bytes.NewReader(apkIndexArchive(t, index)), "APKINDEX.tar.gz") + if err != nil { + t.Fatal(err) + } + want := []indexFile{{Path: "curl-8.9.1-r0.apk"}, {Path: "busybox-1.36.1-r29.apk"}} + if !reflect.DeepEqual(got, want) { + t.Errorf("parseAPKIndex = %+v, want %+v", got, want) + } +} + +const debRelease = `-----BEGIN PGP SIGNED MESSAGE----- +Hash: SHA256 + +Origin: Debian +Suite: stable +Codename: bookworm +Architectures: all amd64 arm64 +Components: main contrib +MD5Sum: + 0123 100 main/binary-amd64/Packages.xz +SHA256: + aaaa 1000 main/binary-amd64/Packages + bbbb 200 main/binary-amd64/Packages.xz + cccc 300 main/binary-amd64/Packages.gz + dddd 400 main/binary-arm64/Packages.gz + eeee 500 contrib/binary-amd64/Packages.xz + ffff 600 main/i18n/Translation-en.bz2 +-----BEGIN PGP SIGNATURE----- +xyz +-----END PGP SIGNATURE----- +` + +func TestDebPackagesIndexes(t *testing.T) { + got := debPackagesIndexes([]byte(debRelease)) + want := map[string]string{ + "main/binary-amd64": "main/binary-amd64/Packages.xz", + "main/binary-arm64": "main/binary-arm64/Packages.gz", + "contrib/binary-amd64": "contrib/binary-amd64/Packages.xz", + } + if !reflect.DeepEqual(got, want) { + t.Errorf("debPackagesIndexes = %v, want %v", got, want) + } +} + +func TestParseDebPackages(t *testing.T) { + packages := `Package: curl +Version: 7.88.1-10+deb12u8 +Architecture: amd64 +Description: a tool + with a long description +Filename: pool/main/c/curl/curl_7.88.1-10+deb12u8_amd64.deb +SHA256: 1111 + +Package: zlib1g +Version: 1:1.2.13.dfsg-1 +Architecture: amd64 +Filename: pool/main/z/zlib/zlib1g_1.2.13.dfsg-1_amd64.deb +SHA256: 2222 +` + got, err := parseDebPackages(strings.NewReader(packages)) + if err != nil { + t.Fatal(err) + } + want := []indexFile{ + {Path: "pool/main/c/curl/curl_7.88.1-10+deb12u8_amd64.deb", Digest: "sha256:1111"}, + {Path: "pool/main/z/zlib/zlib1g_1.2.13.dfsg-1_amd64.deb", Digest: "sha256:2222"}, + } + if !reflect.DeepEqual(got, want) { + t.Errorf("parseDebPackages = %+v, want %+v", got, want) + } +} + +const repomd = ` + + 1700000000 + + + +` + +func TestRepomdPrimary(t *testing.T) { + got, err := repomdPrimary([]byte(repomd)) + if err != nil || got != "repodata/bbbb-primary.xml.zst" { + t.Errorf("repomdPrimary = %q, %v", got, err) + } + if _, err := repomdPrimary([]byte(``)); err == nil { + t.Error("repomdPrimary accepted a repomd without primary") + } +} + +const rpmPrimary = ` + + + curl + x86_64 + + 3333 + + + + curl + src + + 4444 + + + + tzdata + noarch + + 5555 + + + +` + +func TestParseRPMPrimary(t *testing.T) { + got, err := parseRPMPrimary(strings.NewReader(rpmPrimary)) + if err != nil { + t.Fatal(err) + } + want := []indexFile{ + {Path: "Packages/c/curl-8.6.0-10.fc40.x86_64.rpm", Digest: "sha256:3333"}, + {Path: "Packages/t/tzdata-2024a-5.fc40.noarch.rpm"}, + } + if !reflect.DeepEqual(got, want) { + t.Errorf("parseRPMPrimary = %+v, want %+v", got, want) + } +} + +func TestDecompressByName(t *testing.T) { + var gz bytes.Buffer + w := gzip.NewWriter(&gz) + _, _ = w.Write([]byte("hello")) + _ = w.Close() + enc, _ := zstd.NewWriter(nil) + zst := enc.EncodeAll([]byte("hello"), nil) + + for name, data := range map[string][]byte{"Packages": []byte("hello"), "Packages.gz": gz.Bytes(), "primary.xml.zst": zst} { + r, err := decompressByName(name, bytes.NewReader(data)) + if err != nil { + t.Fatalf("%s: %v", name, err) + } + var out bytes.Buffer + if _, err := out.ReadFrom(r); err != nil || out.String() != "hello" { + t.Errorf("%s: got %q, %v", name, out.String(), err) + } + _ = r.Close() + } +} diff --git a/internal/mirror/refresh_index_test.go b/internal/mirror/refresh_index_test.go new file mode 100644 index 0000000..1f66c38 --- /dev/null +++ b/internal/mirror/refresh_index_test.go @@ -0,0 +1,231 @@ +package mirror + +import ( + "bytes" + "compress/gzip" + "context" + "net/http" + "net/http/httptest" + "slices" + "sync" + "testing" + "time" +) + +// indexServer serves repository index documents that a test can change. +type indexServer struct { + *httptest.Server + mu sync.Mutex + docs map[string][]byte +} + +func newIndexServer(t *testing.T) *indexServer { + t.Helper() + s := &indexServer{docs: map[string][]byte{}} + s.Server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + s.mu.Lock() + body, ok := s.docs[r.URL.Path] + s.mu.Unlock() + if !ok { + http.NotFound(w, r) + return + } + _, _ = w.Write(body) + })) + t.Cleanup(s.Close) + return s +} + +func (s *indexServer) set(path string, body []byte) { + s.mu.Lock() + defer s.mu.Unlock() + s.docs[path] = body +} + +func gzipped(t *testing.T, s string) []byte { + t.Helper() + var buf bytes.Buffer + w := gzip.NewWriter(&buf) + if _, err := w.Write([]byte(s)); err != nil { + t.Fatal(err) + } + if err := w.Close(); err != nil { + t.Fatal(err) + } + return buf.Bytes() +} + +// setupIndexRefresh returns a mirror whose package files come from a +// servingFetcher and whose indexes come from an indexServer. +func setupIndexRefresh(t *testing.T) (*Mirror, *servingFetcher, *indexServer) { + t.Helper() + m, fetcher := setupRefreshMirror(t, "package") + idx := newIndexServer(t) + m.proxy.HTTPClient = idx.Client() + m.proxy.CacheMetadata = true + return m, fetcher, idx +} + +// clientFetchesCurl caches an index document and a curl package file the +// way the handlers do for a client. +func clientFetchesCurl(t *testing.T, m *Mirror, metaEcosystem, indexURL, ecosystem, version, cacheFilename, fileURL string) { + t.Helper() + ctx := context.Background() + if _, _, err := m.proxy.FetchOrCacheMetadata(ctx, metaEcosystem, "key:"+indexURL, indexURL, "*/*"); err != nil { + t.Fatalf("fetching %s: %v", indexURL, err) + } + result, err := m.proxy.GetOrFetchArtifactFromURL(ctx, ecosystem, "curl", version, cacheFilename, fileURL) + if err != nil { + t.Fatalf("fetching %s: %v", fileURL, err) + } + _ = result.Reader.Close() +} + +func refreshOnce(t *testing.T, m *Mirror) *Progress { + t.Helper() + progress, err := m.Refresh(context.Background(), Refresh{Top: 10, Since: time.Hour}) + if err != nil { + t.Fatalf("Refresh: %v", err) + } + return progress +} + +func cachedNames(t *testing.T, m *Mirror, ecosystem, filename string) []string { + t.Helper() + names, err := m.db.CachedArtifactNames(ecosystem, filename) + if err != nil { + t.Fatal(err) + } + return names +} + +func TestRefreshAlpineIndex(t *testing.T) { + m, fetcher, idx := setupIndexRefresh(t) + dir := "/alpine/v3.20/main/aarch64" + idx.set(dir+"/APKINDEX.tar.gz", apkIndexArchive(t, "P:curl\nV:8.9.0-r0\nA:aarch64\n\nP:busybox\nV:1.36.1-r29\n\n")) + clientFetchesCurl(t, m, "alpine", idx.URL+dir+"/APKINDEX.tar.gz", + "alpine", "8.9.0-r0", "edge/v3.20/main/aarch64/curl-8.9.0-r0.apk", idx.URL+dir+"/curl-8.9.0-r0.apk") + + // A new release of curl; busybox was never downloaded and stays out. + idx.set(dir+"/APKINDEX.tar.gz", apkIndexArchive(t, "P:curl\nV:8.9.1-r0\nA:aarch64\n\nP:busybox\nV:1.36.1-r30\n\n")) + fetcher.reset() + progress := refreshOnce(t, m) + + if want := []string{idx.URL + dir + "/curl-8.9.1-r0.apk"}; !slices.Equal(fetcher.fetched(), want) || progress.Completed != 1 { + t.Fatalf("progress = %+v, fetched %v; want %v", progress, fetcher.fetched(), want) + } + // Cached where the APK handler looks for it. + if names := cachedNames(t, m, "alpine", "edge/v3.20/main/aarch64/curl-8.9.1-r0.apk"); !slices.Equal(names, []string{"curl"}) { + t.Errorf("cached names = %v, want [curl]", names) + } + + fetcher.reset() + if progress := refreshOnce(t, m); progress.Completed != 0 || len(fetcher.fetched()) != 0 { + t.Errorf("second run: progress = %+v, fetched %v; want nothing", progress, fetcher.fetched()) + } +} + +func TestRefreshIndexNeverDowngrades(t *testing.T) { + m, fetcher, idx := setupIndexRefresh(t) + dir := "/alpine/v3.20/main/aarch64" + idx.set(dir+"/APKINDEX.tar.gz", apkIndexArchive(t, "P:curl\nV:8.9.1-r0\n\n")) + clientFetchesCurl(t, m, "alpine", idx.URL+dir+"/APKINDEX.tar.gz", + "alpine", "8.9.1-r0", "edge/v3.20/main/aarch64/curl-8.9.1-r0.apk", idx.URL+dir+"/curl-8.9.1-r0.apk") + idx.set(dir+"/APKINDEX.tar.gz", apkIndexArchive(t, "P:curl\nV:8.9.0-r0\n\n")) + fetcher.reset() + + if progress := refreshOnce(t, m); progress.Completed != 0 || len(fetcher.fetched()) != 0 { + t.Errorf("progress = %+v, fetched %v; want nothing", progress, fetcher.fetched()) + } +} + +func TestRefreshDebianIndex(t *testing.T) { + m, fetcher, idx := setupIndexRefresh(t) + release := []byte("Suite: stable\nSHA256:\n 0000 1 main/binary-amd64/Packages.gz\n 0000 1 main/binary-arm64/Packages.gz\n") + packages := func(curl string) []byte { + return gzipped(t, "Package: curl\nVersion: "+curl+"\nArchitecture: amd64\nFilename: pool/main/c/curl/curl_"+curl+"_amd64.deb\nSHA256: "+ + "bc4a71180870f7945155fbb02f4b0a2e3faa2a62d6d31b7039013055ed19869a\n\n"+ + "Package: zlib1g\nVersion: 1:1.2.13.dfsg-1\nArchitecture: amd64\nFilename: pool/main/z/zlib/zlib1g_1.2.13.dfsg-1_amd64.deb\n\n") + } + idx.set("/debian/dists/bookworm/InRelease", release) + idx.set("/debian/dists/bookworm/main/binary-amd64/Packages.gz", packages("7.88.1-10")) + clientFetchesCurl(t, m, "debian", idx.URL+"/debian/dists/bookworm/InRelease", + "deb", "7.88.1-10", "curl_7.88.1-10_amd64.deb", idx.URL+"/debian/pool/main/c/curl/curl_7.88.1-10_amd64.deb") + + idx.set("/debian/dists/bookworm/main/binary-amd64/Packages.gz", packages("7.88.1-10+deb12u8")) + fetcher.reset() + progress := refreshOnce(t, m) + + // Only the amd64 index is read: nothing was downloaded for arm64. The + // file is checked against the index's SHA-256 of "package". + want := []string{idx.URL + "/debian/pool/main/c/curl/curl_7.88.1-10+deb12u8_amd64.deb"} + if !slices.Equal(fetcher.fetched(), want) || progress.Completed != 1 || progress.Failed != 0 { + t.Fatalf("progress = %+v, fetched %v; want %v", progress, fetcher.fetched(), want) + } + if names := cachedNames(t, m, "deb", "curl_7.88.1-10+deb12u8_amd64.deb"); !slices.Equal(names, []string{"curl"}) { + t.Errorf("cached names = %v, want [curl]", names) + } +} + +func TestRefreshDebianIndexChecksDigest(t *testing.T) { + m, fetcher, idx := setupIndexRefresh(t) + idx.set("/debian/dists/bookworm/InRelease", []byte("SHA256:\n 0000 1 main/binary-amd64/Packages\n")) + idx.set("/debian/dists/bookworm/main/binary-amd64/Packages", []byte("Package: curl\nFilename: pool/main/c/curl/curl_7.88.1-10_amd64.deb\n\n")) + clientFetchesCurl(t, m, "debian", idx.URL+"/debian/dists/bookworm/InRelease", + "deb", "7.88.1-10", "curl_7.88.1-10_amd64.deb", idx.URL+"/debian/pool/main/c/curl/curl_7.88.1-10_amd64.deb") + idx.set("/debian/dists/bookworm/main/binary-amd64/Packages", []byte( + "Package: curl\nFilename: pool/main/c/curl/curl_7.88.1-11_amd64.deb\nSHA256: 0000000000000000000000000000000000000000000000000000000000000000\n\n")) + fetcher.reset() + + progress := refreshOnce(t, m) + if progress.Failed != 1 || progress.Completed != 0 { + t.Errorf("progress = %+v, want the file failing its digest", progress) + } + if names := cachedNames(t, m, "deb", "curl_7.88.1-11_amd64.deb"); len(names) != 0 { + t.Errorf("a file failing its digest was cached as %v", names) + } +} + +func TestRefreshRPMIndex(t *testing.T) { + m, fetcher, idx := setupIndexRefresh(t) + base := "/fedora/updates/40/Everything/x86_64" + primary := func(rel string) []byte { + return gzipped(t, `curlx86_64`+ + ``) + } + repomdFor := func(href string) []byte { + return []byte(``) + } + idx.set(base+"/repodata/repomd.xml", repomdFor("repodata/aaaa-primary.xml.gz")) + idx.set(base+"/repodata/aaaa-primary.xml.gz", primary("10")) + clientFetchesCurl(t, m, "rpm", idx.URL+base+"/repodata/repomd.xml", + "rpm", "8.6.0-10.fc40", "curl-8.6.0-10.fc40.x86_64.rpm", idx.URL+base+"/Packages/c/curl-8.6.0-10.fc40.x86_64.rpm") + + idx.set(base+"/repodata/repomd.xml", repomdFor("repodata/bbbb-primary.xml.gz")) + idx.set(base+"/repodata/bbbb-primary.xml.gz", primary("11")) + fetcher.reset() + progress := refreshOnce(t, m) + + want := []string{idx.URL + base + "/Packages/c/curl-8.6.0-11.fc40.x86_64.rpm"} + if !slices.Equal(fetcher.fetched(), want) || progress.Completed != 1 { + t.Fatalf("progress = %+v, fetched %v; want %v", progress, fetcher.fetched(), want) + } + if names := cachedNames(t, m, "rpm", "curl-8.6.0-11.fc40.x86_64.rpm"); !slices.Equal(names, []string{"curl"}) { + t.Errorf("cached names = %v, want [curl]", names) + } +} + +func TestRefreshIndexWithoutRecordedURLDoesNothing(t *testing.T) { + m, fetcher, idx := setupIndexRefresh(t) + result, err := m.proxy.GetOrFetchArtifactFromURL(context.Background(), "alpine", "curl", "8.9.0-r0", + "edge/v3.20/main/aarch64/curl-8.9.0-r0.apk", idx.URL+"/alpine/v3.20/main/aarch64/curl-8.9.0-r0.apk") + if err != nil { + t.Fatal(err) + } + _ = result.Reader.Close() + fetcher.reset() + + if progress := refreshOnce(t, m); progress.Completed != 0 || progress.Failed != 0 || len(fetcher.fetched()) != 0 { + t.Errorf("progress = %+v, fetched %v; want nothing", progress, fetcher.fetched()) + } +} diff --git a/internal/mirror/refresh_test.go b/internal/mirror/refresh_test.go new file mode 100644 index 0000000..97624d6 --- /dev/null +++ b/internal/mirror/refresh_test.go @@ -0,0 +1,459 @@ +package mirror + +import ( + "context" + "fmt" + "io" + "net/http" + "slices" + "strings" + "sync" + "testing" + "time" + + "github.com/git-pkgs/cooldown" + "github.com/git-pkgs/registries" + "github.com/git-pkgs/registries/fetch" +) + +// servingFetcher answers every fetch with body and records the URLs. +type servingFetcher struct { + body string + mu sync.Mutex + urls []string +} + +func (f *servingFetcher) Fetch(ctx context.Context, url string) (*fetch.Artifact, error) { + return f.FetchWithHeaders(ctx, url, nil) +} + +func (f *servingFetcher) FetchWithHeaders(_ context.Context, url string, _ http.Header) (*fetch.Artifact, error) { + f.mu.Lock() + f.urls = append(f.urls, url) + f.mu.Unlock() + return &fetch.Artifact{Body: io.NopCloser(strings.NewReader(f.body)), Size: int64(len(f.body)), ContentType: "application/octet-stream"}, nil +} + +func (f *servingFetcher) Head(context.Context, string) (int64, string, error) { + return int64(len(f.body)), "application/octet-stream", nil +} + +func (f *servingFetcher) fetched() []string { + f.mu.Lock() + defer f.mu.Unlock() + return append([]string(nil), f.urls...) +} + +func (f *servingFetcher) reset() { + f.mu.Lock() + defer f.mu.Unlock() + f.urls = nil +} + +// stubReleases lists releases by "ecosystem/name". +type stubReleases map[string][]registries.Version + +func (s stubReleases) ListReleases(_ context.Context, ecosystem, name string) ([]registries.Version, error) { + r, ok := s[ecosystem+"/"+name] + if !ok { + return nil, fmt.Errorf("%w: %s/%s", registries.ErrNotFound, ecosystem, name) + } + return r, nil +} + +func (s stubReleases) ListVersions(ctx context.Context, ecosystem, name string) ([]string, error) { + r, err := s.ListReleases(ctx, ecosystem, name) + numbers := make([]string, len(r)) + for i, v := range r { + numbers[i] = v.Number + } + return numbers, err +} + +func (s stubReleases) FindVersion(ctx context.Context, ecosystem, name, version string) (registries.Version, error) { + r, err := s.ListReleases(ctx, ecosystem, name) + if err != nil { + return registries.Version{}, err + } + for _, v := range r { + if v.Number == version { + return v, nil + } + } + return registries.Version{}, registries.ErrNotFound +} + +func oldReleases(numbers ...string) []registries.Version { + r := releases(numbers...) + for i := range r { + r[i].PublishedAt = time.Now().Add(-time.Duration(len(r)-i) * 30 * 24 * time.Hour) + } + return r +} + +func setupRefreshMirror(t *testing.T, body string) (*Mirror, *servingFetcher) { + t.Helper() + m := setupTestMirror(t, 1) + fetcher := &servingFetcher{body: body} + m.proxy.Fetcher = fetcher + return m, fetcher +} + +// cacheNPM downloads a version the way a client would, so it counts as used. +func cacheNPM(t *testing.T, m *Mirror, name, version string) { + t.Helper() + result, err := m.proxy.GetOrFetchArtifact(context.Background(), "npm", name, version, "") + if err != nil { + t.Fatalf("caching %s@%s: %v", name, version, err) + } + _ = result.Reader.Close() +} + +func fetchedMatching(urls []string, part string) []string { + var out []string + for _, u := range urls { + if strings.Contains(u, part) { + out = append(out, u) + } + } + return out +} + +func TestRefreshMirrorsNewerVersionOnCachedLine(t *testing.T) { + m, fetcher := setupRefreshMirror(t, "tarball") + cacheNPM(t, m, "lodash", "4.17.20") + m.Versions = stubReleases{"npm/lodash": oldReleases("4.17.20", "4.17.21", "5.0.0")} + fetcher.reset() + + progress, err := m.Refresh(context.Background(), Refresh{Top: 10, Since: 24 * time.Hour}) + if err != nil { + t.Fatalf("Refresh: %v", err) + } + if progress.Completed != 1 || progress.Failed != 0 { + t.Errorf("progress = %+v, want one mirrored", progress) + } + urls := fetcher.fetched() + if len(fetchedMatching(urls, "lodash-4.17.21.tgz")) != 1 || len(fetchedMatching(urls, "5.0.0")) != 0 { + t.Errorf("fetched %v, want lodash 4.17.21 only", urls) + } + + // The new version is cached now, so the next run has nothing to do. + progress, err = m.Refresh(context.Background(), Refresh{Top: 10, Since: 24 * time.Hour}) + if err != nil { + t.Fatalf("second Refresh: %v", err) + } + if progress.Completed != 0 || progress.Failed != 0 { + t.Errorf("second run progress = %+v, want nothing to do", progress) + } +} + +func TestRefreshKeepsCooldown(t *testing.T) { + m, fetcher := setupRefreshMirror(t, "tarball") + cacheNPM(t, m, "lodash", "4.17.20") + r := oldReleases("4.17.20", "4.17.21") + r[1].PublishedAt = time.Now().Add(-time.Hour) + m.Versions = stubReleases{"npm/lodash": r} + m.proxy.Cooldown = &cooldown.Config{Default: "3d"} + fetcher.reset() + + progress, err := m.Refresh(context.Background(), Refresh{Top: 10, Since: 24 * time.Hour}) + if err != nil { + t.Fatalf("Refresh: %v", err) + } + if progress.Completed != 0 || len(fetcher.fetched()) != 0 { + t.Errorf("progress = %+v, fetched %v; want a version within cooldown left alone", progress, fetcher.fetched()) + } +} + +func TestRefreshOnlyTopPackagesRecentlyUsed(t *testing.T) { + m, fetcher := setupRefreshMirror(t, "tarball") + cacheNPM(t, m, "lodash", "4.17.20") + cacheNPM(t, m, "react", "18.3.0") + cacheNPM(t, m, "react", "18.3.0") // a second download: react is used most + m.Versions = stubReleases{ + "npm/lodash": oldReleases("4.17.20", "4.17.21"), + "npm/react": oldReleases("18.3.0", "18.3.1"), + } + if err := m.db.RecordArtifactHit("pkg:npm/react@18.3.0", "react-18.3.0.tgz"); err != nil { + t.Fatal(err) + } + fetcher.reset() + + progress, err := m.Refresh(context.Background(), Refresh{Top: 1, Since: 24 * time.Hour}) + if err != nil { + t.Fatalf("Refresh: %v", err) + } + urls := fetcher.fetched() + if progress.Completed != 1 || len(fetchedMatching(urls, "react-18.3.1.tgz")) != 1 || len(fetchedMatching(urls, "lodash")) != 0 { + t.Errorf("progress = %+v, fetched %v; want only react refreshed", progress, urls) + } +} + +func TestRefreshStopsAtMaxVersions(t *testing.T) { + m, fetcher := setupRefreshMirror(t, "tarball") + cacheNPM(t, m, "lodash", "4.17.20") + cacheNPM(t, m, "react", "18.3.0") + m.Versions = stubReleases{ + "npm/lodash": oldReleases("4.17.20", "4.17.21"), + "npm/react": oldReleases("18.3.0", "18.3.1"), + } + fetcher.reset() + + progress, err := m.Refresh(context.Background(), Refresh{Top: 10, Since: 24 * time.Hour, MaxVersions: 1}) + if err != nil { + t.Fatalf("Refresh: %v", err) + } + if progress.Completed != 1 || len(fetcher.fetched()) != 1 { + t.Errorf("progress = %+v, fetched %v; want one version", progress, fetcher.fetched()) + } +} + +func TestRefreshStopsAtMaxBytes(t *testing.T) { + m, fetcher := setupRefreshMirror(t, "0123456789") + cacheNPM(t, m, "lodash", "4.17.20") + cacheNPM(t, m, "react", "18.3.0") + m.Versions = stubReleases{ + "npm/lodash": oldReleases("4.17.20", "4.17.21"), + "npm/react": oldReleases("18.3.0", "18.3.1"), + } + fetcher.reset() + + // The cap is checked before each download, so the first one goes over it. + progress, err := m.Refresh(context.Background(), Refresh{Top: 10, Since: 24 * time.Hour, MaxBytes: 5}) + if err != nil { + t.Fatalf("Refresh: %v", err) + } + if progress.Completed != 1 || progress.Bytes != 10 { + t.Errorf("progress = %+v, want one version of 10 bytes", progress) + } +} + +func TestRefreshCountsListingFailure(t *testing.T) { + m, fetcher := setupRefreshMirror(t, "tarball") + cacheNPM(t, m, "lodash", "4.17.20") + m.Versions = stubReleases{} + fetcher.reset() + + progress, err := m.Refresh(context.Background(), Refresh{Top: 10, Since: 24 * time.Hour}) + if err != nil { + t.Fatalf("Refresh: %v", err) + } + if progress.Failed != 1 || len(progress.Errors) != 1 || progress.Errors[0].Name != "lodash" { + t.Errorf("progress = %+v, want lodash failed", progress) + } +} + +func TestRefreshMirrorsTheFileVariantsClientsFetched(t *testing.T) { + m, fetcher := setupRefreshMirror(t, "wheel") + ctx := context.Background() + for _, f := range []string{"demo-1.0.0-py3-none-any.whl", "demo-1.0.0-cp312-cp312-manylinux_2_17_x86_64.whl"} { + result, err := m.proxy.GetOrFetchArtifactFromURLWithDigest(ctx, "pypi", "demo", "1.0.0", f, "https://files.example/"+f, "") + if err != nil { + t.Fatal(err) + } + _ = result.Reader.Close() + } + files := func(version string, names ...string) registries.Version { + v := registries.Version{Number: version, PublishedAt: time.Now().Add(-30 * 24 * time.Hour)} + for _, n := range names { + v.Artifacts = append(v.Artifacts, registries.Artifact{Filename: n, URL: "https://files.example/" + n}) + } + return v + } + m.Versions = stubReleases{"pypi/demo": { + files("1.0.0", "demo-1.0.0-py3-none-any.whl", "demo-1.0.0-cp312-cp312-manylinux_2_17_x86_64.whl"), + files("1.1.0", + "demo-1.1.0.tar.gz", + "demo-1.1.0-py3-none-any.whl", + "demo-1.1.0-cp312-cp312-manylinux_2_17_x86_64.whl", + "demo-1.1.0-cp313-cp313-manylinux_2_17_x86_64.whl", + "demo-1.1.0-cp312-cp312-win_amd64.whl"), + }} + fetcher.reset() + + progress, err := m.Refresh(ctx, Refresh{Top: 10, Since: 24 * time.Hour}) + if err != nil { + t.Fatalf("Refresh: %v", err) + } + got := fetcher.fetched() + slices.Sort(got) + want := []string{ + "https://files.example/demo-1.1.0-cp312-cp312-manylinux_2_17_x86_64.whl", + "https://files.example/demo-1.1.0-py3-none-any.whl", + } + if progress.Completed != 1 || !slices.Equal(got, want) { + t.Errorf("progress = %+v, fetched %v; want %v", progress, got, want) + } +} + +func TestFileVariants(t *testing.T) { + tests := []struct { + ecosystem, cacheFilename, want string + }{ + {"pypi", "demo-1.0.0-py3-none-any.whl", "py3-none-any"}, + {"pypi", "demo-1.0.0-1-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", "cp312-cp312-manylinux_x86_64"}, + {"pypi", "demo-1.0.0-cp312-cp312-manylinux_2_17_x86_64.manylinux_2_17_aarch64.whl", "cp312-cp312-manylinux_x86_64 cp312-cp312-manylinux_aarch64"}, + {"pypi", "demo-1.0.0-py2.py3-none-any.whl", "py2-none-any py3-none-any"}, + {"pypi", "demo-1.0.0-cp312-cp312-musllinux_1_2_x86_64.whl", "cp312-cp312-musllinux_x86_64"}, + {"pypi", "demo-1.0.0-cp312-cp312-macosx_10_13_universal2.whl", "cp312-cp312-macosx_universal2"}, + {"pypi", "demo-1.0.0-cp312-cp312-win_amd64.whl", "cp312-cp312-win_amd64"}, + {"pypi", "demo-1.0.0-cp39-abi3-manylinux_2_28_x86_64.whl", "cp-abi3-manylinux_x86_64"}, + {"pypi", "demo-1.0.0.tar.gz", "sdist"}, + {"pypi", "demo-1.0.0.zip", "sdist"}, + {"conda", "linux-64/numpy-1.26.4-py312h8753938_0.conda", "linux-64/py312/conda"}, + {"conda", "noarch/requests-2.32.3-pyhd8ed1ab_0.conda", "noarch/py/conda"}, + {"conda", "osx-arm64/zlib-1.3.1-h8359307_2.tar.bz2", "osx-arm64//tar.bz2"}, + {"conda", "linux-64/python-3.12.16-h5f976f7_0_cpython.conda", "linux-64/_cpython/conda"}, + {"conda", "linux-64/python-3.12.16-h5f976f7_0_debug_cpython.conda", "linux-64/_debug_cpython/conda"}, + } + for _, tt := range tests { + if got := strings.Join(fileEcosystems[tt.ecosystem].cachedVariants(tt.cacheFilename), " "); got != tt.want { + t.Errorf("%s variant of %q = %q, want %q", tt.ecosystem, tt.cacheFilename, got, tt.want) + } + } +} + +func TestRefreshable(t *testing.T) { + for ecosystem, want := range map[string]bool{ + "npm": true, "pypi": true, "conda": true, "composer": true, + // Their registries need the configured upstream URL. + "swift": true, "helm": true, + // Julia files are cached by tree hash, not by version. + "julia": false, + // Images follow mirror.schedules; OS packages their indexes. + "docker": false, "oci": false, "deb": false, "alpine": false, "rpm": false, + "generic": false, + } { + if got := refreshable(ecosystem); got != want { + t.Errorf("refreshable(%s) = %v, want %v", ecosystem, got, want) + } + } +} + +// refreshFetches caches files of an old version of name the way a client +// would, lists newFiles for newVersion and returns what a refresh fetched. +func refreshFetches(t *testing.T, ecosystem, name, oldVersion string, cached []string, newVersion string, newFiles []registries.Artifact) []string { + t.Helper() + m, fetcher := setupRefreshMirror(t, "file") + ctx := context.Background() + old := registries.Version{Number: oldVersion, PublishedAt: time.Now().Add(-60 * 24 * time.Hour)} + for _, f := range cached { + result, err := m.proxy.GetOrFetchArtifactFromURLWithDigest(ctx, ecosystem, name, oldVersion, f, "https://files.example/"+f, "") + if err != nil { + t.Fatal(err) + } + _ = result.Reader.Close() + } + for i := range newFiles { + newFiles[i].URL = "https://files.example/" + newFiles[i].Filename + } + m.Versions = stubReleases{ecosystem + "/" + name: { + old, + {Number: newVersion, PublishedAt: time.Now().Add(-30 * 24 * time.Hour), Artifacts: newFiles}, + }} + fetcher.reset() + + progress, err := m.Refresh(ctx, Refresh{Top: 10, Since: 24 * time.Hour}) + if err != nil { + t.Fatalf("Refresh: %v", err) + } + if progress.Failed != 0 { + t.Errorf("progress = %+v, want no failures", progress) + } + got := fetcher.fetched() + slices.Sort(got) + return got +} + +func wheels(names ...string) []registries.Artifact { + files := make([]registries.Artifact, 0, len(names)) + for _, n := range names { + files = append(files, registries.Artifact{Filename: n}) + } + return files +} + +// A new wheel built for a newer glibc or macOS still replaces the cached +// one: platform tags match on OS and architecture. +func TestRefreshMatchesWheelsAcrossPlatformMinimums(t *testing.T) { + got := refreshFetches(t, "pypi", "numpy", "2.2.6", + []string{"numpy-2.2.6-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", "numpy-2.2.6-cp312-cp312-macosx_10_13_x86_64.whl"}, + "2.3.0", wheels( + "numpy-2.3.0-cp312-cp312-manylinux_2_28_x86_64.whl", + "numpy-2.3.0-cp312-cp312-manylinux_2_28_aarch64.whl", + "numpy-2.3.0-cp312-cp312-musllinux_1_2_x86_64.whl", + "numpy-2.3.0-cp313-cp313-manylinux_2_28_x86_64.whl", + "numpy-2.3.0-cp312-cp312-macosx_11_0_x86_64.whl", + "numpy-2.3.0-cp312-cp312-macosx_11_0_arm64.whl", + "numpy-2.3.0-cp312-cp312-win_amd64.whl", + )) + want := []string{ + "https://files.example/numpy-2.3.0-cp312-cp312-macosx_11_0_x86_64.whl", + "https://files.example/numpy-2.3.0-cp312-cp312-manylinux_2_28_x86_64.whl", + } + if !slices.Equal(got, want) { + t.Errorf("fetched %v, want %v", got, want) + } +} + +// conda-forge's python builds carry the hash before a suffix; the suffix +// stays part of the kind. +func TestRefreshMatchesCondaBuildsWithHashInside(t *testing.T) { + conda := func(subdir, filename, build string) registries.Artifact { + return registries.Artifact{Filename: filename, Metadata: map[string]any{"subdir": subdir, "build": build}} + } + got := refreshFetches(t, "conda", "conda-forge/python", "3.12.15", + []string{"linux-64/python-3.12.15-h5f976f7_0_cpython.conda"}, + "3.12.16", []registries.Artifact{ + conda("linux-64", "python-3.12.16-hab00c5b_1_cpython.conda", "hab00c5b_1_cpython"), + conda("linux-64", "python-3.12.16-hd12c33a_1_debug_cpython.conda", "hd12c33a_1_debug_cpython"), + conda("osx-arm64", "python-3.12.16-h99e199e_1_cpython.conda", "h99e199e_1_cpython"), + }) + want := []string{"https://files.example/python-3.12.16-hab00c5b_1_cpython.conda"} + if !slices.Equal(got, want) { + t.Errorf("fetched %v, want %v", got, want) + } +} + +// The dot-separated tags of a wheel are alternatives: a wheel matches a +// cached one when any of its tags does. +func TestRefreshMatchesWheelsOnAnyAlternativeTag(t *testing.T) { + got := refreshFetches(t, "pypi", "demo", "1.0.0", + []string{"demo-1.0.0-cp312-cp312-manylinux_2_17_x86_64.whl", "demo-1.0.0-py2.py3-none-macosx_11_0_arm64.macosx_11_0_x86_64.whl"}, + "1.1.0", wheels( + "demo-1.1.0-cp312-cp312-manylinux_2_17_x86_64.linux_x86_64.whl", + "demo-1.1.0-py3-none-macosx_11_0_x86_64.whl", + "demo-1.1.0-cp312-cp312-win_amd64.whl", + )) + want := []string{ + "https://files.example/demo-1.1.0-cp312-cp312-manylinux_2_17_x86_64.linux_x86_64.whl", + "https://files.example/demo-1.1.0-py3-none-macosx_11_0_x86_64.whl", + } + if !slices.Equal(got, want) { + t.Errorf("fetched %v, want %v", got, want) + } +} + +// In an abi3 wheel the python tag is a minimum: cryptography 44.0.0 ships +// cp37-abi3 and cp39-abi3 wheels, 46.0.0 cp38-abi3 and cp311-abi3 ones. A +// refresh stays on the cached major line, so the newer tags are on 44.1.0 +// here. +func TestRefreshMatchesAbi3WheelsAcrossPythonMinimums(t *testing.T) { + got := refreshFetches(t, "pypi", "cryptography", "44.0.0", + []string{"cryptography-44.0.0-cp39-abi3-manylinux_2_28_x86_64.whl"}, + "44.1.0", wheels( + "cryptography-44.1.0-cp38-abi3-manylinux_2_28_x86_64.whl", + "cryptography-44.1.0-cp311-abi3-manylinux_2_28_x86_64.whl", + "cryptography-44.1.0-cp311-abi3-manylinux_2_28_aarch64.whl", + "cryptography-44.1.0-cp311-abi3-macosx_10_9_universal2.whl", + "cryptography-44.1.0-cp311-abi3-win_amd64.whl", + "cryptography-44.1.0-cp314-cp314t-manylinux_2_28_x86_64.whl", + )) + want := []string{ + "https://files.example/cryptography-44.1.0-cp311-abi3-manylinux_2_28_x86_64.whl", + "https://files.example/cryptography-44.1.0-cp38-abi3-manylinux_2_28_x86_64.whl", + } + if !slices.Equal(got, want) { + t.Errorf("fetched %v, want %v", got, want) + } +} diff --git a/internal/mirror/refresh_versions.go b/internal/mirror/refresh_versions.go new file mode 100644 index 0000000..22fe7c1 --- /dev/null +++ b/internal/mirror/refresh_versions.go @@ -0,0 +1,76 @@ +package mirror + +import ( + "strconv" + + "github.com/git-pkgs/purl" + "github.com/git-pkgs/registries" + "github.com/git-pkgs/vers" +) + +// newestPerCachedLine returns, for each major line a cached version is on, +// the newest release of that line that allowed accepts, when it is newer +// than every cached version of the line. A line is the major version, or +// 0.minor below 1.0, as caret ranges read them, and calendar versions are +// one line. Prereleases and yanked, +// retracted or deprecated releases are skipped. +func newestPerCachedLine(ecosystem string, cached []string, releases []registries.Version, allowed func(registries.Version) bool) []string { + scheme := purl.EcosystemToPURLType(ecosystem) + newestCached := map[string]string{} + var lines []string + for _, v := range cached { + line, ok := versionLine(v) + if !ok { + continue + } + current, seen := newestCached[line] + if !seen { + lines = append(lines, line) + } + if !seen || vers.CompareWithScheme(v, current, scheme) > 0 { + newestCached[line] = v + } + } + + newest := map[string]string{} + for _, r := range releases { + line, ok := versionLine(r.Number) + if !ok || r.Status != registries.StatusNone || vers.IsPrereleaseWithScheme(r.Number, scheme) { + continue + } + if _, cachedLine := newestCached[line]; !cachedLine || !allowed(r) { + continue + } + if current, seen := newest[line]; !seen || vers.CompareWithScheme(r.Number, current, scheme) > 0 { + newest[line] = r.Number + } + } + + var out []string + for _, line := range lines { + if v, ok := newest[line]; ok && vers.CompareWithScheme(v, newestCached[line], scheme) > 0 { + out = append(out, v) + } + } + return out +} + +// firstCalendarYear is the smallest first number read as a year. +const firstCalendarYear = 1000 + +// versionLine returns the major line of a version. Calendar versions, whose +// first number is a year, are all one line, so a new year's release follows +// the last one's. +func versionLine(v string) (string, bool) { + info, err := vers.ParseVersion(v) + if err != nil { + return "", false + } + if info.Major >= firstCalendarYear { + return "calendar", true + } + if info.Major == 0 { + return "0." + strconv.Itoa(info.Minor), true + } + return strconv.Itoa(info.Major), true +} diff --git a/internal/mirror/refresh_versions_test.go b/internal/mirror/refresh_versions_test.go new file mode 100644 index 0000000..bc88947 --- /dev/null +++ b/internal/mirror/refresh_versions_test.go @@ -0,0 +1,92 @@ +package mirror + +import ( + "reflect" + "testing" + "time" + + "github.com/git-pkgs/registries" +) + +func releases(numbers ...string) []registries.Version { + out := make([]registries.Version, len(numbers)) + for i, n := range numbers { + out[i] = registries.Version{Number: n, PublishedAt: time.Date(2026, 1, 1+i, 0, 0, 0, 0, time.UTC)} + } + return out +} + +func TestNewestPerCachedLine(t *testing.T) { + allowAll := func(registries.Version) bool { return true } + yanked := releases("4.17.20", "4.17.21", "4.17.22") + yanked[2].Status = registries.StatusYanked + + tests := []struct { + name string + cached []string + releases []registries.Version + allowed func(registries.Version) bool + want []string + }{ + {name: "newer patch on the cached line", cached: []string{"4.17.20"}, + releases: releases("4.17.20", "4.17.21", "5.0.0"), want: []string{"4.17.21"}}, + {name: "newest already cached", cached: []string{"4.17.21"}, + releases: releases("4.17.20", "4.17.21", "5.0.0")}, + {name: "one per cached major line", cached: []string{"1.2.0", "2.0.0"}, + releases: releases("1.2.0", "1.3.0", "2.0.0", "2.1.0", "3.0.0"), want: []string{"1.3.0", "2.1.0"}}, + {name: "zero major lines are minor lines", cached: []string{"0.3.1"}, + releases: releases("0.3.1", "0.3.2", "0.4.0"), want: []string{"0.3.2"}}, + {name: "prereleases skipped", cached: []string{"2.0.0"}, + releases: releases("2.0.0", "2.1.0-beta.1")}, + {name: "yanked skipped", cached: []string{"4.17.20"}, + releases: yanked, want: []string{"4.17.21"}}, + {name: "newest withheld, older newer one taken", cached: []string{"4.17.20"}, + releases: releases("4.17.20", "4.17.21", "4.17.22"), + allowed: func(v registries.Version) bool { return v.Number != "4.17.22" }, + want: []string{"4.17.21"}}, + {name: "nothing allowed newer than cached", cached: []string{"4.17.20"}, + releases: releases("4.17.20", "4.17.21"), + allowed: func(v registries.Version) bool { return v.Number == "4.17.20" }}, + {name: "cached newer than every listed one", cached: []string{"4.17.25"}, + releases: releases("4.17.20", "4.17.21")}, + {name: "only the newest cached of a line counts", cached: []string{"4.17.19", "4.17.21"}, + releases: releases("4.17.19", "4.17.20", "4.17.21")}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + allowed := tt.allowed + if allowed == nil { + allowed = allowAll + } + got := newestPerCachedLine("npm", tt.cached, tt.releases, allowed) + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("newestPerCachedLine = %v, want %v", got, tt.want) + } + }) + } +} + +func TestNewestPerCachedLineUsesEcosystemOrdering(t *testing.T) { + // Maven orders 1.0.10 after 1.0.9, and a gem's 1.0.0.rc1 is a prerelease. + got := newestPerCachedLine("maven", []string{"1.0.9"}, releases("1.0.9", "1.0.10"), func(registries.Version) bool { return true }) + if !reflect.DeepEqual(got, []string{"1.0.10"}) { + t.Errorf("maven: got %v, want [1.0.10]", got) + } + got = newestPerCachedLine("gem", []string{"1.0.0"}, releases("1.0.0", "1.0.1.rc1"), func(registries.Version) bool { return true }) + if got != nil { + t.Errorf("gem: got %v, want nothing", got) + } +} + +func TestNewestPerCachedLineCalendarVersions(t *testing.T) { + allowAll := func(registries.Version) bool { return true } + // certifi and tzdata number releases by year: 2025.1.31 follows 2024.12.14. + got := newestPerCachedLine("pypi", []string{"2024.8.30"}, releases("2024.8.30", "2024.12.14", "2025.1.31"), allowAll) + if !reflect.DeepEqual(got, []string{"2025.1.31"}) { + t.Errorf("certifi: got %v, want [2025.1.31]", got) + } + got = newestPerCachedLine("pypi", []string{"2024.2"}, releases("2024.2", "2025.1"), allowAll) + if !reflect.DeepEqual(got, []string{"2025.1"}) { + t.Errorf("tzdata: got %v, want [2025.1]", got) + } +} diff --git a/internal/mirror/sbom_version_test.go b/internal/mirror/sbom_version_test.go new file mode 100644 index 0000000..43dde04 --- /dev/null +++ b/internal/mirror/sbom_version_test.go @@ -0,0 +1,73 @@ +package mirror + +import ( + "context" + "net/http" + "reflect" + "testing" + + "github.com/git-pkgs/proxy/internal/handler" + "github.com/git-pkgs/registries" +) + +func TestSBOMSourceUsesComponentVersion(t *testing.T) { + for name, data := range map[string]string{ + "CycloneDX JSON": `{"components":[{"name":"app","version":"1.0","purl":"pkg:docker/ghcr.io/team/app"}]}`, + "CycloneDX XML": `app1.0pkg:docker/ghcr.io/team/app`, + "SPDX JSON": `{"spdxVersion":"SPDX-2.3","packages":[{"name":"app","versionInfo":"1.0","externalRefs":[{"referenceType":"purl","referenceLocator":"pkg:docker/ghcr.io/team/app"}]}]}`, + "SPDX tag-value": "DataLicense: CC0-1.0\nSPDXVersion: SPDX-2.3\nSPDXID: SPDXRef-DOCUMENT\nDocumentName: example\nDocumentNamespace: https://example.com/sbom\nPackageName: app\nSPDXID: SPDXRef-app\nPackageVersion: 1.0\nExternalRef: PACKAGE-MANAGER purl pkg:docker/ghcr.io/team/app\n", + } { + t.Run(name, func(t *testing.T) { + source := &SBOMSource{Data: []byte(data)} + var got []PackageVersion + if err := source.Enumerate(context.Background(), func(pv PackageVersion) error { got = append(got, pv); return nil }); err != nil { + t.Fatal(err) + } + if len(got) != 1 || got[0].Version != "1.0" { + t.Fatalf("Enumerate = %+v, want one image at 1.0", got) + } + }) + } +} + +func TestSBOMSourceVersionPrecedence(t *testing.T) { + for _, test := range []struct{ name, componentVersion, imagePURL, wantVersion string }{ + {"PURL version wins", "2.0", "pkg:docker/team/app@1.0", "1.0"}, + {"digest from component", "sha256:abc123", "pkg:docker/team/app", "sha256:abc123"}, + {"unknown version", "", "pkg:docker/team/app", ""}, + {"package version", "1.0", "pkg:npm/example", "1.0"}, + } { + t.Run(test.name, func(t *testing.T) { + data := marshalJSON(t, map[string]any{"components": []map[string]any{{"name": "app", "version": test.componentVersion, "purl": test.imagePURL}}}) + var got []PackageVersion + source := &SBOMSource{Data: data, Versions: RegistryVersions{Client: registries.NewClient(registries.WithHTTPClient(&http.Client{Transport: rejectingMirrorTransport{}}))}} + if err := source.Enumerate(context.Background(), func(pv PackageVersion) error { got = append(got, pv); return nil }); err != nil { + t.Fatal(err) + } + if len(got) != 1 || got[0].Version != test.wantVersion { + t.Fatalf("Enumerate = %+v, want version %q", got, test.wantVersion) + } + }) + } +} + +func TestMirrorRunSBOMDockerReference(t *testing.T) { + m := setupTestMirror(t, 1) + images := &fakeImages{result: handler.ImageResult{Fetched: 1}} + m.Images = images + source := &SBOMSource{ + Data: []byte(`{"components":[{"name":"app","version":"1.0","purl":"pkg:docker/registry.example:5000/team/app?arch=arm64"}]}`), + Platforms: []string{"linux/arm64"}, + } + progress, err := m.Run(context.Background(), source) + if err != nil { + t.Fatal(err) + } + if progress.Completed != 1 || progress.Failed != 0 { + t.Fatalf("progress = %+v", progress) + } + want := []handler.ImageRef{{Registry: "registry.example:5000", Name: "team/app", References: []string{"1.0"}}} + if !reflect.DeepEqual(images.refs, want) { + t.Errorf("image refs = %+v, want %+v", images.refs, want) + } +} diff --git a/internal/mirror/schedule.go b/internal/mirror/schedule.go new file mode 100644 index 0000000..244fd89 --- /dev/null +++ b/internal/mirror/schedule.go @@ -0,0 +1,162 @@ +package mirror + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "fmt" + "log/slog" + "math/rand/v2" + "sync" + "time" +) + +const ( + maxFirstScheduleDelay = 10 * time.Minute + // scheduleJitter spreads later runs by ±interval/scheduleJitter. + scheduleJitter = 10 +) + +// Schedule mirrors a set of image PURLs every Interval, or refreshes the +// most used packages when Refresh is set. +type Schedule struct { + PURLs []string + Platforms []string + Refresh *Refresh + Interval time.Duration +} + +// Scheduler runs schedules in the background until its context ends. +type Scheduler struct { + mirror *Mirror + schedules []Schedule + logger *slog.Logger + wg sync.WaitGroup + // Claim, when set, reports whether this instance should run a schedule + // that no instance sharing the database started within minGap. Each + // instance keeps its own timer, so without it every instance would run + // every schedule. + Claim func(key string, minGap time.Duration) (bool, error) + // Release, when set, drops the claim of a run that was interrupted, so + // the next attempt runs it rather than waiting an interval. + Release func(key string) error + // randN returns a value in [0, n); tests replace it. + randN func(n int64) int64 +} + +// NewScheduler creates a scheduler that runs the schedules through m. +func NewScheduler(m *Mirror, schedules []Schedule, logger *slog.Logger) *Scheduler { + return &Scheduler{ + mirror: m, + schedules: schedules, + logger: logger, + randN: rand.Int64N, //nolint:gosec // jitter, not security + } +} + +// Start starts one goroutine per schedule. +func (s *Scheduler) Start(ctx context.Context) { + for i, schedule := range s.schedules { + if schedule.Interval <= 0 { + s.logger.Error("mirror schedule has no interval, skipped", "schedule", i) + continue + } + s.wg.Add(1) + go s.loop(ctx, i, schedule) + } +} + +// Wait blocks until every schedule has stopped after its context ended. +func (s *Scheduler) Wait() { + s.wg.Wait() +} + +func (s *Scheduler) loop(ctx context.Context, index int, schedule Schedule) { + defer s.wg.Done() + timer := time.NewTimer(scheduleDelay(schedule.Interval, true, s.randN)) + defer timer.Stop() + for { + select { + case <-ctx.Done(): + return + case <-timer.C: + } + s.run(ctx, index, schedule) + // The next run is timed from the end of this one, so runs never overlap. + timer.Reset(scheduleDelay(schedule.Interval, false, s.randN)) + } +} + +func (s *Scheduler) run(ctx context.Context, index int, schedule Schedule) { + key := scheduleKey(schedule) + if s.Claim != nil { + // Later runs come at least interval - 2*spread apart, so a run + // started more recently than that was another instance's. + minGap := schedule.Interval - 2*(schedule.Interval/scheduleJitter) //nolint:mnd // two spreads of margin + claimed, err := s.Claim(key, minGap) + if err != nil { + s.logger.Warn("mirror schedule: failed to claim run, skipping it", "schedule", index, "error", err) + return + } + if !claimed { + s.logger.Debug("mirror schedule: another instance ran it, skipping", "schedule", index) + return + } + } + started := time.Now() + var progress *Progress + var err error + if schedule.Refresh != nil { + progress, err = s.mirror.Refresh(ctx, *schedule.Refresh) + } else { + progress, err = s.mirror.Run(ctx, &PURLSource{PURLs: schedule.PURLs, Versions: s.mirror.Versions, Platforms: schedule.Platforms}) + } + if ctx.Err() != nil { + if s.Claim != nil && s.Release != nil { + if err := s.Release(key); err != nil { + s.logger.Warn("mirror schedule: failed to release interrupted run", "schedule", index, "error", err) + } + } + return + } + if err != nil { + s.logger.Error("mirror schedule failed", "schedule", index, "error", err) + return + } + level := slog.LevelInfo + if progress.Failed > 0 { + level = slog.LevelWarn + } + s.logger.Log(ctx, level, "mirror schedule run", + "schedule", index, "mirrored", progress.Completed, "unchanged", progress.Skipped, + "failed", progress.Failed, "bytes", progress.Bytes, "duration", time.Since(started).Round(time.Millisecond)) +} + +// scheduleDelay spreads runs so instances and schedules started together +// don't hit the registry at once. The first run comes within ten minutes, so +// a restart doesn't push a refresh back by a whole interval. +func scheduleDelay(interval time.Duration, first bool, randN func(int64) int64) time.Duration { + if first { + return time.Duration(randN(int64(min(interval, maxFirstScheduleDelay)))) + } + spread := interval / scheduleJitter + return interval - spread + time.Duration(randN(int64(2*spread)+1)) //nolint:mnd // spread on both sides +} + +// scheduleKey names a schedule by what it mirrors and how often, so +// instances with the same configuration agree on it and a changed schedule +// does not inherit the old one's last run. +func scheduleKey(schedule Schedule) string { + h := sha256.New() + if r := schedule.Refresh; r != nil { + _, _ = fmt.Fprintf(h, "refresh top %d since %s max_versions %d max_bytes %d\n", r.Top, r.Since, r.MaxVersions, r.MaxBytes) + } + for _, purl := range schedule.PURLs { + _, _ = fmt.Fprintf(h, "purl %s\n", purl) + } + for _, platform := range schedule.Platforms { + _, _ = fmt.Fprintf(h, "platform %s\n", platform) + } + _, _ = fmt.Fprintf(h, "interval %s\n", schedule.Interval) + return "mirror-schedule:" + hex.EncodeToString(h.Sum(nil))[:32] +} diff --git a/internal/mirror/schedule_test.go b/internal/mirror/schedule_test.go new file mode 100644 index 0000000..0a6edc3 --- /dev/null +++ b/internal/mirror/schedule_test.go @@ -0,0 +1,314 @@ +package mirror + +import ( + "context" + "errors" + "io" + "log/slog" + "math/rand/v2" + "reflect" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/git-pkgs/proxy/internal/handler" +) + +func TestScheduleDelay(t *testing.T) { + lowest := func(int64) int64 { return 0 } + highest := func(n int64) int64 { return n - 1 } + tests := []struct { + name string + interval time.Duration + first bool + randN func(int64) int64 + want time.Duration + }{ + {name: "first run lowest", interval: 6 * time.Hour, first: true, randN: lowest, want: 0}, + {name: "first run capped at ten minutes", interval: 6 * time.Hour, first: true, randN: highest, want: 10*time.Minute - 1}, + {name: "first run within a short interval", interval: 2 * time.Minute, first: true, randN: highest, want: 2*time.Minute - 1}, + {name: "later run lowest", interval: 6 * time.Hour, randN: lowest, want: 6*time.Hour - 36*time.Minute}, + {name: "later run highest", interval: 6 * time.Hour, randN: highest, want: 6*time.Hour + 36*time.Minute}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := scheduleDelay(tt.interval, tt.first, tt.randN); got != tt.want { + t.Errorf("scheduleDelay() = %v, want %v", got, tt.want) + } + }) + } +} + +// scheduleImages records MirrorImage calls and can block or fail them. +type scheduleImages struct { + mu sync.Mutex + refs []handler.ImageRef + platforms [][]handler.Platform + calls atomic.Int32 + running atomic.Int32 + overlap atomic.Bool + block chan struct{} + err error +} + +func (f *scheduleImages) MirrorImage(ctx context.Context, ref handler.ImageRef, platforms []handler.Platform) (handler.ImageResult, error) { + if f.running.Add(1) > 1 { + f.overlap.Store(true) + } + defer f.running.Add(-1) + f.mu.Lock() + f.refs = append(f.refs, ref) + f.platforms = append(f.platforms, platforms) + f.mu.Unlock() + f.calls.Add(1) + if f.block != nil { + select { + case <-f.block: + case <-ctx.Done(): + return handler.ImageResult{}, ctx.Err() + } + } + return handler.ImageResult{}, f.err +} + +func newTestScheduler(images ImageMirrorer, schedules ...Schedule) *Scheduler { + logger := slog.New(slog.NewTextHandler(io.Discard, nil)) + m := New(nil, nil, nil, logger, 1) + m.Images = images + s := NewScheduler(m, schedules, logger) + s.randN = func(int64) int64 { return 0 } + return s +} + +func waitFor(t *testing.T, what string, cond func() bool) { + t.Helper() + deadline := time.Now().Add(5 * time.Second) + for !cond() { + if time.Now().After(deadline) { + t.Fatalf("timed out waiting for %s", what) + } + time.Sleep(time.Millisecond) + } +} + +func TestSchedulerRepeatsRunsAndStops(t *testing.T) { + images := &scheduleImages{err: errors.New("upstream down")} + s := newTestScheduler(images, Schedule{ + PURLs: []string{"pkg:docker/library/alpine@3.20"}, + Platforms: []string{"linux/arm64"}, + Interval: time.Millisecond, + }) + ctx, cancel := context.WithCancel(context.Background()) + s.Start(ctx) + // A failing run must not end the schedule. + waitFor(t, "three runs", func() bool { return images.calls.Load() >= 3 }) + cancel() + s.Wait() + + images.mu.Lock() + defer images.mu.Unlock() + wantRef := handler.ImageRef{Name: "library/alpine", References: []string{"3.20"}} + if !reflect.DeepEqual(images.refs[0], wantRef) { + t.Errorf("ref = %+v, want %+v", images.refs[0], wantRef) + } + wantPlatforms := []handler.Platform{{OS: "linux", Architecture: "arm64"}} + if !reflect.DeepEqual(images.platforms[0], wantPlatforms) { + t.Errorf("platforms = %+v, want %+v", images.platforms[0], wantPlatforms) + } +} + +func TestSchedulerRunsDoNotOverlap(t *testing.T) { + images := &scheduleImages{block: make(chan struct{})} + s := newTestScheduler(images, Schedule{PURLs: []string{"pkg:docker/alpine@3"}, Interval: time.Millisecond}) + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + s.Start(ctx) + + waitFor(t, "first run", func() bool { return images.calls.Load() == 1 }) + // Many intervals pass while the run blocks; none may start a second run. + time.Sleep(50 * time.Millisecond) + if got := images.calls.Load(); got != 1 { + t.Fatalf("calls while the first run blocks = %d, want 1", got) + } + images.block <- struct{}{} + waitFor(t, "second run", func() bool { return images.calls.Load() == 2 }) + cancel() + s.Wait() + if images.overlap.Load() { + t.Error("two runs of one schedule overlapped") + } +} + +func TestSchedulerWaitReturnsAfterCancelDuringRun(t *testing.T) { + images := &scheduleImages{block: make(chan struct{})} + s := newTestScheduler(images, + Schedule{PURLs: []string{"pkg:docker/alpine@3"}, Interval: time.Hour}, + Schedule{PURLs: []string{"pkg:docker/nginx@stable"}, Interval: time.Hour}) + ctx, cancel := context.WithCancel(context.Background()) + s.Start(ctx) + waitFor(t, "both schedules running", func() bool { return images.calls.Load() == 2 }) + + cancel() + done := make(chan struct{}) + go func() { + s.Wait() + close(done) + }() + select { + case <-done: + case <-time.After(5 * time.Second): + t.Fatal("Wait did not return after cancel") + } +} + +func TestSchedulerSkipsScheduleWithoutInterval(t *testing.T) { + images := &scheduleImages{} + s := newTestScheduler(images, Schedule{PURLs: []string{"pkg:docker/alpine@3"}}) + // The real random source panics on a zero interval. + s.randN = rand.Int64N + ctx, cancel := context.WithCancel(context.Background()) + s.Start(ctx) + cancel() + s.Wait() + if got := images.calls.Load(); got != 0 { + t.Errorf("calls = %d, want 0", got) + } +} + +func TestSchedulerSkipsRunClaimedElsewhere(t *testing.T) { + images := &scheduleImages{} + schedule := Schedule{PURLs: []string{"pkg:docker/alpine@3"}, Interval: time.Hour} + s := newTestScheduler(images, schedule) + var mu sync.Mutex + var keys []string + var gaps []time.Duration + claim := true + s.Claim = func(key string, minGap time.Duration) (bool, error) { + mu.Lock() + defer mu.Unlock() + keys = append(keys, key) + gaps = append(gaps, minGap) + return claim, nil + } + + s.run(context.Background(), 0, schedule) + if got := images.calls.Load(); got != 1 { + t.Fatalf("calls after a claimed run = %d, want 1", got) + } + claim = false + s.run(context.Background(), 0, schedule) + if got := images.calls.Load(); got != 1 { + t.Fatalf("calls after a run claimed elsewhere = %d, want 1", got) + } + s.Claim = func(string, time.Duration) (bool, error) { return false, errors.New("database down") } + s.run(context.Background(), 0, schedule) + if got := images.calls.Load(); got != 1 { + t.Fatalf("calls after a failed claim = %d, want 1", got) + } + + if keys[0] != keys[1] { + t.Errorf("claim keys differ between runs: %q, %q", keys[0], keys[1]) + } + // Runs come at least 0.9 intervals apart; the gap stays below that. + if want := 48 * time.Minute; gaps[0] != want { + t.Errorf("minGap = %s, want %s", gaps[0], want) + } +} + +// TestSchedulerReleasesInterruptedRun checks that a run cut off by shutdown +// does not count as done: the next attempt, on a restarted instance or +// another one, runs the schedule again. +func TestSchedulerReleasesInterruptedRun(t *testing.T) { + images := &scheduleImages{block: make(chan struct{})} + schedule := Schedule{PURLs: []string{"pkg:docker/alpine@3"}, Interval: time.Hour} + s := newTestScheduler(images, schedule) + // The claims of a shared database: a claimed key is not claimed again. + var mu sync.Mutex + claims := map[string]bool{} + s.Claim = func(key string, _ time.Duration) (bool, error) { + mu.Lock() + defer mu.Unlock() + if claims[key] { + return false, nil + } + claims[key] = true + return true, nil + } + s.Release = func(key string) error { + mu.Lock() + defer mu.Unlock() + delete(claims, key) + return nil + } + + ctx, cancel := context.WithCancel(context.Background()) + done := make(chan struct{}) + go func() { + s.run(ctx, 0, schedule) + close(done) + }() + waitFor(t, "the run to start", func() bool { return images.calls.Load() == 1 }) + cancel() + <-done + + close(images.block) + s.run(context.Background(), 0, schedule) + if got := images.calls.Load(); got != 2 { + t.Fatalf("calls = %d, want 2: the interrupted run blocked the next one", got) + } + // A finished run keeps its claim. + s.run(context.Background(), 0, schedule) + if got := images.calls.Load(); got != 2 { + t.Fatalf("calls = %d, want 2 after a finished run", got) + } +} + +func TestScheduleKey(t *testing.T) { + base := Schedule{PURLs: []string{"pkg:docker/alpine@3"}, Platforms: []string{"linux/amd64"}, Interval: time.Hour} + if scheduleKey(base) != scheduleKey(Schedule{PURLs: []string{"pkg:docker/alpine@3"}, Platforms: []string{"linux/amd64"}, Interval: time.Hour}) { + t.Error("same schedule gave different keys") + } + for name, other := range map[string]Schedule{ + "purls": {PURLs: []string{"pkg:docker/alpine@4"}, Platforms: base.Platforms, Interval: base.Interval}, + "platforms": {PURLs: base.PURLs, Platforms: []string{"linux/arm64"}, Interval: base.Interval}, + "interval": {PURLs: base.PURLs, Platforms: base.Platforms, Interval: 2 * time.Hour}, + } { + if scheduleKey(other) == scheduleKey(base) { + t.Errorf("changing %s kept the key", name) + } + } +} + +func TestSchedulerRunsRefresh(t *testing.T) { + m, fetcher := setupRefreshMirror(t, "tarball") + cacheNPM(t, m, "lodash", "4.17.20") + m.Versions = stubReleases{"npm/lodash": oldReleases("4.17.20", "4.17.21")} + fetcher.reset() + + schedule := Schedule{Refresh: &Refresh{Top: 10, Since: time.Hour}, Interval: time.Hour} + s := NewScheduler(m, []Schedule{schedule}, m.logger) + s.run(context.Background(), 0, schedule) + + if urls := fetcher.fetched(); len(urls) != 1 || len(fetchedMatching(urls, "lodash-4.17.21.tgz")) != 1 { + t.Errorf("fetched %v, want lodash 4.17.21", urls) + } +} + +func TestScheduleKeyRefresh(t *testing.T) { + base := Schedule{Refresh: &Refresh{Top: 50, Since: time.Hour}, Interval: time.Hour} + same := Schedule{Refresh: &Refresh{Top: 50, Since: time.Hour}, Interval: time.Hour} + if scheduleKey(base) != scheduleKey(same) { + t.Error("same refresh gave different keys") + } + for name, other := range map[string]Schedule{ + "no refresh": {Interval: time.Hour}, + "top": {Refresh: &Refresh{Top: 10, Since: time.Hour}, Interval: time.Hour}, + "since": {Refresh: &Refresh{Top: 50, Since: 2 * time.Hour}, Interval: time.Hour}, + "interval": {Refresh: &Refresh{Top: 50, Since: time.Hour}, Interval: 2 * time.Hour}, + } { + if scheduleKey(other) == scheduleKey(base) { + t.Errorf("changing %s kept the key", name) + } + } +} diff --git a/internal/mirror/source.go b/internal/mirror/source.go index 6d3d096..bbfddf0 100644 --- a/internal/mirror/source.go +++ b/internal/mirror/source.go @@ -1,18 +1,14 @@ package mirror import ( - "bytes" "context" - "encoding/json" "fmt" + "strings" - cdx "github.com/CycloneDX/cyclonedx-go" + "github.com/git-pkgs/proxy/internal/packageurl" "github.com/git-pkgs/purl" "github.com/git-pkgs/registries" - _ "github.com/git-pkgs/registries/all" - spdxjson "github.com/spdx/tools-golang/json" - "github.com/spdx/tools-golang/spdx" - spdxtv "github.com/spdx/tools-golang/tagvalue" + "github.com/git-pkgs/sbom" ) // PackageVersion identifies a specific package version to mirror. @@ -20,11 +16,23 @@ type PackageVersion struct { Ecosystem string Name string Version string + // Namespace is the PURL namespace of apk packages, which Name leaves + // out. It picks the upstream.apk repository. + Namespace string // Qualifiers are the PURL qualifiers. Images use repository_url, tag and - // arch. + // arch; PyPI uses file_name, and conda subdir, build and type, to select + // which files of the version are mirrored. Julia uses uuid to identify + // the package. Qualifiers map[string]string // Platforms limit which platforms of an image index are mirrored. Platforms []string + // variants, when set, limit the files of a version that are mirrored to + // those of these variants (see fileEcosystem.variants). + variants map[string]bool + // fileURL, when set, is the one file to mirror, cached as cacheFilename + // and checked against digest when there is one. A refresh finds it in + // a repository index. + fileURL, cacheFilename, digest string } func (pv PackageVersion) String() string { @@ -37,18 +45,23 @@ type Source interface { } // PURLSource yields packages from PURL strings. -// Versioned PURLs produce a single item. Unversioned PURLs look up all versions from the registry. +// Versioned PURLs produce a single item. Unversioned PURLs produce one item +// per version Versions lists, or only the newest with Latest. type PURLSource struct { - PURLs []string - RegClient *registries.Client + PURLs []string + // Versions lists the versions of unversioned PURLs. Nil lists them from + // the public registries. + Versions VersionLister + // Latest mirrors only the newest version of unversioned PURLs. + Latest bool // Platforms limit which platforms of container images are mirrored. Platforms []string } func (s *PURLSource) Enumerate(ctx context.Context, fn func(PackageVersion) error) error { - client := s.RegClient - if client == nil { - client = registries.DefaultClient() + versions := s.Versions + if versions == nil { + versions = RegistryVersions{} } for _, purlStr := range s.PURLs { @@ -57,18 +70,21 @@ func (s *PURLSource) Enumerate(ctx context.Context, fn func(PackageVersion) erro return fmt.Errorf("parsing PURL %q: %w", purlStr, err) } - ecosystem := purl.PURLTypeToEcosystem(p.Type) - name := p.Name - if p.Namespace != "" { - name = p.Namespace + "/" + p.Name + ecosystem, name, qualifiers := mirrorTarget(p) + var namespace string + if ecosystem == "alpine" { + namespace = p.Namespace } - if p.Version != "" || isImageEcosystem(ecosystem) { - // Images are never expanded to all tags; an unversioned image - // fails when it is mirrored. - pv := PackageVersion{Ecosystem: ecosystem, Name: name, Version: p.Version} + // Images are never expanded to all tags, and conda packages without + // a channel aren't listed; both fail when they are mirrored. A Git + // repository without a commit is mirrored as a whole. + if p.Version != "" || isImageEcosystem(ecosystem) || ecosystem == "git" || (ecosystem == "conda" && !strings.Contains(name, "/")) { + pv := PackageVersion{Ecosystem: ecosystem, Name: name, Version: p.Version, Namespace: namespace, Qualifiers: qualifiers} if isImageEcosystem(ecosystem) { pv.Qualifiers = p.Qualifiers.Map() + } + if takesPlatforms(ecosystem) { pv.Platforms = s.Platforms } if err := fn(pv); err != nil { @@ -77,13 +93,17 @@ func (s *PURLSource) Enumerate(ctx context.Context, fn func(PackageVersion) erro continue } - // Unversioned: enumerate all versions - versions, err := s.fetchVersions(ctx, client, ecosystem, name) + // Unversioned: enumerate all versions, or the newest + listed, err := s.listVersions(ctx, versions, ecosystem, name) if err != nil { return fmt.Errorf("fetching versions for %s/%s: %w", ecosystem, name, err) } - for _, v := range versions { - if err := fn(PackageVersion{Ecosystem: ecosystem, Name: name, Version: v}); err != nil { + for _, v := range listed { + pv := PackageVersion{Ecosystem: ecosystem, Name: name, Version: v, Namespace: namespace, Qualifiers: qualifiers} + if takesPlatforms(ecosystem) { + pv.Platforms = s.Platforms + } + if err := fn(pv); err != nil { return err } } @@ -91,27 +111,59 @@ func (s *PURLSource) Enumerate(ctx context.Context, fn func(PackageVersion) erro return nil } -func (s *PURLSource) fetchVersions(ctx context.Context, client *registries.Client, ecosystem, name string) ([]string, error) { - reg, err := registries.New(purl.EcosystemToPURLType(ecosystem), "", client) - if err != nil { - return nil, err +func (s *PURLSource) listVersions(ctx context.Context, versions VersionLister, ecosystem, name string) ([]string, error) { + if !s.Latest { + return versions.ListVersions(ctx, ecosystem, name) } - versions, err := reg.FetchVersions(ctx, name) - if err != nil { - return nil, err + var latest string + if finder, ok := versions.(LatestFinder); ok { + v, err := finder.LatestVersion(ctx, ecosystem, name) + if err != nil { + return nil, err + } + latest = v + } else { + listed, err := versions.ListVersions(ctx, ecosystem, name) + if err != nil { + return nil, err + } + all := make([]registries.Version, len(listed)) + for i, v := range listed { + all[i] = registries.Version{Number: v} + } + if v := registries.SelectLatestVersion(all, purl.EcosystemToPURLType(ecosystem), ""); v != nil { + latest = v.Number + } } - result := make([]string, len(versions)) - for i, v := range versions { - result[i] = v.Number + if latest == "" { + return nil, nil } - return result, nil + return []string{latest}, nil +} + +// mirrorTarget returns the ecosystem, name and file qualifiers a PURL is +// mirrored under. +func mirrorTarget(p *purl.PURL) (ecosystem, name string, qualifiers map[string]string) { + ecosystem, name = packageurl.HandlerPackage(p) + qualifiers = fileQualifiers(ecosystem, p.Qualifiers.Map()) + switch ecosystem { + case "julia": + qualifiers = map[string]string{"uuid": p.Qualifier("uuid")} + case "alpine": + qualifiers = map[string]string{"arch": p.Qualifier("arch"), "distro": p.Qualifier("distro")} + } + return ecosystem, name, qualifiers } // SBOMSource extracts package versions from CycloneDX or SPDX SBOM data. type SBOMSource struct { - Data []byte - Name string - RegClient *registries.Client + Data []byte + Name string + // Versions lists the versions of unversioned PURLs. Nil lists them from + // the public registries. + Versions VersionLister + // Latest mirrors only the newest version of unversioned PURLs. + Latest bool // Platforms limit which platforms of container images are mirrored. Platforms []string } @@ -125,80 +177,36 @@ func (s *SBOMSource) Enumerate(ctx context.Context, fn func(PackageVersion) erro return fmt.Errorf("parsing SBOM: %w", err) } - inner := &PURLSource{PURLs: purls, RegClient: s.RegClient, Platforms: s.Platforms} + inner := &PURLSource{PURLs: purls, Versions: s.Versions, Latest: s.Latest, Platforms: s.Platforms} return inner.Enumerate(ctx, fn) } func (s *SBOMSource) extractPURLs() ([]string, error) { - // Try CycloneDX first - if purls, err := extractCycloneDXPURLs(s.Data); err == nil && len(purls) > 0 { - return purls, nil + doc, err := sbom.Parse(s.Data) + if err != nil { + return nil, err } - - // Try SPDX JSON - if purls, err := extractSPDXJSONPURLs(s.Data); err == nil && len(purls) > 0 { - return purls, nil - } - - // Try SPDX tag-value - if purls, err := extractSPDXTVPURLs(s.Data); err == nil && len(purls) > 0 { - return purls, nil - } - - return nil, fmt.Errorf("could not parse SBOM as CycloneDX or SPDX") -} - -func extractCycloneDXPURLs(data []byte) ([]string, error) { - bom := new(cdx.BOM) - if err := json.Unmarshal(data, bom); err != nil { - // Try XML - decoder := cdx.NewBOMDecoder(bytes.NewReader(data), cdx.BOMFileFormatXML) - bom = new(cdx.BOM) - if err := decoder.Decode(bom); err != nil { - return nil, err - } - } - - if bom.Components == nil { - return nil, nil - } - var purls []string - for _, c := range *bom.Components { - if c.PackageURL != "" { - purls = append(purls, c.PackageURL) + for _, p := range doc.Packages { + for _, ref := range p.ExternalRefs { + if ref.Type != "purl" || ref.Locator == "" { + continue + } + locator := ref.Locator + if p.Version != "" { + parsed, err := purl.Parse(locator) + if err != nil { + return nil, fmt.Errorf("parsing PURL %q: %w", locator, err) + } + if parsed.Version == "" { + locator = parsed.WithVersion(p.Version).String() + } + } + purls = append(purls, locator) } } + if len(purls) == 0 { + return nil, fmt.Errorf("SBOM contains no package URLs") + } return purls, nil } - -func extractSPDXJSONPURLs(data []byte) ([]string, error) { - doc, err := spdxjson.Read(bytes.NewReader(data)) - if err != nil { - return nil, err - } - return extractSPDXDocPURLs(doc), nil -} - -func extractSPDXTVPURLs(data []byte) ([]string, error) { - doc, err := spdxtv.Read(bytes.NewReader(data)) - if err != nil { - return nil, err - } - return extractSPDXDocPURLs(doc), nil -} - -func extractSPDXDocPURLs(doc *spdx.Document) []string { - if doc == nil { - return nil - } - var purls []string - for _, pkg := range doc.Packages { - for _, ref := range pkg.PackageExternalReferences { - if ref.RefType == "purl" { - purls = append(purls, ref.Locator) - } - } - } - return purls -} diff --git a/internal/mirror/source_formats_test.go b/internal/mirror/source_formats_test.go new file mode 100644 index 0000000..972c047 --- /dev/null +++ b/internal/mirror/source_formats_test.go @@ -0,0 +1,74 @@ +package mirror + +import ( + "context" + "reflect" + "testing" +) + +func TestSBOMSourcePreservesPackageIdentities(t *testing.T) { + for name, data := range map[string]string{ + "CycloneDX JSON": `{"components":[ + {"name":"shared","version":"1.0","purl":"pkg:npm/%40alpha/shared@1.0"}, + {"name":"shared","version":"1.0","purl":"pkg:npm/%40beta/shared@1.0"}]}`, + "CycloneDX XML": ` + shared1.0pkg:npm/%40alpha/shared@1.0 + shared1.0pkg:npm/%40beta/shared@1.0 + `, + "SPDX JSON": `{"spdxVersion":"SPDX-2.3","packages":[{"name":"shared","versionInfo":"1.0","externalRefs":[ + {"referenceType":"purl","referenceLocator":"pkg:npm/%40alpha/shared@1.0"}, + {"referenceType":"purl","referenceLocator":"pkg:npm/%40beta/shared@1.0"}]}]}`, + "SPDX tag-value": `DataLicense: CC0-1.0 +SPDXVersion: SPDX-2.3 +SPDXID: SPDXRef-DOCUMENT +DocumentName: example +DocumentNamespace: https://example.com/sbom +PackageName: shared +SPDXID: SPDXRef-shared +PackageVersion: 1.0 +ExternalRef: PACKAGE-MANAGER purl pkg:npm/%40alpha/shared@1.0 +ExternalRef: PACKAGE-MANAGER purl pkg:npm/%40beta/shared@1.0 +`, + } { + t.Run(name, func(t *testing.T) { + source := &SBOMSource{Data: []byte(data), Name: name} + var got []PackageVersion + err := source.Enumerate(context.Background(), func(pv PackageVersion) error { + got = append(got, pv) + return nil + }) + if err != nil { + t.Fatal(err) + } + want := []PackageVersion{ + {Ecosystem: "npm", Name: "@alpha/shared", Version: "1.0"}, + {Ecosystem: "npm", Name: "@beta/shared", Version: "1.0"}, + } + if !reflect.DeepEqual(got, want) { + t.Errorf("Enumerate = %+v, want %+v", got, want) + } + }) + } +} + +func TestSBOMSourcePreservesImageOptions(t *testing.T) { + source := &SBOMSource{ + Data: []byte(`{"bomFormat":"CycloneDX","components":[{"name":"alpine","purl":"pkg:docker/library/alpine@3.20?repository_url=ghcr.io&arch=arm64"}]}`), + Platforms: []string{"linux/amd64"}, + } + var got []PackageVersion + if err := source.Enumerate(context.Background(), func(pv PackageVersion) error { + got = append(got, pv) + return nil + }); err != nil { + t.Fatal(err) + } + want := []PackageVersion{{ + Ecosystem: "docker", Name: "library/alpine", Version: "3.20", + Qualifiers: map[string]string{"repository_url": "ghcr.io", "arch": "arm64"}, + Platforms: []string{"linux/amd64"}, + }} + if !reflect.DeepEqual(got, want) { + t.Errorf("Enumerate = %+v, want %+v", got, want) + } +} diff --git a/internal/mirror/source_test.go b/internal/mirror/source_test.go index fe56ca4..faddf35 100644 --- a/internal/mirror/source_test.go +++ b/internal/mirror/source_test.go @@ -3,6 +3,7 @@ package mirror import ( "context" "encoding/json" + "slices" "strings" "testing" ) @@ -211,8 +212,6 @@ func TestSBOMSourceEmptyCycloneDX(t *testing.T) { "bomFormat": "CycloneDX", "specVersion": "1.4", } - // This should fall through to SPDX parsing, which will also fail, - // resulting in an error about not being able to parse source := &SBOMSource{Data: marshalJSON(t, bom)} err := source.Enumerate(context.Background(), func(pv PackageVersion) error { return nil @@ -230,3 +229,39 @@ func marshalJSON(t *testing.T, v any) []byte { } return data } + +// The mirror files packages under the ecosystem and package names the +// handlers use, so a mirrored package and the same package cached by a client +// share one name. +func TestPURLSourceUsesHandlerEcosystemNames(t *testing.T) { + source := &PURLSource{PURLs: []string{ + "pkg:gem/rake@13.2.1", + "pkg:composer/psr/log@3.0.2", + "pkg:apk/alpine/curl@8.14.1-r2", + "pkg:npm/left-pad@1.3.0", + "pkg:maven/org.slf4j/slf4j-api@2.0.13", + "pkg:pypi/Zope.Interface@6.4", + "pkg:nuget/Newtonsoft.Json@13.0.3", + }} + + var got []string + if err := source.Enumerate(context.Background(), func(pv PackageVersion) error { + got = append(got, pv.Ecosystem+" "+pv.Name) + return nil + }); err != nil { + t.Fatalf("Enumerate() error = %v", err) + } + + want := []string{ + "gem rake", + "composer psr/log", + "alpine curl", + "npm left-pad", + "maven org.slf4j:slf4j-api", + "pypi zope-interface", + "nuget newtonsoft.json", + } + if !slices.Equal(got, want) { + t.Errorf("packages = %q, want %q", got, want) + } +} diff --git a/internal/mirror/swift.go b/internal/mirror/swift.go new file mode 100644 index 0000000..153bb10 --- /dev/null +++ b/internal/mirror/swift.go @@ -0,0 +1,57 @@ +package mirror + +import ( + "context" + "fmt" + "strings" + + "github.com/git-pkgs/proxy/internal/handler" +) + +// mirrorSwift mirrors the source archive of a Swift registry release, with +// its release metadata, from the registry the proxy serves Swift packages +// from. +func (m *Mirror) mirrorSwift(ctx context.Context, pv PackageVersion, tracker *progressTracker) { + upstream, err := m.registryURL("swift", pv.Name) + if err != nil { + m.recordFailure(tracker, pv, err) + return + } + h := handler.NewSwiftHandler(m.proxy, "", upstream) + var scope, name string + if source := handler.SwiftSourceURL(pv.Name); source != "" { + scope, name, err = h.ResolveIdentity(ctx, source) + } else { + scope, name, err = swiftScopeAndName(pv.Name) + } + if err != nil { + m.recordFailure(tracker, pv, err) + return + } + result, err := h.MirrorRelease(ctx, scope, name, pv.Version) + if err != nil { + m.recordFailure(tracker, pv, err) + return + } + m.recordResult(tracker, pv, result) +} + +// registryURL returns the registry base URL Versions lists purlType packages +// from, which is the configured upstream, or empty for the default one. +func (m *Mirror) registryURL(purlType, name string) (string, error) { + if r, ok := m.Versions.(RegistryVersions); ok && r.URL != nil { + return r.URL(purlType, name) + } + return "", nil +} + +// swiftScopeAndName splits the name of a pkg:swift PURL whose namespace is +// a registry scope, as in pkg:swift/apple/swift-nio for the identity +// apple.swift-nio. +func swiftScopeAndName(name string) (scope, pkg string, _ error) { + scope, pkg, ok := strings.Cut(name, "/") + if !ok || scope == "" || pkg == "" || strings.ContainsAny(scope, ".:") || strings.Contains(pkg, "/") { + return "", "", fmt.Errorf("pkg:swift/%s needs a registry scope or a source repository as the namespace, such as pkg:swift/apple/swift-nio or pkg:swift/github.com/apple/swift-nio", name) + } + return scope, pkg, nil +} diff --git a/internal/mirror/swift_test.go b/internal/mirror/swift_test.go new file mode 100644 index 0000000..4ae0764 --- /dev/null +++ b/internal/mirror/swift_test.go @@ -0,0 +1,43 @@ +package mirror + +import ( + "context" + "net/http" + "net/http/httptest" + "testing" + + "github.com/git-pkgs/registries" +) + +func TestSwiftIdentity(t *testing.T) { + registry := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/identifiers" || r.Header.Get("Accept") != "application/vnd.swift.registry.v1+json" { + http.Error(w, "unexpected request", http.StatusBadRequest) + return + } + switch r.URL.Query().Get("url") { + case "https://github.com/apple/swift-nio": + _, _ = w.Write([]byte(`{"identifiers":["apple.swift-nio","mirror.swift-nio"]}`)) + case "https://github.com/acme/empty": + _, _ = w.Write([]byte(`{"identifiers":[]}`)) + default: + http.NotFound(w, r) + } + })) + defer registry.Close() + + for name, want := range map[string]string{ + "apple/swift-nio": "apple.swift-nio", + "github.com/apple/swift-nio": "apple.swift-nio", + "github.com/acme/empty": "", + "github.com/acme/unknown": "", + "swift-nio": "", + "apple/": "", + "apple/swift-nio/extra": "", + } { + got, err := swiftIdentity(context.Background(), registries.DefaultClient(), registry.URL, name) + if got != want || (want == "") != (err != nil) { + t.Errorf("swiftIdentity(%q) = %q, %v; want %q", name, got, err, want) + } + } +} diff --git a/internal/mirror/versions.go b/internal/mirror/versions.go new file mode 100644 index 0000000..0a7e1ba --- /dev/null +++ b/internal/mirror/versions.go @@ -0,0 +1,174 @@ +package mirror + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "net/http" + "net/url" + "strings" + + "github.com/git-pkgs/proxy/internal/config" + "github.com/git-pkgs/proxy/internal/handler" + "github.com/git-pkgs/purl" + "github.com/git-pkgs/registries" + _ "github.com/git-pkgs/registries/all" +) + +// VersionLister lists the versions of a package, for PURLs without one. +type VersionLister interface { + ListVersions(ctx context.Context, ecosystem, name string) ([]string, error) +} + +// RegistryVersions lists versions through the registries clients. +type RegistryVersions struct { + // Client makes the requests. Nil uses registries.DefaultClient. + Client *registries.Client + // URL returns the registry base URL to list a package from, by PURL + // type. Nil, or an empty URL, uses the public registry. + URL func(purlType, name string) (string, error) +} + +// VersionFinder finds one version of a package, with the files it +// publishes, for ecosystems the mirror fetches from the version's metadata. +type VersionFinder interface { + FindVersion(ctx context.Context, ecosystem, name, version string) (registries.Version, error) +} + +// LatestFinder picks the latest version of a package, for unversioned PURLs +// when only the latest is mirrored. Listers without it fall back to +// registries.SelectLatestVersion over ListVersions. +type LatestFinder interface { + LatestVersion(ctx context.Context, ecosystem, name string) (string, error) +} + +// LatestVersion implements LatestFinder with registries.FetchLatestVersion: +// the version the registry advertises as latest where it has one, such as +// npm's dist-tags.latest, and otherwise the newest version by publish time +// that isn't yanked, retracted or deprecated. +func (r RegistryVersions) LatestVersion(ctx context.Context, ecosystem, name string) (string, error) { + reg, name, err := r.registryFor(ctx, ecosystem, name) + if err != nil { + return "", err + } + v, err := registries.FetchLatestVersion(ctx, reg, name) + if err != nil || v == nil { + return "", err + } + return v.Number, nil +} + +// ListVersions implements VersionLister. +func (r RegistryVersions) ListVersions(ctx context.Context, ecosystem, name string) ([]string, error) { + versions, err := r.fetchVersions(ctx, ecosystem, name) + if err != nil { + return nil, err + } + result := make([]string, len(versions)) + for i, v := range versions { + result[i] = v.Number + } + return result, nil +} + +// FindVersion implements VersionFinder. +func (r RegistryVersions) FindVersion(ctx context.Context, ecosystem, name, version string) (registries.Version, error) { + versions, err := r.fetchVersions(ctx, ecosystem, name) + if err != nil { + return registries.Version{}, err + } + for _, v := range versions { + if v.Number == version { + return v, nil + } + } + return registries.Version{}, fmt.Errorf("%w: %s %s@%s", registries.ErrNotFound, ecosystem, name, version) +} + +func (r RegistryVersions) fetchVersions(ctx context.Context, ecosystem, name string) ([]registries.Version, error) { + reg, name, err := r.registryFor(ctx, ecosystem, name) + if err != nil { + return nil, err + } + return reg.FetchVersions(ctx, name) +} + +// registryFor returns the client for the registry name is listed in, and +// the name the registry knows the package by. +func (r RegistryVersions) registryFor(ctx context.Context, ecosystem, name string) (registries.Registry, string, error) { //nolint:ireturn // registries.New returns the interface + reg, err := r.registry(ecosystem, name) + if err != nil { + return nil, "", err + } + switch purl.EcosystemToPURLType(ecosystem) { + case "helm": + // The namespace names the repository, which URL resolves to the + // index the chart is listed in. + _, name, _ = strings.Cut(name, "/") + case "swift": + var baseURL string + if baseURL, err = r.baseURL("swift", name); err != nil { + return nil, "", err + } + if name, err = swiftIdentity(ctx, r.client(), baseURL, name); err != nil { + return nil, "", err + } + } + return reg, name, nil +} + +// registry returns the client for the registry name is listed in. +func (r RegistryVersions) registry(ecosystem, name string) (registries.Registry, error) { //nolint:ireturn // registries.New returns the interface + purlType := purl.EcosystemToPURLType(ecosystem) + baseURL, err := r.baseURL(purlType, name) + if err != nil { + return nil, err + } + return registries.New(purlType, baseURL, r.client()) +} + +func (r RegistryVersions) baseURL(purlType, name string) (string, error) { + if r.URL == nil { + return "", nil + } + return r.URL(purlType, name) +} + +func (r RegistryVersions) client() *registries.Client { + if r.Client == nil { + return registries.DefaultClient() + } + return r.Client +} + +// swiftIdentity returns the registry identity, scope.name, of the name of a +// pkg:swift PURL, looking a source repository up on the registry at baseURL. +func swiftIdentity(ctx context.Context, client *registries.Client, baseURL, name string) (string, error) { + source := handler.SwiftSourceURL(name) + if source == "" { + scope, pkg, err := swiftScopeAndName(name) + if err != nil { + return "", err + } + return scope + "." + pkg, nil + } + if baseURL == "" { + baseURL = config.DefaultSwiftUpstream + } + var body json.RawMessage + _, err := client.GetJSONWithHeaders(ctx, + strings.TrimSuffix(baseURL, "/")+"/identifiers?"+url.Values{"url": {source}}.Encode(), + http.Header{"Accept": {"application/vnd.swift.registry.v1+json"}}, &body) + if httpErr := (*registries.HTTPError)(nil); errors.As(err, &httpErr) && httpErr.IsNotFound() { + return "", fmt.Errorf("the Swift registry has no package for %s", source) + } + if err != nil { + return "", err + } + scope, pkg, err := handler.SwiftIdentityOf(body, source) + if err != nil { + return "", err + } + return scope + "." + pkg, nil +} diff --git a/internal/mirror/versions_test.go b/internal/mirror/versions_test.go new file mode 100644 index 0000000..29f9f41 --- /dev/null +++ b/internal/mirror/versions_test.go @@ -0,0 +1,118 @@ +package mirror + +import ( + "context" + "encoding/json" + "errors" + "reflect" + "testing" +) + +// fakeVersions lists fixed versions and records what it was asked for. +type fakeVersions struct { + versions []string + err error + asked []string +} + +func (f *fakeVersions) ListVersions(_ context.Context, ecosystem, name string) ([]string, error) { + f.asked = append(f.asked, ecosystem+"/"+name) + return f.versions, f.err +} + +func enumerate(t *testing.T, source Source) []PackageVersion { + t.Helper() + var items []PackageVersion + if err := source.Enumerate(context.Background(), func(pv PackageVersion) error { + items = append(items, pv) + return nil + }); err != nil { + t.Fatalf("Enumerate() error = %v", err) + } + return items +} + +func TestPURLSourceListsVersionsThroughLister(t *testing.T) { + versions := &fakeVersions{versions: []string{"1.0.0", "1.1.0"}} + source := &PURLSource{PURLs: []string{"pkg:npm/%40acme/widget"}, Versions: versions} + + items := enumerate(t, source) + + want := []PackageVersion{ + {Ecosystem: "npm", Name: "@acme/widget", Version: "1.0.0"}, + {Ecosystem: "npm", Name: "@acme/widget", Version: "1.1.0"}, + } + if !reflect.DeepEqual(items, want) { + t.Errorf("items = %v, want %v", items, want) + } + if !reflect.DeepEqual(versions.asked, []string{"npm/@acme/widget"}) { + t.Errorf("lister asked for %v, want npm/@acme/widget", versions.asked) + } +} + +func TestPURLSourceReportsListerError(t *testing.T) { + source := &PURLSource{PURLs: []string{"pkg:npm/left-pad"}, Versions: &fakeVersions{err: errors.New("upstream down")}} + err := source.Enumerate(context.Background(), func(PackageVersion) error { return nil }) + if err == nil { + t.Fatal("Enumerate() succeeded although listing versions failed") + } +} + +func TestSBOMSourceListsVersionsThroughLister(t *testing.T) { + bom := map[string]any{ + "bomFormat": "CycloneDX", + "specVersion": "1.4", + "components": []map[string]any{{"type": "library", "name": "left-pad", "purl": "pkg:npm/left-pad"}}, + } + versions := &fakeVersions{versions: []string{"1.3.0"}} + source := &SBOMSource{Data: marshalJSON(t, bom), Versions: versions} + + items := enumerate(t, source) + + if len(items) != 1 || items[0].Version != "1.3.0" { + t.Errorf("items = %v, want left-pad@1.3.0 from the lister", items) + } +} + +func TestSourceFromRequestUsesMirrorVersions(t *testing.T) { + m := setupTestMirror(t, 1) + versions := &fakeVersions{} + m.Versions = versions + js := NewJobStore(context.Background(), m) + + source, err := js.sourceFromRequest(JobRequest{PURLs: []string{"pkg:npm/left-pad"}}) + if err != nil { + t.Fatalf("sourceFromRequest() error = %v", err) + } + if got := source.(*PURLSource).Versions; got != versions { + t.Errorf("PURL source lists versions through %v, want the mirror's lister", got) + } + + source, err = js.sourceFromRequest(JobRequest{SBOM: json.RawMessage(`{"bomFormat":"CycloneDX","components":[]}`)}) + if err != nil { + t.Fatalf("sourceFromRequest() error = %v", err) + } + if got := source.(*SBOMSource).Versions; got != versions { + t.Errorf("SBOM source lists versions through %v, want the mirror's lister", got) + } +} + +func TestPURLSourceKeepsJuliaUUID(t *testing.T) { + const uuid = "7876af07-990d-54b4-ab0e-23690620f79a" + versions := &fakeVersions{versions: []string{"0.5.5"}} + source := &PURLSource{ + PURLs: []string{"pkg:julia/Example@0.5.4?uuid=" + uuid, "pkg:julia/Example?uuid=" + uuid}, + Versions: versions, + } + + items := enumerate(t, source) + + qualifiers := map[string]string{"uuid": uuid} + want := []PackageVersion{ + {Ecosystem: "julia", Name: "Example", Version: "0.5.4", Qualifiers: qualifiers}, + {Ecosystem: "julia", Name: "Example", Version: "0.5.5", Qualifiers: qualifiers}, + } + if !reflect.DeepEqual(items, want) { + t.Errorf("items = %v, want %v", items, want) + } +} diff --git a/internal/packageurl/handler.go b/internal/packageurl/handler.go new file mode 100644 index 0000000..5edcf80 --- /dev/null +++ b/internal/packageurl/handler.go @@ -0,0 +1,70 @@ +package packageurl + +import ( + "github.com/git-pkgs/purl" +) + +// distroTypes are PURL types whose namespace names the distribution +// ("alpine", "debian"), not part of the package name the handlers store. +var distroTypes = map[string]bool{"alpm": true, "apk": true, "bsd": true, "deb": true, "rpm": true} + +// DistroType reports whether a PURL type's namespace names the distribution, +// so that handlers ignore it. +func DistroType(purlType string) bool { + return distroTypes[purlType] +} + +// HandlerEcosystem returns the ecosystem name the proxy's handlers store +// packages of a PURL type under. purl names gem and composer after their +// registries, rubygems and packagist; the handlers use the type. +func HandlerEcosystem(purlType string) string { + switch purlType { + case "gem", "composer": + return purlType + default: + return purl.PURLTypeToEcosystem(purlType) + } +} + +// HandlerPackage returns the ecosystem and package name the proxy's handlers +// store p under, so a package named in a PURL, such as one from an SBOM, +// matches the package a client fetched through the proxy: +// +// - apk, alpm, bsd, deb and rpm: the namespace names the distribution and +// is dropped +// - conda: the channel, from the namespace or the channel qualifier, is +// part of the name ("conda-forge/numpy"); without either the name stays +// bare +// - pypi and nuget: the name in purl's comparison form, PEP 503 for PyPI +// and lowercased for NuGet, as the handlers store them +// - swift: namespace/name, the registry scope or the source repository +// with the package, which the Swift mirror resolves; purl's full name +// is the registry identity scope.name +// +// Other types use purl's full name, which keeps the namespace: "@babel/core", +// or "org.slf4j:slf4j-api" for Maven, as its handler stores it. +func HandlerPackage(p *purl.PURL) (ecosystem, name string) { + ecosystem = HandlerEcosystem(p.Type) + switch { + case distroTypes[p.Type]: + return ecosystem, p.Name + case p.Type == "conda": + return ecosystem, condaName(p.Namespace, p.Name, p.Qualifier("channel")) + case p.Type == "pypi" || p.Type == "nuget": + return ecosystem, p.ComparisonForm().FullName() + case p.Type == "swift" && p.Namespace != "": + return ecosystem, p.Namespace + "/" + p.Name + } + return ecosystem, p.FullName() +} + +func condaName(namespace, name, channel string) string { + switch { + case namespace != "": + return namespace + "/" + name + case channel != "": + return channel + "/" + name + default: + return name + } +} diff --git a/internal/packageurl/handler_test.go b/internal/packageurl/handler_test.go new file mode 100644 index 0000000..7283b9f --- /dev/null +++ b/internal/packageurl/handler_test.go @@ -0,0 +1,62 @@ +package packageurl + +import ( + "testing" + + "github.com/git-pkgs/purl" +) + +// HandlerPackage is used by both the mirror and the project inventory, so a +// mirrored package, a package listed in an SBOM and the same package fetched +// by a client end up under one name. +func TestHandlerPackage(t *testing.T) { + tests := []struct { + purl string + ecosystem string + name string + }{ + // purl names these after their registries; the handlers use the type. + {"pkg:gem/rake@13.2.1", "gem", "rake"}, + {"pkg:composer/psr/log@3.0.2", "composer", "psr/log"}, + // Distribution namespaces are dropped. + {"pkg:apk/alpine/busybox@1.36.1-r15?arch=x86_64", "alpine", "busybox"}, + {"pkg:apk/curl@8.14.1-r2", "alpine", "curl"}, + {"pkg:alpm/arch/glibc@2.39-1", "arch", "glibc"}, + {"pkg:bsd/freebsd/curl@8.7.1", "freebsd", "curl"}, + {"pkg:deb/debian/libc6@2.36-9?arch=amd64", "deb", "libc6"}, + {"pkg:rpm/fedora/curl@8.6.0-7.fc40", "rpm", "curl"}, + // The conda channel is part of the name. + {"pkg:conda/numpy@1.26.4?channel=conda-forge", "conda", "conda-forge/numpy"}, + {"pkg:conda/conda-forge/numpy@1.26.4", "conda", "conda-forge/numpy"}, + {"pkg:conda/numpy@1.26.4", "conda", "numpy"}, + // PyPI names are normalized as PEP 503 does, NuGet IDs lowercased. + {"pkg:pypi/Zope.Interface@6.4", "pypi", "zope-interface"}, + {"pkg:pypi/zope_interface", "pypi", "zope-interface"}, + {"pkg:nuget/Newtonsoft.Json@13.0.3", "nuget", "newtonsoft.json"}, + // Other namespaces stay part of the name. + {"pkg:npm/%40babel/core@7.23.0", "npm", "@babel/core"}, + // The Maven handler stores "group:artifact". + {"pkg:maven/org.slf4j/slf4j-api@2.0.13", "maven", "org.slf4j:slf4j-api"}, + {"pkg:docker/library/alpine@3.20", "docker", "library/alpine"}, + {"pkg:julia/Example@0.5.3?uuid=7876af07-990d-54b4-ab0e-23690620f79a", "julia", "Example"}, + // Swift keeps namespace/name, the scope or the source repository, + // which the Swift mirror splits again; purl's full name would be the + // registry identity "scope.name". + {"pkg:swift/Acme/Widget@1.0.0", "swift", "Acme/Widget"}, + {"pkg:swift/github.com/apple/swift-nio@2.62.0", "swift", "github.com/apple/swift-nio"}, + // Go module paths keep their case. + {"pkg:golang/github.com/Azure/foo@v1.2.0", "golang", "github.com/Azure/foo"}, + } + for _, tt := range tests { + t.Run(tt.purl, func(t *testing.T) { + p, err := purl.Parse(tt.purl) + if err != nil { + t.Fatal(err) + } + ecosystem, name := HandlerPackage(p) + if ecosystem != tt.ecosystem || name != tt.name { + t.Errorf("HandlerPackage(%q) = %q, %q, want %q, %q", tt.purl, ecosystem, name, tt.ecosystem, tt.name) + } + }) + } +} diff --git a/internal/packageurl/packageurl.go b/internal/packageurl/packageurl.go index 7110942..e01f4b2 100644 --- a/internal/packageurl/packageurl.go +++ b/internal/packageurl/packageurl.go @@ -18,6 +18,15 @@ func MakeString(ecosystem, name, version string) string { return purl.MakePURLString(ecosystem, name, version) } +// PolicyPackageKey maps a canonical versionless PURL to its policy key. +// Go policies match module names case-insensitively for compatibility. +func PolicyPackageKey(packagePURL string) string { + if strings.HasPrefix(packagePURL, "pkg:golang/") { + return strings.ToLower(packagePURL) + } + return packagePURL +} + // WithVersionString returns a package PURL with its version replaced. It // returns an empty string when packagePURL is invalid. func WithVersionString(packagePURL, version string) string { @@ -29,25 +38,19 @@ func WithVersionString(packagePURL, version string) string { } // MakeCacheStrings returns package and version PURLs suitable for artifact -// cache records. Swift registry identities use an explicit generic PURL until -// their source repository has been resolved. The result is independent of the -// configured upstream so cache entries survive an upstream.swift change, -// matching every other ecosystem. +// cache records. Swift registry identities keep their generic storage PURLs. +// Cache keys are independent of the configured upstream. func MakeCacheStrings(ecosystem, name, version string) (packagePURL, versionPURL string) { + if purl.NormalizeEcosystem(ecosystem) == "swift" { + if identity, ok := swiftRegistryIdentity(name); ok { + pkg := purl.New("generic", "swift-registry", identity, "", nil) + return pkg.String(), pkg.WithVersion(version).String() + } + } if pkg := Make(ecosystem, name, ""); pkg != nil { return pkg.String(), pkg.WithVersion(version).String() } - if purl.NormalizeEcosystem(ecosystem) != "swift" { - return "", "" - } - - identity, ok := swiftRegistryIdentity(name) - if !ok { - return "", "" - } - - pkg := purl.New("generic", "swift-registry", identity, "", nil) - return pkg.String(), pkg.WithVersion(version).String() + return "", "" } func swiftRegistryIdentity(name string) (string, bool) { diff --git a/internal/packageurl/packageurl_test.go b/internal/packageurl/packageurl_test.go index 8982288..5a46776 100644 --- a/internal/packageurl/packageurl_test.go +++ b/internal/packageurl/packageurl_test.go @@ -2,17 +2,12 @@ package packageurl import "testing" -func TestMakeSwiftRegistryIdentityUnsupported(t *testing.T) { - identities := []string{"apple.swift-argument-parser", "apple/swift-argument-parser"} - for _, identity := range identities { - t.Run(identity, func(t *testing.T) { - if got := Make("swift", identity, "1.8.2"); got != nil { - t.Errorf("Make() = %q, want nil", got.String()) - } - if got := MakeString("swift", identity, "1.8.2"); got != "" { - t.Errorf("MakeString() = %q, want empty string", got) - } - }) +func TestMakeSwiftRegistryPathUnsupported(t *testing.T) { + if got := Make("swift", "apple/swift-argument-parser", "1.8.2"); got != nil { + t.Errorf("Make() = %q, want nil", got.String()) + } + if got := MakeString("swift", "apple/swift-argument-parser", "1.8.2"); got != "" { + t.Errorf("MakeString() = %q, want empty string", got) } } @@ -49,9 +44,11 @@ func TestMakeCacheStringsSwiftRegistryIdentity(t *testing.T) { t.Errorf("version PURL = %q, want %q", versionPURL, wantVersion) } - dottedPackage, dottedVersion := MakeCacheStrings("swift", "apple.example", "1.2.3") - if dottedPackage != packagePURL || dottedVersion != versionPURL { - t.Errorf("dotted identity cache PURLs = %q, %q; want %q, %q", dottedPackage, dottedVersion, packagePURL, versionPURL) + for _, identity := range []string{"apple.example", "APPLE.EXAMPLE", "apple/example"} { + dottedPackage, dottedVersion := MakeCacheStrings("Swift", identity, "1.2.3") + if dottedPackage != packagePURL || dottedVersion != versionPURL { + t.Errorf("%q cache PURLs = %q, %q; want %q, %q", identity, dottedPackage, dottedVersion, packagePURL, versionPURL) + } } } diff --git a/internal/retention/retention.go b/internal/retention/retention.go index c26ef4a..156e410 100644 --- a/internal/retention/retention.go +++ b/internal/retention/retention.go @@ -14,6 +14,7 @@ import ( "sync" "time" + "github.com/git-pkgs/proxy/internal/packageurl" "github.com/git-pkgs/purl" ) @@ -22,8 +23,8 @@ import ( // outside this list is a typo; a key in it whose handler has not registered // yet is not supported by this version. var KnownKeys = []string{ - "alpine", "cargo", "composer", "conan", "conda", "cran", "deb", "gem", - "golang", "helm", "hex", "julia", "maven", "npm", "nuget", "oci", "pub", + "alpine", "cargo", "composer", "conan", "conda", "cran", "deb", "freebsd", "gem", + "generic", "golang", "helm", "hex", "julia", "maven", "npm", "nuget", "oci", "pub", "pypi", "rpm", "swift", } @@ -41,11 +42,18 @@ type Spec struct { // derived from Key that belong to this ecosystem. ExtraDBEcosystems []string - // CanonicalPackage turns a package PURL from the config into the - // package PURL the handler stores in the cache, reporting false when the + // CanonicalPackage turns a package PURL from the config into a + // policy key, reporting false when the // PURL does not belong to this ecosystem. Nil means the ecosystem accepts // no package overrides. CanonicalPackage func(p *purl.PURL) (string, bool) + + // SourcePackage reports a package PURL that names the package by where + // its source lives, such as a Swift package by its repository. It has to + // be resolved through the upstream before it can be compared, so the + // config keeps it in Rules.Sources until then. Nil means the ecosystem + // has no such form. + SourcePackage func(p *purl.PURL) bool } // dbEcosystems returns every packages.ecosystem value that belongs to the @@ -150,8 +158,7 @@ func (r *Registry) KeyForDBEcosystem(ecosystem string) (string, bool) { return key, ok } -// Canonical returns the stored package PURL a configured package PURL -// stands for, asking the registered specs in key order. +// Canonical returns the policy key for a configured package PURL. func (r *Registry) Canonical(p *purl.PURL) (string, bool) { for _, key := range r.Keys() { s, _ := r.Lookup(key) @@ -165,27 +172,78 @@ func (r *Registry) Canonical(p *purl.PURL) (string, bool) { return "", false } +// Source returns the ecosystem key whose SourcePackage claims p. +func (r *Registry) Source(p *purl.PURL) (string, bool) { + for _, key := range r.Keys() { + s, _ := r.Lookup(key) + if s.SourcePackage != nil && s.SourcePackage(p) { + return key, true + } + } + return "", false +} + // Rules are resolved retention durations. A duration of zero means an // artifact is never evicted by age. type Rules struct { - // Default applies to registered ecosystems without their own rule. + // Default applies to registered ecosystems without their own rule, + // except generic, which requires an explicit rule. Default time.Duration // Ecosystems holds rules keyed by registered ecosystem key. Ecosystems map[string]time.Duration - // Packages holds rules keyed by the package PURL stored in the cache. + // Packages holds rules keyed by package PURL, with Go keys lowercased. Packages map[string]time.Duration + // Sources holds package rules not resolved to a stored package PURL + // yet, by ecosystem key and then by the configured PURL (see + // Spec.SourcePackage). An ecosystem with any is not swept, since one of + // them may keep an artifact the sweep would otherwise clear. + Sources map[string]map[string]time.Duration +} + +// Pending reports whether the ecosystem key has package rules still to be +// resolved, and must not be swept. +func (r Rules) Pending(key string) bool { + return len(r.Sources[key]) > 0 +} + +// Resolve moves the rule for source in ecosystem key to every stored package +// PURL it resolved to. A different rule already set for any of them is a +// conflict, and the source stays pending with none of them set. +func (r Rules) Resolve(key, source string, canonical []string) error { + d, ok := r.Sources[key][source] + if !ok { + return nil + } + if len(canonical) == 0 { + return fmt.Errorf("%s resolves to no stored package", source) + } + for _, c := range canonical { + if prev, set := r.Packages[c]; set && prev != d { + return fmt.Errorf("%s resolves to %s, which another rule sets differently", source, c) + } + } + for _, c := range canonical { + r.Packages[c] = d + } + delete(r.Sources[key], source) + return nil } // For returns the retention for an artifact of the given ecosystem key and // stored package PURL: the package rule, else the ecosystem rule, else the -// default. +// default. Generic artifacts require an explicit package or ecosystem rule. func (r Rules) For(key, packagePURL string) time.Duration { + packagePURL = packageurl.PolicyPackageKey(packagePURL) if d, ok := r.Packages[packagePURL]; ok { return d } if d, ok := r.Ecosystems[key]; ok { return d } + // Release assets may disappear upstream, so keep generic opt-in. + if key == "generic" { + return 0 + } return r.Default } @@ -205,5 +263,10 @@ func (r Rules) MinPositive() time.Duration { for _, d := range r.Packages { consider(d) } + for _, sources := range r.Sources { + for _, d := range sources { + consider(d) + } + } return minimum } diff --git a/internal/retention/retention_test.go b/internal/retention/retention_test.go index 9fa67b7..5036375 100644 --- a/internal/retention/retention_test.go +++ b/internal/retention/retention_test.go @@ -56,7 +56,7 @@ func TestRegistryRegisterPanics(t *testing.T) { name string specs []Spec }{ - {"unknown key", []Spec{{Key: "generic"}}}, + {"unknown key", []Spec{{Key: "not-an-ecosystem"}}}, {"duplicate key", []Spec{{Key: "npm"}, {Key: "npm"}}}, {"overlapping ecosystem value", []Spec{{Key: "gem"}, {Key: "npm", ExtraDBEcosystems: []string{"rubygems"}}}}, } @@ -148,6 +148,37 @@ func TestRulesFor(t *testing.T) { } } +func TestGenericRulesRequireExplicitConfiguration(t *testing.T) { + day := 24 * time.Hour + const pkg = "pkg:generic/jqlang%2Fjq" + tests := []struct { + name string + ecosystems map[string]time.Duration + packages map[string]time.Duration + want time.Duration + }{ + {"global default ignored", nil, nil, 0}, + {"ecosystem rule", map[string]time.Duration{"generic": 7 * day}, nil, 7 * day}, + {"ecosystem disabled", map[string]time.Duration{"generic": 0}, nil, 0}, + {"package only", nil, map[string]time.Duration{pkg: 14 * day}, 14 * day}, + {"other package ignored", nil, map[string]time.Duration{"pkg:generic/other%2Frepo": day}, 0}, + {"package overrides ecosystem", map[string]time.Duration{"generic": 7 * day}, map[string]time.Duration{pkg: 14 * day}, 14 * day}, + {"package disables eviction", map[string]time.Duration{"generic": 7 * day}, map[string]time.Duration{pkg: 0}, 0}, + {"package enables eviction", map[string]time.Duration{"generic": 0}, map[string]time.Duration{pkg: day}, day}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + rules := Rules{Default: 30 * day, Ecosystems: tt.ecosystems, Packages: tt.packages} + if got := rules.For("generic", pkg); got != tt.want { + t.Errorf("generic retention = %v, want %v", got, tt.want) + } + if got := rules.For("npm", "pkg:npm/lodash"); got != 30*day { + t.Errorf("npm default retention = %v, want 30d", got) + } + }) + } +} + func TestRulesMinPositive(t *testing.T) { if got := (Rules{}).MinPositive(); got != 0 { t.Errorf("empty rules MinPositive() = %v, want 0", got) @@ -161,3 +192,53 @@ func TestRulesMinPositive(t *testing.T) { t.Errorf("MinPositive() = %v, want 2h", got) } } + +func TestRulesResolveSources(t *testing.T) { + rules := Rules{ + Packages: map[string]time.Duration{"pkg:x/kept": 0}, + Sources: map[string]map[string]time.Duration{"swift": { + "pkg:swift/github.com/a/one": 0, + "pkg:swift/github.com/a/two": time.Hour, + }}, + } + if got := rules.MinPositive(); got != time.Hour { + t.Errorf("MinPositive = %v, want the pending rule's hour", got) + } + if err := rules.Resolve("swift", "pkg:swift/github.com/a/two", []string{"pkg:x/kept"}); err == nil { + t.Error("a rule resolving to a package another rule sets differently was accepted") + } + if !rules.Pending("swift") { + t.Fatal("conflicting rule no longer pending") + } + if err := rules.Resolve("swift", "pkg:swift/github.com/a/one", []string{"pkg:x/kept"}); err != nil { + t.Errorf("same duration for the same package: %v", err) + } + if err := rules.Resolve("swift", "pkg:swift/github.com/a/two", []string{"pkg:x/two"}); err != nil { + t.Fatal(err) + } + if rules.Pending("swift") || rules.Packages["pkg:x/two"] != time.Hour { + t.Errorf("after resolving: sources %v, packages %v", rules.Sources, rules.Packages) + } +} + +// A source that resolves to several stored packages sets the rule for all +// of them, or, on a conflict with any, for none. +func TestRulesResolveSeveralPackages(t *testing.T) { + rules := Rules{ + Packages: map[string]time.Duration{"pkg:x/b": time.Hour}, + Sources: map[string]map[string]time.Duration{"swift": {"pkg:swift/github.com/a/one": 0}}, + } + if err := rules.Resolve("swift", "pkg:swift/github.com/a/one", []string{"pkg:x/a", "pkg:x/b"}); err == nil { + t.Error("a rule conflicting for one of its packages was accepted") + } + if _, set := rules.Packages["pkg:x/a"]; set || !rules.Pending("swift") { + t.Fatalf("conflicting rule partly applied: sources %v, packages %v", rules.Sources, rules.Packages) + } + delete(rules.Packages, "pkg:x/b") + if err := rules.Resolve("swift", "pkg:swift/github.com/a/one", []string{"pkg:x/a", "pkg:x/b"}); err != nil { + t.Fatal(err) + } + if rules.Pending("swift") || len(rules.Packages) != 2 { + t.Errorf("after resolving: sources %v, packages %v", rules.Sources, rules.Packages) + } +} diff --git a/internal/scanner/group.go b/internal/scanner/group.go index a31d324..a4856e0 100644 --- a/internal/scanner/group.go +++ b/internal/scanner/group.go @@ -67,7 +67,11 @@ func NewGroup(cfg config.ScanningConfig, logger *slog.Logger) (*Group, error) { if len(sc.Ecosystems) > 0 { ecosystems = make(map[string]struct{}, len(sc.Ecosystems)) for _, eco := range sc.Ecosystems { - ecosystems[eco] = struct{}{} + key, err := config.ScannerEcosystemKey(eco) + if err != nil { + return nil, fmt.Errorf("scanner %q: %w", sc.Name, err) + } + ecosystems[key] = struct{}{} } } @@ -86,6 +90,25 @@ func (g *Group) Enabled() bool { return g != nil && len(g.entries) > 0 } +// Covers reports whether any scanner, in either mode, applies to ecosystem. +func (g *Group) Covers(ecosystem string) bool { + return g.Enabled() && len(g.applicable(ecosystem)) > 0 +} + +// Blocks reports whether a block-mode scanner applies to ecosystem, so an +// artifact must be scanned whole before any of it is served. +func (g *Group) Blocks(ecosystem string) bool { + if !g.Enabled() { + return false + } + for _, e := range g.applicable(ecosystem) { + if e.mode == modeBlock { + return true + } + } + return false +} + // Timeout returns the per-scan-call timeout used to bound the signed fetch // URL's validity. func (g *Group) Timeout() time.Duration { @@ -93,6 +116,8 @@ func (g *Group) Timeout() time.Duration { } func (g *Group) applicable(ecosystem string) []entry { + // Callers may pass an alias such as go from a PURL type. + ecosystem = config.NormalizeScannerEcosystem(ecosystem) var out []entry for _, e := range g.entries { if len(e.ecosystems) == 0 { diff --git a/internal/scanner/group_test.go b/internal/scanner/group_test.go index e5b40ee..5dca201 100644 --- a/internal/scanner/group_test.go +++ b/internal/scanner/group_test.go @@ -77,6 +77,33 @@ func TestGroup_Enabled(t *testing.T) { } } +func TestGroup_Covers(t *testing.T) { + var nilGroup *Group + if nilGroup.Covers("npm") { + t.Error("nil group Covers(npm) = true, want false") + } + g, err := NewGroup(config.ScanningConfig{ + Enabled: true, + SigningKey: "test-signing-key", + Scanners: []config.ScannerConfig{ + {Name: "trivy", URL: "http://trivy.invalid", Mode: "monitor", Ecosystems: []string{"npm"}}, + {Name: "clamav", URL: "http://clamav.invalid", Ecosystems: []string{"pypi"}}, + }, + }, discardLogger()) + if err != nil { + t.Fatalf("NewGroup() error: %v", err) + } + for ecosystem, want := range map[string]bool{"npm": true, "pypi": true, "freebsd": false} { + if got := g.Covers(ecosystem); got != want { + t.Errorf("Covers(%s) = %v, want %v", ecosystem, got, want) + } + } + all := newTestGroup([]entry{{mode: modeBlock}}, false) + if !all.Covers("freebsd") { + t.Error("unrestricted scanner: Covers(freebsd) = false, want true") + } +} + func TestGroup_NewGroup_InvalidMode(t *testing.T) { _, err := NewGroup(config.ScanningConfig{ Enabled: true, @@ -243,3 +270,58 @@ func TestGroup_Scan_ErrorFailOpen(t *testing.T) { t.Error("Allowed = false, want true — FailOpen must treat scanner errors as allowed") } } + +func TestGroupBlocks(t *testing.T) { + g, err := NewGroup(config.ScanningConfig{ + Enabled: true, + SigningKey: "key", + Scanners: []config.ScannerConfig{ + {Name: "watch", URL: "http://watch.invalid", Mode: "monitor"}, + {Name: "gate", URL: "http://gate.invalid", Mode: "block", Ecosystems: []string{"npm"}}, + }, + }, slog.New(slog.NewTextHandler(io.Discard, nil))) + if err != nil { + t.Fatal(err) + } + if !g.Blocks("npm") { + t.Error("Blocks(npm) = false with a block-mode scanner for npm") + } + if g.Blocks("pypi") { + t.Error("Blocks(pypi) = true with only a monitor-mode scanner for it") + } + var none *Group + if none.Blocks("npm") { + t.Error("nil group blocks") + } +} + +func TestGroup_NormalisesEcosystemAliases(t *testing.T) { + g, err := NewGroup(config.ScanningConfig{ + Enabled: true, + SigningKey: "test-signing-key", + Scanners: []config.ScannerConfig{ + {Name: "clamav", URL: "http://clamav.invalid", Ecosystems: []string{"go", "docker", "rubygems"}}, + }, + }, discardLogger()) + if err != nil { + t.Fatalf("NewGroup() error: %v", err) + } + for _, ecosystem := range []string{"golang", "oci", "gem", "go", "Docker", "rubygems"} { + if !g.Blocks(ecosystem) { + t.Errorf("Blocks(%s) = false, want true", ecosystem) + } + } +} + +func TestNewGroup_RejectsUnknownEcosystem(t *testing.T) { + _, err := NewGroup(config.ScanningConfig{ + Enabled: true, + SigningKey: "test-signing-key", + Scanners: []config.ScannerConfig{ + {Name: "clamav", URL: "http://clamav.invalid", Ecosystems: []string{"npm", "pypy"}}, + }, + }, discardLogger()) + if err == nil || !strings.Contains(err.Error(), "pypy") { + t.Errorf("NewGroup() error = %v, want unknown ecosystem pypy", err) + } +} diff --git a/internal/server/analytics.go b/internal/server/analytics.go index b7b4a83..2e0e0ce 100644 --- a/internal/server/analytics.go +++ b/internal/server/analytics.go @@ -21,6 +21,7 @@ type AnalyticsData struct { Donut DonutView EnrichmentStats EnrichmentStatsView Ecosystems []EcosystemRow + Metadata MetadataCacheView Runtime RuntimeView // StatsFailed records that the per-ecosystem query errored, so the page // can say the figures are unavailable instead of claiming an empty cache. @@ -66,6 +67,54 @@ type EcosystemRow struct { SharePct string } +// MetadataCacheView summarises the metadata cache, which is stored separately +// from artifacts and so appears in none of the artifact figures. +type MetadataCacheView struct { + // Enabled reports whether cache_metadata is on. Entries can remain from + // an earlier run with it on, so both are shown independently. + Enabled bool + // Failed records that the query errored, so the card can say so rather + // than claim the cache is empty. + Failed bool + Entries string + Size string + Rows []MetadataCacheRow +} + +// MetadataCacheRow is one ecosystem's share of the metadata cache. +type MetadataCacheRow struct { + Ecosystem string + Entries string + Size string + SharePct string +} + +// metadataCacheView turns per-ecosystem metadata cache rows into the card's +// totals and table. +func metadataCacheView(stats []database.MetadataCacheStats, enabled bool) MetadataCacheView { + var entries, size int64 + for _, e := range stats { + entries += e.Entries + size += e.Size + } + + v := MetadataCacheView{ + Enabled: enabled, + Entries: formatCount(entries), + Size: formatSize(size), + Rows: make([]MetadataCacheRow, 0, len(stats)), + } + for _, e := range stats { + v.Rows = append(v.Rows, MetadataCacheRow{ + Ecosystem: e.Ecosystem, + Entries: formatCount(e.Entries), + Size: formatSize(e.Size), + SharePct: formatPercent(e.Size, size), + }) + } + return v +} + func formatCount(n int64) string { s := strconv.FormatInt(n, 10) neg := strings.HasPrefix(s, "-") @@ -165,6 +214,16 @@ func (s *Server) handleAnalytics(w http.ResponseWriter, r *http.Request) { data.Totals, data.Ecosystems = analyticsView(ecosystems) data.Donut = donutView(ecosystems, data.Totals.DownloadedBytes, data.Totals.Downloaded) + // The same 60-second snapshot the metadata cache gauges are published + // from, so a page load costs no query of its own. A failed read keeps the + // last good rows, which the card shows in preference to the error. + metadataStats, err := s.metaStats.Get(s.db) + if err != nil { + s.logger.Error("failed to get metadata cache stats", "error", err) + } + data.Metadata = metadataCacheView(metadataStats, s.cfg != nil && s.cfg.CacheMetadata) + data.Metadata.Failed = err != nil + // Process-lifetime counters come from the Prometheus registry rather than // the database; a failure here must not take the page down with it. snap, err := metrics.Gather() diff --git a/internal/server/analytics_coverage_test.go b/internal/server/analytics_coverage_test.go index 12cc895..02e67e2 100644 --- a/internal/server/analytics_coverage_test.go +++ b/internal/server/analytics_coverage_test.go @@ -5,6 +5,7 @@ import ( "testing" "github.com/git-pkgs/proxy/internal/metrics" + "github.com/prometheus/client_golang/prometheus" ) // metricSurface records where each registered metric is shown on /ui/analytics. @@ -24,6 +25,8 @@ var metricSurface = map[string]string{ "proxy_ecosystem_versions": "breakdown table", "proxy_cache_size_bytes": "Cache size tile", "proxy_cached_artifacts_total": "Cached artifacts tile", + "proxy_metadata_cache_size_bytes": "Metadata cache card", + "proxy_metadata_cache_entries": "Metadata cache card", // Request-path counters. "proxy_response_bytes_total": "Runtime: Served", @@ -31,36 +34,40 @@ var metricSurface = map[string]string{ "proxy_client_response_bytes_total": "Runtime: Request sources -- By client", // Registry-derived, shown in the Runtime card. - "proxy_requests_total": "Runtime: Requests + Responses by status", - "proxy_request_duration_seconds": "Runtime: Mean latency", - "proxy_active_requests": "Runtime: In flight", - "proxy_cache_hits_total": "Runtime: Cache lookups + hit rate", - "proxy_cache_misses_total": "Runtime: Cache lookups + hit rate", - "proxy_upstream_fetch_duration_seconds": "Runtime: Upstream fetches + mean fetch", - "proxy_upstream_errors_total": "Runtime: Upstream errors", - "proxy_storage_operation_duration_seconds": "Runtime: Storage operations", - "proxy_storage_errors_total": "Runtime: Storage errors", - "proxy_integrity_failures_total": "Runtime: Integrity failures", - "proxy_health_probe_failures_total": "Runtime: Health probe failures", - "proxy_circuit_breaker_state": "Runtime: Circuit breakers", - "proxy_circuit_breaker_trips_total": "Runtime: Circuit breaker trips", - "proxy_artifacts_evicted_total": "Runtime: Evicted artifacts", - "proxy_scan_duration_seconds": "Runtime: Pre-cache scanning -- Scans", - "proxy_scan_blocked_total": "Runtime: Pre-cache scanning -- Artifacts blocked", - "proxy_scan_errors_total": "Runtime: Pre-cache scanning -- Scan errors", + "proxy_requests_total": "Runtime: Requests + Responses by status", + "proxy_request_duration_seconds": "Runtime: Mean latency", + "proxy_active_requests": "Runtime: In flight", + "proxy_cache_hits_total": "Runtime: Artifact and metadata cache lookups + artifact hit rate", + "proxy_cache_misses_total": "Runtime: Artifact and metadata cache lookups + artifact hit rate", + "proxy_metadata_cache_served_bytes_total": "Runtime: Metadata cache lookups -- served from cache", + "proxy_upstream_fetch_duration_seconds": "Runtime: Upstream fetches + mean fetch", + "proxy_upstream_errors_total": "Runtime: Upstream errors", + "proxy_storage_operation_duration_seconds": "Runtime: Storage operations", + "proxy_storage_errors_total": "Runtime: Storage errors", + "proxy_integrity_failures_total": "Runtime: Integrity failures", + "proxy_health_probe_failures_total": "Runtime: Health probe failures", + "proxy_circuit_breaker_state": "Runtime: Circuit breakers", + "proxy_circuit_breaker_trips_total": "Runtime: Circuit breaker trips", + "proxy_artifacts_evicted_total": "Runtime: Evicted artifacts", + "proxy_metadata_evicted_total": "Runtime: Evicted metadata", + "proxy_metadata_expired_by_change_feed_total": "Runtime: Metadata changed upstream", + "proxy_scan_duration_seconds": "Runtime: Pre-cache scanning -- Scans", + "proxy_scan_blocked_total": "Runtime: Pre-cache scanning -- Artifacts blocked", + "proxy_scan_errors_total": "Runtime: Pre-cache scanning -- Scan errors", } // TestEveryMetricIsSurfaced fails when a metric is registered but has no home // on the analytics page. The page is meant to be a complete view of what // /metrics exposes, so a silently unsurfaced metric is a gap, not a detail. func TestEveryMetricIsSurfaced(t *testing.T) { - isolateRecentFailures(t) // Touch every metric family so it is present in the registry output, since // a vector with no observed label values gathers as nothing at all. metrics.RecordRequest("npm", 200, 0) metrics.RecordResponse("npm", "npm", 1) - metrics.RecordCacheHit("npm") - metrics.RecordCacheMiss("npm") + metrics.RecordArtifactCacheHit("npm") + metrics.RecordArtifactCacheMiss("npm") + metrics.RecordMetadataCacheHit("npm", 1) + metrics.RecordMetadataCacheMiss("npm") metrics.RecordUpstreamFetch("npm", 0) metrics.RecordUpstreamError("npm", "fetch_failed", metrics.FailureDetail{}) metrics.RecordStorageOperation("get", 0) @@ -73,15 +80,19 @@ func TestEveryMetricIsSurfaced(t *testing.T) { metrics.RecordScanError("npm", "clamav", "timeout", metrics.FailureDetail{}) metrics.UpdateCacheStats(1, 1) metrics.RecordArtifactEvicted("retention", "npm") + metrics.RecordMetadataEvicted("npm") + metrics.RecordMetadataExpiredByChangeFeed("npm", 1) metrics.UpdateEcosystemStats([]metrics.EcosystemStats{{Ecosystem: "npm", DownloadedBytes: 1}}) + metrics.UpdateMetadataCacheStats([]metrics.MetadataCacheStats{{Ecosystem: "npm", Entries: 1, Size: 1}}) - snap, err := metrics.Gather() + families, err := prometheus.DefaultGatherer.Gather() if err != nil { t.Fatalf("Gather: %v", err) } var registered []string - for _, name := range snap.Names() { + for _, family := range families { + name := family.GetName() if strings.HasPrefix(name, "proxy_") { registered = append(registered, name) } diff --git a/internal/server/analytics_failures_test.go b/internal/server/analytics_failures_test.go index 6f7856e..aa89cb5 100644 --- a/internal/server/analytics_failures_test.go +++ b/internal/server/analytics_failures_test.go @@ -9,15 +9,6 @@ import ( "github.com/prometheus/client_golang/prometheus" ) -// isolateRecentFailures empties the process-wide failure history for the -// test and again when it ends, so neither earlier tests nor repeated runs -// reach its assertions. -func isolateRecentFailures(t *testing.T) { - t.Helper() - metrics.ResetRecentFailures() - t.Cleanup(metrics.ResetRecentFailures) -} - func storageErrorSnapshot(t *testing.T, operation string) *metrics.Snapshot { t.Helper() reg := prometheus.NewRegistry() @@ -34,7 +25,6 @@ func storageErrorSnapshot(t *testing.T, operation string) *metrics.Snapshot { } func TestRuntimeViewAttachesRecentFailuresWhenEnabled(t *testing.T) { - isolateRecentFailures(t) const operation = "test-attach" metrics.RecordStorageError(operation, metrics.FailureDetail{ PURL: "pkg:npm/left-pad@1.0.0", Filename: "left-pad-1.0.0.tgz", Path: "npm/left-pad", Err: errors.New("disk full")}) @@ -44,8 +34,8 @@ func TestRuntimeViewAttachesRecentFailuresWhenEnabled(t *testing.T) { if !v.FailureDetailsOn { t.Error("FailureDetailsOn = false, want true") } - if len(v.StorageErrors) != 1 || len(v.StorageErrors[0].Recent) != 1 { - t.Fatalf("StorageErrors = %+v, want one row with one recent failure", v.StorageErrors) + if len(v.StorageErrors) != 1 || len(v.StorageErrors[0].Recent) == 0 { + t.Fatalf("StorageErrors = %+v, want one row with recent failures", v.StorageErrors) } got := v.StorageErrors[0].Recent[0] if got.PURL != "pkg:npm/left-pad@1.0.0" || got.Filename != "left-pad-1.0.0.tgz" || @@ -55,7 +45,6 @@ func TestRuntimeViewAttachesRecentFailuresWhenEnabled(t *testing.T) { } func TestRuntimeViewOmitsRecentFailuresWhenDisabled(t *testing.T) { - isolateRecentFailures(t) const operation = "test-omit" metrics.RecordStorageError(operation, metrics.FailureDetail{PURL: "pkg:npm/left-pad@1.0.0"}) @@ -72,7 +61,6 @@ func TestRuntimeViewOmitsRecentFailuresWhenDisabled(t *testing.T) { // Package names and upstream URLs say what the proxy's users depend on, so like // the caller table they are published only when asked for. func TestAnalyticsPageHidesFailureDetailsByDefault(t *testing.T) { - isolateRecentFailures(t) ts := newTestServer(t) defer ts.close() @@ -91,7 +79,6 @@ func TestAnalyticsPageHidesFailureDetailsByDefault(t *testing.T) { } func TestAnalyticsPageShowsFailureDetailsWhenEnabled(t *testing.T) { - isolateRecentFailures(t) ts := newTestServer(t) defer ts.close() diff --git a/internal/server/analytics_runtime.go b/internal/server/analytics_runtime.go index 8e5d0d1..103e33e 100644 --- a/internal/server/analytics_runtime.go +++ b/internal/server/analytics_runtime.go @@ -15,14 +15,15 @@ import ( type RuntimeView struct { Available bool - Requests string - ActiveRequests string - RequestMean string - StatusClasses []LabelledCount - CacheHits string - CacheMisses string - CacheHitRatio string - HasCacheTraffic bool + Requests string + ActiveRequests string + RequestMean string + StatusClasses []LabelledCount + // Artifact and metadata lookups are counted apart: they are separate + // caches. Only artifacts feed the database figures above. + ArtifactCache CacheLookups + MetadataCache CacheLookups + MetadataServed string UpstreamFetches string UpstreamFetchMean string @@ -33,6 +34,8 @@ type RuntimeView struct { IntegrityFailures []LabelledCount ProbeFailures []LabelledCount Evictions []LabelledCount + MetadataEvictions []LabelledCount + ChangeFeedExpired []LabelledCount Breakers []BreakerRow BreakerTrips []LabelledCount @@ -58,6 +61,28 @@ type RuntimeView struct { HasFailures bool } +// CacheLookups is one cache's hits and misses since the process started. +type CacheLookups struct { + Hits string + Misses string + HitRatio string + HasTraffic bool +} + +// cacheLookups reads one kind's share of the hit and miss counters. +func cacheLookups(hits, misses map[string]float64, kind string) CacheLookups { + h, m := hits[kind], misses[kind] + c := CacheLookups{ + Hits: formatCount(int64(h)), + Misses: formatCount(int64(m)), + HasTraffic: h+m > 0, + } + if c.HasTraffic { + c.HitRatio = strconv.FormatFloat(h/(h+m)*100, 'f', 1, 64) //nolint:mnd // percent + } + return c +} + // ClientRow is one client tool's share of requests and bytes. type ClientRow struct { Client string @@ -121,14 +146,11 @@ func runtimeView(snap *metrics.Snapshot, failureDetails bool) RuntimeView { v.RequestMean = formatDuration(snap.Mean("proxy_request_duration_seconds")) v.StatusClasses = statusClasses(snap) - hits := snap.Sum("proxy_cache_hits_total") - misses := snap.Sum("proxy_cache_misses_total") - v.CacheHits = formatCount(int64(hits)) - v.CacheMisses = formatCount(int64(misses)) - v.HasCacheTraffic = hits+misses > 0 - if v.HasCacheTraffic { - v.CacheHitRatio = strconv.FormatFloat(hits/(hits+misses)*100, 'f', 1, 64) //nolint:mnd // percent - } + hits := snap.SumBy("proxy_cache_hits_total", "kind") + misses := snap.SumBy("proxy_cache_misses_total", "kind") + v.ArtifactCache = cacheLookups(hits, misses, metrics.CacheKindArtifact) + v.MetadataCache = cacheLookups(hits, misses, metrics.CacheKindMetadata) + v.MetadataServed = formatSize(int64(snap.Sum("proxy_metadata_cache_served_bytes_total"))) v.UpstreamFetches = formatCount(int64(snap.Count("proxy_upstream_fetch_duration_seconds"))) v.UpstreamFetchMean = formatDuration(snap.Mean("proxy_upstream_fetch_duration_seconds")) @@ -139,6 +161,8 @@ func runtimeView(snap *metrics.Snapshot, failureDetails bool) RuntimeView { v.IntegrityFailures = failures("proxy_integrity_failures_total", "ecosystem") v.ProbeFailures = failures("proxy_health_probe_failures_total", "step") v.Evictions = countRows(snap, "proxy_artifacts_evicted_total", "reason", "ecosystem") + v.MetadataEvictions = countRows(snap, "proxy_metadata_evicted_total", "ecosystem") + v.ChangeFeedExpired = countRows(snap, "proxy_metadata_expired_by_change_feed_total", "ecosystem") v.Breakers = breakerRows(snap) v.BreakerTrips = failures("proxy_circuit_breaker_trips_total", "registry") diff --git a/internal/server/analytics_runtime_test.go b/internal/server/analytics_runtime_test.go index 5bff0f3..03bc236 100644 --- a/internal/server/analytics_runtime_test.go +++ b/internal/server/analytics_runtime_test.go @@ -40,9 +40,9 @@ func TestRuntimeViewShapesRegistry(t *testing.T) { scanErrors := prometheus.NewCounterVec( prometheus.CounterOpts{Name: "proxy_scan_errors_total", Help: "t"}, []string{"ecosystem", "scanner", "error_type"}) hits := prometheus.NewCounterVec( - prometheus.CounterOpts{Name: "proxy_cache_hits_total", Help: "t"}, []string{"ecosystem"}) + prometheus.CounterOpts{Name: "proxy_cache_hits_total", Help: "t"}, []string{"ecosystem", "kind"}) misses := prometheus.NewCounterVec( - prometheus.CounterOpts{Name: "proxy_cache_misses_total", Help: "t"}, []string{"ecosystem"}) + prometheus.CounterOpts{Name: "proxy_cache_misses_total", Help: "t"}, []string{"ecosystem", "kind"}) breaker := prometheus.NewGaugeVec( prometheus.GaugeOpts{Name: "proxy_circuit_breaker_state", Help: "t"}, []string{"registry"}) storage := prometheus.NewHistogramVec( @@ -53,8 +53,8 @@ func TestRuntimeViewShapesRegistry(t *testing.T) { requests.WithLabelValues("npm", "304").Add(5) requests.WithLabelValues("npm", "500").Add(5) scanErrors.WithLabelValues("npm", "clamav", "timeout").Add(3) - hits.WithLabelValues("npm").Add(80) - misses.WithLabelValues("npm").Add(20) + hits.WithLabelValues("npm", metrics.CacheKindArtifact).Add(80) + misses.WithLabelValues("npm", metrics.CacheKindArtifact).Add(20) breaker.WithLabelValues("registry.npmjs.org").Set(0) breaker.WithLabelValues("static.crates.io").Set(2) storage.WithLabelValues("get").Observe(0.002) @@ -71,8 +71,8 @@ func TestRuntimeViewShapesRegistry(t *testing.T) { if v.Requests != "100" { t.Errorf("Requests = %q, want %q", v.Requests, "100") } - if v.CacheHitRatio != "80.0" || !v.HasCacheTraffic { - t.Errorf("CacheHitRatio = %q (traffic=%v), want 80.0", v.CacheHitRatio, v.HasCacheTraffic) + if a := v.ArtifactCache; a.HitRatio != "80.0" || !a.HasTraffic { + t.Errorf("ArtifactCache = %+v, want an 80.0%% hit rate", a) } // Status codes collapse to classes; 5xx is flagged as a failure row. @@ -152,6 +152,42 @@ func TestRuntimeViewShowsEvictions(t *testing.T) { } } +func TestRuntimeViewShowsMetadataEvictions(t *testing.T) { + reg := prometheus.NewRegistry() + evicted := prometheus.NewCounterVec( + prometheus.CounterOpts{Name: "proxy_metadata_evicted_total", Help: "t"}, []string{"ecosystem"}) + reg.MustRegister(evicted) + evicted.WithLabelValues("golang").Add(3) + + snap, err := metrics.GatherFrom(reg) + if err != nil { + t.Fatalf("GatherFrom: %v", err) + } + v := runtimeView(snap, false) + + if len(v.MetadataEvictions) != 1 || v.MetadataEvictions[0].Label != "golang" || v.MetadataEvictions[0].Count != "3" { + t.Errorf("MetadataEvictions = %+v, want golang = 3", v.MetadataEvictions) + } +} + +func TestRuntimeViewShowsChangeFeedExpiries(t *testing.T) { + reg := prometheus.NewRegistry() + expired := prometheus.NewCounterVec( + prometheus.CounterOpts{Name: "proxy_metadata_expired_by_change_feed_total", Help: "t"}, []string{"ecosystem"}) + reg.MustRegister(expired) + expired.WithLabelValues("packagist").Add(2) + + snap, err := metrics.GatherFrom(reg) + if err != nil { + t.Fatalf("GatherFrom: %v", err) + } + v := runtimeView(snap, false) + + if len(v.ChangeFeedExpired) != 1 || v.ChangeFeedExpired[0].Label != "packagist" || v.ChangeFeedExpired[0].Count != "2" { + t.Errorf("ChangeFeedExpired = %+v, want packagist = 2", v.ChangeFeedExpired) + } +} + // A counter sitting at zero carries no information and would bury the rows // that do, so it is left out. func TestRuntimeViewDropsZeroCounters(t *testing.T) { @@ -178,6 +214,48 @@ func TestRuntimeViewDropsZeroCounters(t *testing.T) { } } +// Artifact and metadata lookups are separate caches, so the view reports each +// on its own rather than pooling them into one hit rate. +func TestRuntimeViewSplitsCacheKinds(t *testing.T) { + reg := prometheus.NewRegistry() + hits := prometheus.NewCounterVec( + prometheus.CounterOpts{Name: "proxy_cache_hits_total", Help: "t"}, []string{"ecosystem", "kind"}) + misses := prometheus.NewCounterVec( + prometheus.CounterOpts{Name: "proxy_cache_misses_total", Help: "t"}, []string{"ecosystem", "kind"}) + served := prometheus.NewCounterVec( + prometheus.CounterOpts{Name: "proxy_metadata_cache_served_bytes_total", Help: "t"}, []string{"ecosystem"}) + reg.MustRegister(hits, misses, served) + + hits.WithLabelValues("npm", metrics.CacheKindArtifact).Add(80) + misses.WithLabelValues("npm", metrics.CacheKindArtifact).Add(20) + hits.WithLabelValues("pypi", metrics.CacheKindMetadata).Add(20) + hits.WithLabelValues("npm", metrics.CacheKindMetadata).Add(10) + misses.WithLabelValues("pypi", metrics.CacheKindMetadata).Add(10) + served.WithLabelValues("pypi").Add(2048) + + snap, err := metrics.GatherFrom(reg) + if err != nil { + t.Fatalf("GatherFrom: %v", err) + } + v := runtimeView(snap, false) + + want := map[string]struct { + got CacheLookups + want CacheLookups + }{ + "artifact": {v.ArtifactCache, CacheLookups{Hits: "80", Misses: "20", HitRatio: "80.0", HasTraffic: true}}, + "metadata": {v.MetadataCache, CacheLookups{Hits: "30", Misses: "10", HitRatio: "75.0", HasTraffic: true}}, + } + for kind, c := range want { + if c.got != c.want { + t.Errorf("%s lookups = %+v, want %+v", kind, c.got, c.want) + } + } + if v.MetadataServed != "2.0 KB" { + t.Errorf("MetadataServed = %q, want %q", v.MetadataServed, "2.0 KB") + } +} + // An empty registry must still render, reporting nothing rather than dividing // by zero or showing a hit rate of NaN. func TestRuntimeViewEmptyRegistry(t *testing.T) { @@ -190,11 +268,13 @@ func TestRuntimeViewEmptyRegistry(t *testing.T) { if !v.Available { t.Error("an empty registry is still a valid snapshot") } - if v.HasCacheTraffic { - t.Error("no traffic recorded, so HasCacheTraffic must be false") - } - if v.CacheHitRatio != "" { - t.Errorf("CacheHitRatio = %q, want empty when nothing was recorded", v.CacheHitRatio) + for name, c := range map[string]CacheLookups{"artifact": v.ArtifactCache, "metadata": v.MetadataCache} { + if c.HasTraffic { + t.Errorf("%s: no traffic recorded, so HasTraffic must be false", name) + } + if c.HitRatio != "" { + t.Errorf("%s: HitRatio = %q, want empty when nothing was recorded", name, c.HitRatio) + } } if v.Requests != "0" { t.Errorf("Requests = %q, want %q", v.Requests, "0") diff --git a/internal/server/analytics_test.go b/internal/server/analytics_test.go index 3ce5289..540408b 100644 --- a/internal/server/analytics_test.go +++ b/internal/server/analytics_test.go @@ -1,6 +1,7 @@ package server import ( + "database/sql" "net/http/httptest" "strings" "testing" @@ -275,3 +276,95 @@ func TestEcosystemMetricsMapping(t *testing.T) { t.Errorf("fields did not map across: %+v", m) } } + +// The metadata cache is stored apart from artifacts, so the page reports it in +// its own card rather than leaving it out of every figure. +func TestAnalyticsPageShowsMetadataCache(t *testing.T) { + ts := newTestServer(t) + defer ts.close() + ts.server.cfg.CacheMetadata = true + + for _, e := range []database.MetadataCacheEntry{ + {Ecosystem: "pypi", Name: "requests", StoragePath: "_metadata/pypi/requests", Size: sql.NullInt64{Int64: 3 << 10, Valid: true}}, + {Ecosystem: "pypi", Name: "urllib3", StoragePath: "_metadata/pypi/urllib3", Size: sql.NullInt64{Int64: 1 << 10, Valid: true}}, + } { + if err := ts.db.UpsertMetadataCache(&e); err != nil { + t.Fatalf("UpsertMetadataCache: %v", err) + } + } + + body := ts.getOK(t, "/ui/analytics") + for _, want := range []string{"Metadata cache", "Cached documents", "4.0 KB", "100.0%"} { + if !strings.Contains(body, want) { + t.Errorf("rendered page missing %q", want) + } + } + if strings.Contains(body, "Metadata caching is off") { + t.Error("the off-state note rendered with cache_metadata on") + } +} + +func TestAnalyticsPageNotesMetadataCachingOff(t *testing.T) { + ts := newTestServer(t) + defer ts.close() + + body := ts.getOK(t, "/ui/analytics") + for _, want := range []string{"Metadata cache", "Metadata caching is off", "No metadata cached yet"} { + if !strings.Contains(body, want) { + t.Errorf("rendered page missing %q", want) + } + } +} + +func TestMetadataCacheView(t *testing.T) { + v := metadataCacheView([]database.MetadataCacheStats{ + {Ecosystem: "npm", Entries: 3, Size: 3000}, + {Ecosystem: "pypi", Entries: 1, Size: 1000}, + }, true) + + if !v.Enabled || v.Entries != "4" || v.Size != "3.9 KB" { + t.Errorf("totals = %+v, want enabled, 4 entries, 3.9 KB", v) + } + if len(v.Rows) != 2 || v.Rows[0].SharePct != "75.0" || v.Rows[1].SharePct != "25.0" { + t.Errorf("rows = %+v, want npm 75.0%% then pypi 25.0%%", v.Rows) + } + + empty := metadataCacheView(nil, false) + if empty.Enabled || len(empty.Rows) != 0 || empty.Entries != "0" || empty.Size != "0 B" { + t.Errorf("empty view = %+v", empty) + } +} + +// The page reads the metadata card from the snapshot the gauges publish, so a +// page load issues no query of its own and the two always agree. +func TestAnalyticsPageMetadataCardUsesSnapshot(t *testing.T) { + ts := newTestServer(t) + defer ts.close() + ts.server.cfg.CacheMetadata = true + + seed := func(name string, size int64) { + t.Helper() + if err := ts.db.UpsertMetadataCache(&database.MetadataCacheEntry{ + Ecosystem: "pypi", Name: name, StoragePath: "_metadata/pypi/" + name, + Size: sql.NullInt64{Int64: size, Valid: true}, + }); err != nil { + t.Fatalf("UpsertMetadataCache: %v", err) + } + } + + seed("requests", 1<<10) + ts.server.updateMetadataCacheStats() + if !strings.Contains(ts.getOK(t, "/ui/analytics"), "1.0 KB") { + t.Fatal("page did not show the snapshot the metrics tick read") + } + + seed("urllib3", 2<<10) + if body := ts.getOK(t, "/ui/analytics"); !strings.Contains(body, "1.0 KB") || strings.Contains(body, "3.0 KB") { + t.Error("a page load re-queried the database instead of serving the snapshot") + } + + ts.server.updateMetadataCacheStats() + if !strings.Contains(ts.getOK(t, "/ui/analytics"), "3.0 KB") { + t.Error("page did not pick up the refreshed snapshot") + } +} diff --git a/internal/server/api.go b/internal/server/api.go index 992d736..07080aa 100644 --- a/internal/server/api.go +++ b/internal/server/api.go @@ -1,9 +1,12 @@ package server import ( + "context" "encoding/json" + "errors" "net/http" "strings" + "time" shared "github.com/git-pkgs/enrichment" "github.com/git-pkgs/proxy/internal/database" @@ -20,9 +23,20 @@ const ( // APIHandler provides REST endpoints for package enrichment data. type APIHandler struct { - enrichment *enrichment.Service + enrichment enricher ecosystems *shared.EcosystemsClient db DBSearcher + // cooldown is nil with cooldown off. + cooldown *cooldownView +} + +// enricher is the part of enrichment.Service the API uses. +type enricher interface { + EnrichPackage(ctx context.Context, ecosystem, name string) (*enrichment.PackageInfo, error) + EnrichFull(ctx context.Context, ecosystem, name, version string) (*enrichment.EnrichmentResult, error) + CheckVulnerabilities(ctx context.Context, ecosystem, name, version string) ([]enrichment.VulnInfo, error) + GetLatestVersion(ctx context.Context, ecosystem, name string) (string, error) + BulkEnrichPackages(ctx context.Context, packages []struct{ Ecosystem, Name string }) map[string]*enrichment.PackageInfo } // DBSearcher defines the interface for database search operations. @@ -46,6 +60,12 @@ func NewAPIHandler(svc *enrichment.Service, db DBSearcher) *APIHandler { return h } +func (s *Server) newAPIHandler(svc *enrichment.Service) *APIHandler { + h := NewAPIHandler(svc, s.db) + h.cooldown = s.cooldown + return h +} + // PackageResponse contains enriched package metadata. type PackageResponse struct { Ecosystem string `json:"ecosystem"` @@ -57,6 +77,9 @@ type PackageResponse struct { Homepage string `json:"homepage,omitempty"` Repository string `json:"repository,omitempty"` RegistryURL string `json:"registry_url,omitempty"` + // Cooldown is the cooldown that applies to the package, in the + // configuration's syntax ("3d", "0"). + Cooldown string `json:"cooldown,omitempty"` } // VersionResponse contains enriched version metadata. @@ -66,11 +89,15 @@ type VersionResponse struct { Version string `json:"version"` License string `json:"license,omitempty"` PublishedAt string `json:"published_at,omitempty"` + // AvailableAt is when a version held back by cooldown leaves it. + AvailableAt string `json:"available_at,omitempty"` Integrity string `json:"integrity,omitempty"` Yanked bool `json:"yanked"` IsOutdated bool `json:"is_outdated"` } +const apiTimeFormat = "2006-01-02T15:04:05Z" + // VulnResponse contains vulnerability information. type VulnResponse struct { ID string `json:"id"` @@ -174,11 +201,12 @@ func (h *APIHandler) HandlePackagePath(w http.ResponseWriter, r *http.Request) { Name: info.Name, LatestVersion: info.LatestVersion, License: info.License, - LicenseCategory: string(h.enrichment.CategorizeLicense(info.License)), + LicenseCategory: string(shared.CategorizeLicense(info.License)), Description: info.Description, Homepage: info.Homepage, Repository: info.Repository, RegistryURL: info.RegistryURL, + Cooldown: h.packageCooldown(ecosystem, fullName), } writeJSON(w, resp) return @@ -207,11 +235,12 @@ func (h *APIHandler) getPackage(w http.ResponseWriter, r *http.Request, ecosyste Name: info.Name, LatestVersion: info.LatestVersion, License: info.License, - LicenseCategory: string(h.enrichment.CategorizeLicense(info.License)), + LicenseCategory: string(shared.CategorizeLicense(info.License)), Description: info.Description, Homepage: info.Homepage, Repository: info.Repository, RegistryURL: info.RegistryURL, + Cooldown: h.packageCooldown(ecosystem, name), } writeJSON(w, resp) @@ -219,6 +248,10 @@ func (h *APIHandler) getPackage(w http.ResponseWriter, r *http.Request, ecosyste func (h *APIHandler) getVersion(w http.ResponseWriter, r *http.Request, ecosystem, name, version string) { result, err := h.enrichment.EnrichFull(r.Context(), ecosystem, name, version) + if errors.Is(err, shared.ErrUnsupportedVulnerabilityIdentity) { + badRequest(w, "package identity is not supported for vulnerability lookups") + return + } if err != nil { writeError(w, http.StatusBadGateway, ErrCodeUpstream, "failed to enrich version") return @@ -235,11 +268,12 @@ func (h *APIHandler) getVersion(w http.ResponseWriter, r *http.Request, ecosyste Name: result.Package.Name, LatestVersion: result.Package.LatestVersion, License: result.Package.License, - LicenseCategory: string(h.enrichment.CategorizeLicense(result.Package.License)), + LicenseCategory: string(shared.CategorizeLicense(result.Package.License)), Description: result.Package.Description, Homepage: result.Package.Homepage, Repository: result.Package.Repository, RegistryURL: result.Package.RegistryURL, + Cooldown: h.packageCooldown(ecosystem, name), } } @@ -253,8 +287,11 @@ func (h *APIHandler) getVersion(w http.ResponseWriter, r *http.Request, ecosyste Yanked: result.Version.Yanked, IsOutdated: result.IsOutdated, } - if !result.Version.PublishedAt.IsZero() { - resp.Version.PublishedAt = result.Version.PublishedAt.Format("2006-01-02T15:04:05Z") + if published := result.Version.PublishedAt; !published.IsZero() { + resp.Version.PublishedAt = published.UTC().Format(apiTimeFormat) + if at := h.cooldown.availableAt(ecosystem, name, published, time.Now()); !at.IsZero() { + resp.Version.AvailableAt = at.UTC().Format(apiTimeFormat) + } } } @@ -272,6 +309,19 @@ func (h *APIHandler) getVersion(w http.ResponseWriter, r *http.Request, ecosyste writeJSON(w, resp) } +// packageCooldown returns the cooldown for a package in the configuration's +// syntax, or "" with cooldown off or not applied to the ecosystem. +func (h *APIHandler) packageCooldown(ecosystem, name string) string { + c := h.cooldown.forPackage(ecosystem, name) + switch { + case c == nil: + return "" + case c.Duration == cooldownOff: + return "0" + } + return c.Duration +} + // HandleVulnsPath dispatches /api/vulns/{ecosystem}/* to the vulns handler. // Supports both {name} and {name}/{version} paths with namespaced package names. func (h *APIHandler) HandleVulnsPath(w http.ResponseWriter, r *http.Request) { @@ -303,6 +353,10 @@ func (h *APIHandler) HandleVulnsPath(w http.ResponseWriter, r *http.Request) { } vulns, err := h.enrichment.CheckVulnerabilities(r.Context(), ecosystem, name, version) + if errors.Is(err, shared.ErrUnsupportedVulnerabilityIdentity) { + badRequest(w, "package identity is not supported for vulnerability lookups") + return + } if err != nil { writeError(w, http.StatusBadGateway, ErrCodeUpstream, "failed to check vulnerabilities") return @@ -366,7 +420,7 @@ func (h *APIHandler) HandleOutdated(w http.ResponseWriter, r *http.Request) { latest, err := h.enrichment.GetLatestVersion(r.Context(), pkg.Ecosystem, pkg.Name) if err == nil && latest != "" { result.LatestVersion = latest - result.IsOutdated = h.enrichment.IsOutdated(pkg.Version, latest) + result.IsOutdated = shared.IsOutdated(pkg.Version, latest) } resp.Results = append(resp.Results, result) @@ -413,7 +467,7 @@ func (h *APIHandler) HandleBulkLookup(w http.ResponseWriter, r *http.Request) { Name: info.Name, LatestVersion: info.LatestVersion, License: info.License, - LicenseCategory: string(h.enrichment.CategorizeLicense(info.License)), + LicenseCategory: string(shared.CategorizeLicense(info.License)), Description: info.Description, Homepage: info.Homepage, Repository: info.Repository, @@ -444,7 +498,7 @@ func (h *APIHandler) HandleBulkLookup(w http.ResponseWriter, r *http.Request) { Name: info.Name, LatestVersion: info.LatestVersion, License: info.License, - LicenseCategory: string(h.enrichment.CategorizeLicense(info.License)), + LicenseCategory: string(shared.CategorizeLicense(info.License)), Description: info.Description, Homepage: info.Homepage, Repository: info.Repository, @@ -635,9 +689,7 @@ func (h *APIHandler) HandlePackagesList(w http.ResponseWriter, r *http.Request) licenseCategory := licenseCategoryUnknown if pkg.License.Valid { license = pkg.License.String - if h.enrichment != nil { - licenseCategory = string(h.enrichment.CategorizeLicense(license)) - } + licenseCategory = string(shared.CategorizeLicense(license)) } cachedAt := "" if pkg.CachedAt.Valid { diff --git a/internal/server/api_cooldown_test.go b/internal/server/api_cooldown_test.go new file mode 100644 index 0000000..4e3e3c7 --- /dev/null +++ b/internal/server/api_cooldown_test.go @@ -0,0 +1,76 @@ +package server + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "testing" + "time" + + "github.com/git-pkgs/proxy/internal/config" + "github.com/git-pkgs/proxy/internal/enrichment" + "github.com/go-chi/chi/v5" +) + +func TestAPIVersionAvailableAt(t *testing.T) { + now := time.Now().UTC().Truncate(time.Second) + recent, old := now.Add(-time.Hour), now.Add(-96*time.Hour) + h := &APIHandler{ + enrichment: fakeEnricher{published: map[string]time.Time{"1.0.0": old, "2.0.0": recent}}, + cooldown: testCooldownView(t, config.CooldownConfig{Default: "3d"}), + } + r := chi.NewRouter() + r.Get("/api/package/{ecosystem}/*", h.HandlePackagePath) + + tests := []struct{ version, availableAt string }{ + {"2.0.0", recent.Add(72 * time.Hour).Format(apiTimeFormat)}, + {"1.0.0", ""}, + } + for _, tt := range tests { + t.Run(tt.version, func(t *testing.T) { + w := httptest.NewRecorder() + r.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/api/package/npm/leftpad/"+tt.version, nil)) + if w.Code != http.StatusOK { + t.Fatalf("status = %d, body = %s", w.Code, w.Body) + } + var resp EnrichmentResponse + if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil { + t.Fatal(err) + } + if resp.Package == nil || resp.Package.Cooldown != "3d" { + t.Errorf("package = %+v, want cooldown 3d", resp.Package) + } + if resp.Version == nil || resp.Version.AvailableAt != tt.availableAt { + t.Errorf("version = %+v, want available_at %q", resp.Version, tt.availableAt) + } + }) + } +} + +// fakeEnricher answers version lookups with the given publish times and +// knows no packages by name alone. +type fakeEnricher struct{ published map[string]time.Time } + +func (fakeEnricher) EnrichPackage(context.Context, string, string) (*enrichment.PackageInfo, error) { + return nil, nil +} + +func (f fakeEnricher) EnrichFull(_ context.Context, ecosystem, name, version string) (*enrichment.EnrichmentResult, error) { + return &enrichment.EnrichmentResult{ + Package: &enrichment.PackageInfo{Ecosystem: ecosystem, Name: name}, + Version: &enrichment.VersionInfo{Number: version, PublishedAt: f.published[version]}, + }, nil +} + +func (fakeEnricher) CheckVulnerabilities(context.Context, string, string, string) ([]enrichment.VulnInfo, error) { + return nil, nil +} + +func (fakeEnricher) GetLatestVersion(context.Context, string, string) (string, error) { + return "", nil +} + +func (fakeEnricher) BulkEnrichPackages(context.Context, []struct{ Ecosystem, Name string }) map[string]*enrichment.PackageInfo { + return nil +} diff --git a/internal/server/apk_snapshots.go b/internal/server/apk_snapshots.go new file mode 100644 index 0000000..ee8e3c9 --- /dev/null +++ b/internal/server/apk_snapshots.go @@ -0,0 +1,48 @@ +package server + +import ( + "context" + "time" +) + +// apkSnapshotPruneInterval is how often snapshots kept past +// upstream.apk_snapshots are deleted. +const apkSnapshotPruneInterval = time.Hour + +// startAPKSnapshotPruning deletes APK index snapshots that were replaced more +// than upstream.apk_snapshots ago, once at startup and then every hour. Their +// blobs go through the pending-delete queue like evicted cache entries. +func (s *Server) startAPKSnapshotPruning(ctx context.Context) { + keep := s.cfg.ParseAPKSnapshots() + if keep <= 0 { + return + } + if !s.cfg.CacheMetadata { + s.logger.Warn("upstream.apk_snapshots needs cache_metadata, snapshots disabled") + return + } + + ticker := time.NewTicker(apkSnapshotPruneInterval) + defer ticker.Stop() + for { + s.pruneAPKSnapshots(ctx, keep, time.Now()) + select { + case <-ctx.Done(): + return + case <-ticker.C: + } + } +} + +func (s *Server) pruneAPKSnapshots(ctx context.Context, keep time.Duration, now time.Time) { + s.runExclusive(ctx, "apk-snapshot-prune", func() { + n, err := s.db.PruneMetadataSnapshots("alpine", now.Add(-keep)) + if err != nil { + s.logger.Warn("apk snapshots: prune failed", "error", err) + return + } + if n > 0 { + s.logger.Info("apk snapshots: pruned", "deleted", n) + } + }) +} diff --git a/internal/server/apk_snapshots_test.go b/internal/server/apk_snapshots_test.go new file mode 100644 index 0000000..191e073 --- /dev/null +++ b/internal/server/apk_snapshots_test.go @@ -0,0 +1,63 @@ +package server + +import ( + "context" + "io" + "log/slog" + "net/http" + "net/http/httptest" + "testing" + "time" + + "github.com/git-pkgs/proxy/internal/config" + "github.com/git-pkgs/proxy/internal/database" + "github.com/git-pkgs/proxy/internal/handler" + "github.com/git-pkgs/proxy/internal/storage" + "github.com/git-pkgs/registries/fetch" + "github.com/go-chi/chi/v5" +) + +// TestAPKSnapshotsConfigured checks that upstream.apk_snapshots enables the +// dated APK paths, with the digest the file storage records for the cached +// index matching the copy kept as a snapshot. +func TestAPKSnapshotsConfigured(t *testing.T) { + const index = "signed index" + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + _, _ = io.WriteString(w, index) + })) + defer upstream.Close() + + db, err := database.Create(t.TempDir() + "/test.db") + if err != nil { + t.Fatalf("creating database: %v", err) + } + t.Cleanup(func() { _ = db.Close() }) + store, err := storage.OpenBucket(context.Background(), "file://"+t.TempDir()) + if err != nil { + t.Fatalf("opening storage: %v", err) + } + logger := slog.New(slog.NewTextHandler(io.Discard, nil)) + proxy := handler.NewProxy(db, store, fetch.NewFetcher(), fetch.NewResolver(), logger) + proxy.HTTPClient = upstream.Client() + proxy.CacheMetadata = true + + cfg := config.Default() + cfg.BaseURL = "http://proxy.test" + cfg.Upstream.APK = map[string]string{"alpine": upstream.URL} + cfg.Upstream.APKSnapshots = "30d" + s := &Server{cfg: cfg, logger: logger} + r := chi.NewRouter() + s.mountProtocolHandlers(r, proxy) + + today := time.Now().UTC().Format("2006-01-02") + for _, target := range []string{ + "/apk/alpine/v3.22/main/x86_64/APKINDEX.tar.gz", + "/apk/alpine@" + today + "/v3.22/main/x86_64/APKINDEX.tar.gz", + } { + w := httptest.NewRecorder() + r.ServeHTTP(w, httptest.NewRequest(http.MethodGet, target, nil)) + if w.Code != http.StatusOK || w.Body.String() != index { + t.Fatalf("%s: status = %d, body = %q, want 200 %q", target, w.Code, w.Body.String(), index) + } + } +} diff --git a/internal/server/breakers_test.go b/internal/server/breakers_test.go index bb5166e..6cfb511 100644 --- a/internal/server/breakers_test.go +++ b/internal/server/breakers_test.go @@ -14,6 +14,7 @@ import ( upstreamhttp "github.com/git-pkgs/proxy/internal/httpclient" "github.com/git-pkgs/proxy/internal/metrics" + registryclient "github.com/git-pkgs/registries/client" "github.com/git-pkgs/registries/fetch" "github.com/prometheus/client_golang/prometheus" dto "github.com/prometheus/client_model/go" @@ -352,7 +353,7 @@ func TestHealthEndpoint_ReportsUpstreamHolds(t *testing.T) { ts := newTestServer(t) defer ts.close() - gate := upstreamhttp.NewRateLimitGate(roundTripperFunc(func(req *http.Request) (*http.Response, error) { + gate := registryclient.NewRateLimitGate(roundTripperFunc(func(req *http.Request) (*http.Response, error) { return &http.Response{ StatusCode: http.StatusTooManyRequests, Header: http.Header{"Retry-After": []string{"600"}}, @@ -364,7 +365,7 @@ func TestHealthEndpoint_ReportsUpstreamHolds(t *testing.T) { if resp, err := gate.RoundTrip(req); err == nil { _ = resp.Body.Close() } - ts.server.rateLimits = gate + ts.server.rateLimits = upstreamhttp.NewSharedRateLimitGate(gate, nil, nil) w := httptest.NewRecorder() ts.handler.ServeHTTP(w, httptest.NewRequest("GET", "/health", nil)) diff --git a/internal/server/browse.go b/internal/server/browse.go index 43cb855..1184f2e 100644 --- a/internal/server/browse.go +++ b/internal/server/browse.go @@ -6,6 +6,7 @@ import ( "errors" "fmt" "io" + "io/fs" "net/http" "path" "strings" @@ -98,20 +99,14 @@ func detectSingleRootDir(reader archives.Reader) string { return "" } - var root rootDetector - for _, f := range files { - if !root.add(f.Path) { - break - } - } - return root.prefix() + return archives.CommonRoot(files) } // openArchive opens a cached artifact as a random-access archive reader, // auto-detecting and stripping a single top-level directory prefix (like // GitHub zipballs). For npm, the hardcoded "package/" prefix takes precedence. // The whole artifact is buffered, so only the version diff uses it; listing -// and file reads stream through browseArchive instead. +// and file reads use the streaming browser instead. func openArchive(filename string, content io.Reader, ecosystem string) (archives.Reader, error) { //nolint:ireturn // wraps multiple archive implementations data, err := readBrowseInput(content, maxBrowseArchiveSize) if err != nil { @@ -142,7 +137,7 @@ func (s *Server) browseLimitsOrDefault() archives.StreamOptions { // openBrowseArchive prepares a cached artifact for streaming. content is the // already open storage reader; later passes reopen the artifact. -func (s *Server) openBrowseArchive(r *http.Request, artifact *database.Artifact, content io.Reader, ecosystem string) (*browseArchive, error) { +func (s *Server) openBrowseArchive(r *http.Request, artifact *database.Artifact, content io.Reader, ecosystem string) (*archives.Browser, error) { storagePath := artifact.StoragePath.String reopen := func() (io.ReadCloser, error) { return s.storage.Open(r.Context(), storagePath) @@ -398,13 +393,9 @@ func (s *Server) browseFile(w http.ResponseWriter, r *http.Request, ecosystem, n // Find the file and stream it straight from the archive fileReader, err := archive.Extract(filePath) switch { - case errors.Is(err, errBrowseNotFound): + case errors.Is(err, fs.ErrNotExist), errors.Is(err, archives.ErrIsDir): notFound(w, "file not found") return - case errors.Is(err, errBrowseIsDir): - s.logger.Error("failed to extract file", "error", err, "path", filePath) - internalError(w, "failed to extract file") - return case err != nil: s.browseArchiveError(w, err, cachedArtifact.Filename) return @@ -433,7 +424,7 @@ func (s *Server) writeBrowseFile(w http.ResponseWriter, file io.Reader, filePath contentType = detectContentTypeFromPrefix(head[:min(len(head), browseSniffSize)]) } w.Header().Set("Content-Type", contentType) - w.Header().Set("Content-Security-Policy", "sandbox") + w.Header().Set("Content-Security-Policy", "sandbox; "+frameAncestorsNone) w.Header().Set("X-Content-Type-Options", "nosniff") _, filename := path.Split(filePath) diff --git a/internal/server/browse_archive.go b/internal/server/browse_archive.go index 4af6afe..4545ed7 100644 --- a/internal/server/browse_archive.go +++ b/internal/server/browse_archive.go @@ -1,15 +1,11 @@ package server import ( - "bufio" "errors" "fmt" "io" - "path" - "strings" "github.com/git-pkgs/archives" - "github.com/git-pkgs/magic" ) // Limits applied when listing or reading a single file. Bodies are streamed @@ -31,14 +27,7 @@ var defaultBrowseLimits = archives.StreamOptions{ MaxEntries: maxBrowseEntries, } -var ( - errArtifactTooLarge = errors.New("artifact too large for browsing") - errBrowseNotFound = errors.New("file not found") - errBrowseIsDir = errors.New("path is a directory") - - // errStopWalk ends a walk early without reporting an error. - errStopWalk = errors.New("stop walk") -) +var errArtifactTooLarge = errors.New("artifact too large for browsing") // isBrowseLimitError reports whether err comes from one of the browse size or // entry-count limits rather than a malformed archive. @@ -50,44 +39,6 @@ func isBrowseLimitError(err error) bool { errors.Is(err, archives.ErrEntryLimit) } -// browseArchive reads a cached artifact sequentially for the browse endpoints -// without holding expanded file bodies in memory. TAR based formats stream from -// storage, reopening it when a second pass is needed. ZIP and conda need random -// access, so their input is read once and shared by every pass. -type browseArchive struct { - filename string - ecosystem string - limits archives.StreamOptions - reopen func() (io.ReadCloser, error) - - // first is the caller's reader, used for the first pass only. - first io.Reader - // data holds buffered ZIP or conda input. - data []byte -} - -// newBrowseArchive prepares content for streaming. The caller keeps ownership -// of content; reopen supplies a fresh reader for any later pass. -func newBrowseArchive(filename, ecosystem string, content io.Reader, reopen func() (io.ReadCloser, error), limits archives.StreamOptions) (*browseArchive, error) { - buffered := bufio.NewReaderSize(content, browseSniffSize) - sniff, err := buffered.Peek(browseSniffSize) - if err != nil && err != io.EOF { - return nil, fmt.Errorf("reading artifact: %w", err) - } - - a := &browseArchive{filename: filename, ecosystem: ecosystem, limits: limits, reopen: reopen} - if !needsRandomAccess(filename, sniff) { - a.first = buffered - return a, nil - } - - a.data, err = readBrowseInput(buffered, limits.MaxInputBytes) - if err != nil { - return nil, err - } - return a, nil -} - // readBrowseInput reads all of r, failing once it exceeds limit bytes. func readBrowseInput(r io.Reader, limit int64) ([]byte, error) { data, err := io.ReadAll(io.LimitReader(r, limit+1)) @@ -100,306 +51,10 @@ func readBrowseInput(r io.Reader, limit int64) ([]byte, error) { return data, nil } -// needsRandomAccess reports whether the archives library buffers this format -// when streaming it, following the library's own detection order: a known -// extension first, then the content's leading bytes. -func needsRandomAccess(filename string, sniff []byte) bool { - name := strings.ToLower(filename) - for _, suffix := range []string{".tar.gz", ".tar.bz2", ".tar.xz", ".tar.zst"} { - if strings.HasSuffix(name, suffix) { - return false - } +func newBrowseArchive(filename, ecosystem string, content io.Reader, reopen func() (io.ReadCloser, error), limits archives.StreamOptions) (*archives.Browser, error) { + options := archives.BrowseOptions{Limits: limits, DetectRoot: true} + if ecosystem == "npm" { + options.StripPrefix = npmPackagePrefix } - switch path.Ext(name) { - case ".zip", ".jar", ".whl", ".nupkg", ".egg", ".vsix", ".conda": - return true - case ".tar", ".tgz", ".crate", ".gem": - return false - } - return magic.DetectPrefix(sniff).Format == "zip" -} - -// openStream starts a pass over the archive. The returned function releases -// the stream and any reader opened for it. -func (a *browseArchive) openStream() (*archives.Stream, func(), error) { - if a.data != nil { - stream, err := archives.OpenStreamBytes(a.filename, a.data, a.limits) - if err != nil { - return nil, nil, err - } - return stream, func() { _ = stream.Close() }, nil - } - - if a.first != nil { - content := a.first - a.first = nil - stream, err := archives.OpenStream(a.filename, content, a.limits) - if err != nil { - return nil, nil, err - } - return stream, func() { _ = stream.Close() }, nil - } - - content, err := a.reopen() - if err != nil { - return nil, nil, fmt.Errorf("reopening artifact: %w", err) - } - stream, err := archives.OpenStream(a.filename, content, a.limits) - if err != nil { - _ = content.Close() - return nil, nil, err - } - return stream, func() { - _ = stream.Close() - _ = content.Close() - }, nil -} - -// walk calls fn for each entry in archive order until fn returns an error or -// the archive ends. fn may read the entry body from the stream. -func (a *browseArchive) walk(fn func(entry *archives.StreamEntry) error) error { - stream, release, err := a.openStream() - if err != nil { - return err - } - defer release() - - for { - entry, err := stream.Next() - if err == io.EOF { - return nil - } - if err != nil { - return err - } - if err := fn(entry); err != nil { - if errors.Is(err, errStopWalk) { - return nil - } - return err - } - } -} - -// prefix returns the directory stripped from every path: npm's "package/", or -// a single top-level directory shared by all entries (like GitHub zipballs). -// For other ecosystems this costs one pass, which stops early once two -// top-level names differ. -func (a *browseArchive) prefix() (string, error) { - if a.ecosystem == "npm" { - return npmPackagePrefix, nil - } - - var root rootDetector - err := a.walk(func(entry *archives.StreamEntry) error { - if !root.add(entry.Path) { - return errStopWalk - } - return nil - }) - if err != nil { - return "", err - } - return root.prefix(), nil -} - -// ListDir returns the entries directly inside dirPath, after prefix stripping, -// in a single pass that keeps only entry metadata. -func (a *browseArchive) ListDir(dirPath string) ([]archives.FileInfo, error) { - var entries []archives.FileInfo - var root rootDetector - err := a.walk(func(entry *archives.StreamEntry) error { - entries = append(entries, entry.FileInfo) - root.add(entry.Path) - return nil - }) - if err != nil { - return nil, err - } - - prefix := npmPackagePrefix - if a.ecosystem != "npm" { - prefix = root.prefix() - } - return listBrowseDir(entries, prefix, dirPath), nil -} - -// Extract returns the body of the first entry at filePath, streamed from the -// archive. The caller must close the returned reader. -func (a *browseArchive) Extract(filePath string) (io.ReadCloser, error) { - prefix, err := a.prefix() - if err != nil { - return nil, err - } - target := prefix + filePath - - stream, release, err := a.openStream() - if err != nil { - return nil, err - } - for { - entry, err := stream.Next() - if err == io.EOF { - release() - return nil, fmt.Errorf("%w: %s", errBrowseNotFound, filePath) - } - if err != nil { - release() - return nil, err - } - if entry.Path != target { - continue - } - if entry.IsDir { - release() - return nil, fmt.Errorf("%w: %s", errBrowseIsDir, filePath) - } - return &streamedFile{Reader: stream, release: release}, nil - } -} - -// streamedFile is an entry body that releases its archive stream on Close. -type streamedFile struct { - io.Reader - release func() -} - -func (f *streamedFile) Close() error { - if f.release != nil { - f.release() - f.release = nil - } - return nil -} - -// rootDetector tracks whether every path seen so far lives under one -// top-level directory. -type rootDetector struct { - root string - mixed bool - seen bool -} - -// add records p and reports whether a single root is still possible. -func (d *rootDetector) add(p string) bool { - if d.mixed { - return false - } - d.seen = true - dir, _, _ := strings.Cut(p, "/") - if d.root == "" { - d.root = dir - } else if dir != d.root { - d.mixed = true - } - return !d.mixed -} - -// prefix returns the shared root with a trailing slash, or "" if paths have -// more than one root or none were seen. -func (d *rootDetector) prefix() string { - if d.mixed || !d.seen || d.root == "" { - return "" - } - return d.root + "/" -} - -// listBrowseDir lists dirPath from entry metadata the same way a reader from -// archives.OpenWithPrefix does: the prefix is joined to dirPath before -// listing, then stripped from the results. -func listBrowseDir(entries []archives.FileInfo, prefix, dirPath string) []archives.FileInfo { - files := listDir(entries, prefix+dirPath) - if prefix == "" { - return files - } - return stripBrowsePrefix(files, prefix) -} - -// listDir mirrors archives.Reader.ListDir: entries directly in dirPath are -// returned in archive order. Deeper paths add one synthesized entry for each -// immediate subdirectory. -func listDir(entries []archives.FileInfo, dirPath string) []archives.FileInfo { - dirPath = normalizeBrowseDir(dirPath) - var files []archives.FileInfo - seenDirs := make(map[string]bool) - - for _, f := range entries { - p := f.Path - - if isInBrowseDir(p, dirPath) { - if f.IsDir { - name := strings.TrimSuffix(strings.TrimPrefix(p, dirPath), "/") - if seenDirs[name] { - continue - } - seenDirs[name] = true - } - files = append(files, f) - continue - } - - if dirPath != "" && !strings.HasPrefix(p, dirPath) { - continue - } - rel := strings.TrimSuffix(strings.TrimPrefix(p, dirPath), "/") - name, _, nested := strings.Cut(rel, "/") - if nested && !seenDirs[name] { - seenDirs[name] = true - files = append(files, archives.FileInfo{ - Path: dirPath + name + "/", - Name: name, - IsDir: true, - }) - } - } - - return files -} - -func normalizeBrowseDir(dirPath string) string { - dirPath = strings.Trim(strings.TrimSpace(dirPath), "/") - if dirPath == "" { - return "" - } - return dirPath + "/" -} - -// isInBrowseDir reports whether filePath is directly in the normalized -// dirPath. An entry naming the directory itself counts as inside it. -func isInBrowseDir(filePath, dirPath string) bool { - filePath = strings.TrimSuffix(filePath, "/") - if dirPath == "" { - return !strings.Contains(filePath, "/") - } - if filePath == dirPath[:len(dirPath)-1] { - return true - } - rest, ok := strings.CutPrefix(filePath, dirPath) - return ok && !strings.Contains(rest, "/") -} - -// stripBrowsePrefix removes prefix from each path, dropping entries outside -// it and the prefix directory itself. -func stripBrowsePrefix(files []archives.FileInfo, prefix string) []archives.FileInfo { - result := make([]archives.FileInfo, 0, len(files)) - for _, f := range files { - stripped, ok := strings.CutPrefix(f.Path, prefix) - if !ok || stripped == "" || stripped == "/" { - continue - } - f.Path = stripped - f.Name = entryName(stripped) - result = append(result, f) - } - return result -} - -// entryName returns the last element of an archive path, ignoring a trailing -// slash. -func entryName(p string) string { - p = strings.TrimSuffix(p, "/") - if i := strings.LastIndexByte(p, '/'); i >= 0 { - return p[i+1:] - } - return p + return archives.OpenBrowser(filename, content, reopen, options) } diff --git a/internal/server/browse_archive_test.go b/internal/server/browse_archive_test.go index c3c7796..838802e 100644 --- a/internal/server/browse_archive_test.go +++ b/internal/server/browse_archive_test.go @@ -9,6 +9,7 @@ import ( "encoding/json" "fmt" "io" + "log/slog" "net/http" "net/http/httptest" "net/url" @@ -332,6 +333,39 @@ func TestBrowseFileContents(t *testing.T) { } } +func TestBrowseFileDirectoryNotFound(t *testing.T) { + for _, format := range []string{"tar.gz", "zip"} { + for _, explicit := range []bool{false, true} { + t.Run(fmt.Sprintf("%s/explicit=%t", format, explicit), func(t *testing.T) { + ts := newTestServer(t) + defer ts.close() + var logs bytes.Buffer + ts.server.logger = slog.New(slog.NewTextHandler(&logs, &slog.HandlerOptions{Level: slog.LevelError})) + + entries := []archiveEntry{{name: "pkg/src/main.go", body: "package main\n"}} + if explicit { + entries = append([]archiveEntry{{name: "pkg/src/", dir: true}}, entries...) + } + data := buildTarGz(t, entries) + if format == "zip" { + data = buildZip(t, entries) + } + cacheBrowseArtifact(t, ts, "cargo", "demo", "demo."+format, data) + + for _, dir := range []string{"src", "src/"} { + response := browseGet(ts, browseFileURL("cargo", "demo", dir)) + if response.Code != http.StatusNotFound { + t.Errorf("directory %q returned %d, want 404: %s", dir, response.Code, response.Body.String()) + } + } + if logs.Len() != 0 { + t.Errorf("directory request logged an error: %s", logs.String()) + } + }) + } + } +} + func TestBrowseFileFirstDuplicateWins(t *testing.T) { ts := newTestServer(t) defer ts.close() @@ -347,6 +381,39 @@ func TestBrowseFileFirstDuplicateWins(t *testing.T) { } } +func TestBrowseSingleRootFile(t *testing.T) { + for _, format := range []string{"tar.gz", "zip"} { + t.Run(format, func(t *testing.T) { + ts := newTestServer(t) + defer ts.close() + entries := []archiveEntry{{name: "README.md", body: "single file\n"}} + data := buildTarGz(t, entries) + if format == "zip" { + data = buildZip(t, entries) + } + filename := "single." + format + cacheBrowseArtifact(t, ts, "cargo", "single", filename, data) + paths := listingPaths(decodeListing(t, browseGet(ts, browseListURL("cargo", "single", "")))) + if len(paths) != 1 || paths[0] != "README.md" { + t.Fatalf("listing = %v, want README.md", paths) + } + response := browseGet(ts, browseFileURL("cargo", "single", "README.md")) + if response.Code != http.StatusOK || response.Body.String() != "single file\n" { + t.Fatalf("file = %d %q", response.Code, response.Body.String()) + } + r, err := openArchive(filename, bytes.NewReader(data), "cargo") + if err != nil { + t.Fatal(err) + } + defer func() { _ = r.Close() }() + files, err := r.List() + if err != nil || len(files) != 1 || files[0].Path != "README.md" { + t.Fatalf("diff reader listing = %+v, %v", files, err) + } + }) + } +} + // TestBrowseFileEscapedPath requests files the way the source browser does, // with each path segment percent-encoded, so names holding URL syntax resolve. func TestBrowseFileEscapedPath(t *testing.T) { diff --git a/internal/server/browse_test.go b/internal/server/browse_test.go index c3352a4..34c864c 100644 --- a/internal/server/browse_test.go +++ b/internal/server/browse_test.go @@ -163,8 +163,11 @@ func TestHandleBrowseFile(t *testing.T) { if got := w.Header().Get("Content-Type"); got != file.contentType { t.Errorf("Content-Type = %q, want %q", got, file.contentType) } - if got := w.Header().Get("Content-Security-Policy"); got != "sandbox" { - t.Errorf("Content-Security-Policy = %q, want sandbox", got) + if got, want := w.Header().Get("Content-Security-Policy"), "sandbox; frame-ancestors 'none'"; got != want { + t.Errorf("Content-Security-Policy = %q, want %q", got, want) + } + if got := w.Header().Get("X-Frame-Options"); got != "DENY" { + t.Errorf("X-Frame-Options = %q, want DENY", got) } if got := w.Header().Get("X-Content-Type-Options"); got != "nosniff" { t.Errorf("X-Content-Type-Options = %q, want nosniff", got) diff --git a/internal/server/cache_api.go b/internal/server/cache_api.go new file mode 100644 index 0000000..771d333 --- /dev/null +++ b/internal/server/cache_api.go @@ -0,0 +1,86 @@ +package server + +import ( + "net/http" + "strings" + + "github.com/git-pkgs/proxy/internal/database" + "github.com/go-chi/chi/v5" +) + +// CacheDeleteResponse lists the cached files removed for a version. +type CacheDeleteResponse struct { + PURL string `json:"purl"` + Deleted []string `json:"deleted"` +} + +// handleCacheDelete handles DELETE /api/cache/{ecosystem}/{name}/{version} +// @Summary Delete cached artifacts +// @Description Removes the cached files of name@version, or only the one named by filename, so the next request fetches them from the upstream again. Pushed archives are not touched; delete those through /api/hosted. +// @Tags cache +// @Produce json +// @Param ecosystem path string true "Ecosystem" +// @Param name path string true "Package name as shown in the UI, e.g. com.google.guava:guava for Maven" +// @Param version path string true "Version" +// @Param filename query string false "Delete only this file" +// @Success 200 {object} CacheDeleteResponse +// @Failure 400 {object} ErrorResponse +// @Failure 404 {object} ErrorResponse +// @Failure 409 {object} ErrorResponse +// @Router /api/cache/{ecosystem}/{name}/{version} [delete] +func (s *Server) handleCacheDelete(w http.ResponseWriter, r *http.Request) { + segments, err := packagePathSegments(r) + if err != nil { + badRequest(w, err.Error()) + return + } + if len(segments) < minVersionPathSegments { + badRequest(w, "path must be /api/cache/{ecosystem}/{name}/{version}") + return + } + last := len(segments) - 1 + ecosystem, name, version := chi.URLParam(r, "ecosystem"), strings.Join(segments[:last], "/"), segments[last] + filename := r.URL.Query().Get("filename") + + versionPURL := s.cachedVersionPURL(ecosystem, name, version) + if versionPURL == "" { + notFound(w, "package not found") + return + } + artifacts, err := s.db.GetArtifactsByVersionPURL(versionPURL) + if err != nil { + s.logger.Error("failed to list artifacts", "purl", versionPURL, "error", err) + internalError(w, "failed to list artifacts") + return + } + + deleted := []string{} + for _, art := range artifacts { + if filename != "" && art.Filename != filename { + continue + } + if !art.StoragePath.Valid { + continue + } + if art.Source == database.SourceLocal { + if filename != "" { + writeError(w, http.StatusConflict, ErrCodeConflict, "pushed archives are deleted through /api/hosted") + return + } + continue + } + if err := s.db.DiscardArtifact(versionPURL, art.Filename, art.StoragePath.String); err != nil { + s.logger.Error("failed to delete cached artifact", "purl", versionPURL, "filename", art.Filename, "error", err) + internalError(w, "failed to delete cached artifact") + return + } + deleted = append(deleted, art.Filename) + } + if len(deleted) == 0 { + notFound(w, "no cached artifact matched") + return + } + + s.logger.Info("deleted cached artifacts", "purl", versionPURL, "files", deleted) + writeJSON(w, CacheDeleteResponse{PURL: versionPURL, Deleted: deleted}) +} diff --git a/internal/server/cache_api_test.go b/internal/server/cache_api_test.go new file mode 100644 index 0000000..8e66755 --- /dev/null +++ b/internal/server/cache_api_test.go @@ -0,0 +1,183 @@ +package server + +import ( + "database/sql" + "encoding/json" + "net/http" + "net/http/httptest" + "slices" + "strings" + "testing" + "time" + + "github.com/git-pkgs/proxy/internal/database" + "github.com/go-chi/chi/v5" +) + +const ( + cacheTestPackage = "pkg:maven/com.example/lib" + cacheTestVersion = cacheTestPackage + "@1.0" +) + +// seedCacheDeleteVersion caches lib-1.0.jar and its .sha1 for +// com.example:lib 1.0, plus a pushed lib-1.0-local.jar when pushed is set. +func seedCacheDeleteVersion(t *testing.T, db *database.DB, pushed bool) { + t.Helper() + if err := db.UpsertPackage(&database.Package{PURL: cacheTestPackage, Ecosystem: "maven", Name: "com.example:lib"}); err != nil { + t.Fatalf("UpsertPackage: %v", err) + } + if err := db.UpsertVersion(&database.Version{PURL: cacheTestVersion, PackagePURL: cacheTestPackage}); err != nil { + t.Fatalf("UpsertVersion: %v", err) + } + files := map[string]string{"lib-1.0.jar": database.SourceUpstream, "lib-1.0.jar.sha1": database.SourceUpstream} + if pushed { + files["lib-1.0-local.jar"] = database.SourceLocal + } + for filename, source := range files { + if err := db.UpsertArtifact(&database.Artifact{ + VersionPURL: cacheTestVersion, + Filename: filename, + UpstreamURL: "https://repo1.maven.org/maven2/com/example/lib/1.0/" + filename, + StoragePath: sql.NullString{String: "objects/" + filename, Valid: true}, + FetchedAt: sql.NullTime{Time: time.Now(), Valid: true}, + Source: source, + }); err != nil { + t.Fatalf("UpsertArtifact %s: %v", filename, err) + } + } +} + +func cacheDelete(ts *testServer, target string) *httptest.ResponseRecorder { + r := chi.NewRouter() + r.Delete("/api/cache/{ecosystem}/*", ts.server.handleCacheDelete) + w := httptest.NewRecorder() + r.ServeHTTP(w, httptest.NewRequest(http.MethodDelete, target, nil)) + return w +} + +func cachedFiles(t *testing.T, db *database.DB) []string { + t.Helper() + artifacts, err := db.GetArtifactsByVersionPURL(cacheTestVersion) + if err != nil { + t.Fatalf("GetArtifactsByVersionPURL: %v", err) + } + var cached []string + for _, art := range artifacts { + if art.StoragePath.Valid { + cached = append(cached, art.Filename) + } + } + slices.Sort(cached) + return cached +} + +func queuedDeletes(t *testing.T, db *database.DB) []string { + t.Helper() + paths, err := db.GetDuePendingDeletes(time.Now().Add(time.Hour), 100) + if err != nil { + t.Fatalf("GetDuePendingDeletes: %v", err) + } + slices.Sort(paths) + return paths +} + +func TestCacheDelete_OneFile(t *testing.T) { + ts := newTestServer(t) + defer ts.close() + seedCacheDeleteVersion(t, ts.db, false) + + w := cacheDelete(ts, "/api/cache/maven/com.example:lib/1.0?filename=lib-1.0.jar") + if w.Code != http.StatusOK { + t.Fatalf("status = %d, want 200; body: %s", w.Code, w.Body.String()) + } + var resp CacheDeleteResponse + if err := json.NewDecoder(w.Body).Decode(&resp); err != nil { + t.Fatalf("decoding response: %v", err) + } + if resp.PURL != cacheTestVersion || !slices.Equal(resp.Deleted, []string{"lib-1.0.jar"}) { + t.Errorf("response = %+v, want lib-1.0.jar deleted from %s", resp, cacheTestVersion) + } + if got := cachedFiles(t, ts.db); !slices.Equal(got, []string{"lib-1.0.jar.sha1"}) { + t.Errorf("still cached = %v, want only the .sha1", got) + } + if got := queuedDeletes(t, ts.db); !slices.Equal(got, []string{"objects/lib-1.0.jar"}) { + t.Errorf("queued for deletion = %v, want the jar's object", got) + } +} + +func TestCacheDelete_WholeVersionKeepsPushedFiles(t *testing.T) { + ts := newTestServer(t) + defer ts.close() + seedCacheDeleteVersion(t, ts.db, true) + + w := cacheDelete(ts, "/api/cache/maven/com.example:lib/1.0") + if w.Code != http.StatusOK { + t.Fatalf("status = %d, want 200; body: %s", w.Code, w.Body.String()) + } + if got := cachedFiles(t, ts.db); !slices.Equal(got, []string{"lib-1.0-local.jar"}) { + t.Errorf("still cached = %v, want only the pushed jar", got) + } + if got := queuedDeletes(t, ts.db); !slices.Equal(got, []string{"objects/lib-1.0.jar", "objects/lib-1.0.jar.sha1"}) { + t.Errorf("queued for deletion = %v, want both upstream objects", got) + } +} + +func TestCacheDelete_Refusals(t *testing.T) { + tests := []struct { + name string + target string + want int + }{ + {"pushed file", "/api/cache/maven/com.example:lib/1.0?filename=lib-1.0-local.jar", http.StatusConflict}, + {"unknown file", "/api/cache/maven/com.example:lib/1.0?filename=other.jar", http.StatusNotFound}, + {"unknown version", "/api/cache/maven/com.example:lib/2.0", http.StatusNotFound}, + {"unknown package", "/api/cache/maven/com.example:other/1.0", http.StatusNotFound}, + {"no version", "/api/cache/maven/lib", http.StatusBadRequest}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + ts := newTestServer(t) + defer ts.close() + seedCacheDeleteVersion(t, ts.db, true) + + w := cacheDelete(ts, tt.target) + if w.Code != tt.want { + t.Fatalf("status = %d, want %d; body: %s", w.Code, tt.want, w.Body.String()) + } + if got := cachedFiles(t, ts.db); len(got) != 3 { + t.Errorf("still cached = %v, want all three files untouched", got) + } + }) + } +} + +func TestVersionPage_CacheDeleteButtons(t *testing.T) { + for _, enabled := range []bool{false, true} { + ts := newTestServer(t) + seedCacheDeleteVersion(t, ts.db, true) + ts.server.cfg.CacheDelete = enabled + + w := httptest.NewRecorder() + ts.handler.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/ui/package/maven/com.example:lib/1.0", nil)) + ts.close() + if w.Code != http.StatusOK { + t.Fatalf("enabled=%v: status = %d, want 200", enabled, w.Code) + } + body := w.Body.String() + // One button per upstream file plus the version-wide one; the pushed + // jar gets none. + wantButtons := 0 + if enabled { + wantButtons = 3 + } + if got := strings.Count(body, `class="cache-delete `); got != wantButtons { + t.Errorf("enabled=%v: %d delete buttons, want %d", enabled, got, wantButtons) + } + if enabled && !strings.Contains(body, `data-cache-url="/ui/api/cache/maven/com.example:lib/1.0"`) { + t.Errorf("page has no data-cache-url for the version") + } + if got := strings.Contains(body, ` + +{{if .Components}} +
+
+ {{range .Components}} +
+
+ {{template "ecosystem_badge" .Ecosystem}} + {{if .Cached}} + {{.Name}} + {{else}} + {{.Name}} + {{end}} + {{.Version}} +
+
+ {{if .Outdated}} + outdated, latest {{.LatestVersion}} + {{end}} + {{if not .Cached}} + not cached + {{end}} +
+
+ {{end}} +
+
+{{else}} +
+

The latest SBOM lists no packages the proxy serves

+
+{{end}} +{{end}} diff --git a/internal/server/templates/pages/projects_list.html b/internal/server/templates/pages/projects_list.html new file mode 100644 index 0000000..d7256da --- /dev/null +++ b/internal/server/templates/pages/projects_list.html @@ -0,0 +1,33 @@ +{{define "title"}}Projects - git-pkgs proxy{{end}} + +{{define "content"}} +
+

Projects

+

{{len .Rows}} projects, as of their latest SBOM upload

+
+ +{{if .Rows}} +
+
+ {{range .Rows}} +
+
+ {{.Name}} + {{if or .Branch .Ref}} +
{{.Branch}}{{if and .Branch .Ref}} @ {{end}}{{.Ref}}
+ {{end}} +
+
+ {{.Components}} packages + {{.UploadedAt}} +
+
+ {{end}} +
+
+{{else}} +
+

No project has uploaded an SBOM yet

+
+{{end}} +{{end}} diff --git a/internal/server/templates/pages/version_show.html b/internal/server/templates/pages/version_show.html index 81bc067..468f24c 100644 --- a/internal/server/templates/pages/version_show.html +++ b/internal/server/templates/pages/version_show.html @@ -69,10 +69,14 @@ {{if .Artifacts}} -
-
+
+

Artifacts ({{len .Artifacts}})

+ {{if and .CacheDelete .HasDeletableArtifact}} + + {{end}}
+
{{range .Artifacts}}
@@ -81,6 +85,9 @@
{{if .Size.Valid}}{{.Size.Int64}} bytes{{end}} {{if gt .HitCount 0}}{{.HitCount}} cache hits{{end}} + {{if and $.CacheDelete .StoragePath.Valid (ne .Source "local")}} + + {{end}}
{{if .ContentHash.Valid}} @@ -100,6 +107,9 @@ {{end}}
+{{if .CacheDelete}} + +{{end}} {{else}}
No artifacts cached yet diff --git a/internal/server/templates_test.go b/internal/server/templates_test.go index 276af6e..c6fa492 100644 --- a/internal/server/templates_test.go +++ b/internal/server/templates_test.go @@ -8,6 +8,7 @@ import ( "regexp" "strings" "testing" + "time" "github.com/git-pkgs/proxy/internal/database" ) @@ -63,19 +64,18 @@ func TestTemplatesRenderAllPages(t *testing.T) { {Ecosystem: "cargo", CacheSize: 120, Downloads: 3004, DownloadedBytes: 500_000_000}, }, 1_500_000_000, "1.4 GB"), Runtime: RuntimeView{ - Available: true, - Requests: "12,004", - ActiveRequests: "2", - RequestMean: "8.1 ms", - CacheHits: "9,000", - CacheMisses: "1,000", - CacheHitRatio: "90.0", - HasCacheTraffic: true, - StatusClasses: []LabelledCount{{Label: "2xx", Count: "11,900"}, {Label: "5xx", Count: "104", Bad: true}}, - StorageOps: []LabelledStat{{Label: "get", Count: "9,000", Mean: "412 µs"}}, - ScanErrors: []LabelledCount{{Label: "npm · clamav · timeout", Count: "3", Bad: true}}, - ScanningOn: true, - Breakers: []BreakerRow{{Registry: "registry.npmjs.org", State: "closed"}}, + Available: true, + Requests: "12,004", + ActiveRequests: "2", + RequestMean: "8.1 ms", + ArtifactCache: CacheLookups{Hits: "9,000", Misses: "1,000", HitRatio: "90.0", HasTraffic: true}, + MetadataCache: CacheLookups{Hits: "4,000", Misses: "500", HitRatio: "88.9", HasTraffic: true}, + MetadataServed: "12.0 MB", + StatusClasses: []LabelledCount{{Label: "2xx", Count: "11,900"}, {Label: "5xx", Count: "104", Bad: true}}, + StorageOps: []LabelledStat{{Label: "get", Count: "9,000", Mean: "412 µs"}}, + ScanErrors: []LabelledCount{{Label: "npm · clamav · timeout", Count: "3", Bad: true}}, + ScanningOn: true, + Breakers: []BreakerRow{{Registry: "registry.npmjs.org", State: "closed"}}, }, }}, {"analytics", AnalyticsData{}}, @@ -123,8 +123,12 @@ func TestTemplatesRenderAllPages(t *testing.T) { LatestVersion: sql.NullString{String: "4.17.21", Valid: true}, License: sql.NullString{String: "MIT", Valid: true}, }, - Versions: []database.Version{ - {PURL: "pkg:npm/lodash@4.17.21", PackagePURL: "pkg:npm/lodash"}, + Versions: []PackageVersion{ + {Version: database.Version{PURL: "pkg:npm/lodash@4.17.21", PackagePURL: "pkg:npm/lodash"}}, + { + Version: database.Version{PURL: "pkg:npm/lodash@4.17.22", PackagePURL: "pkg:npm/lodash"}, + AvailableAt: time.Date(2026, 1, 2, 3, 4, 0, 0, time.UTC), + }, }, Vulnerabilities: []database.Vulnerability{}, LicenseCategory: "permissive", @@ -135,7 +139,7 @@ func TestTemplatesRenderAllPages(t *testing.T) { Ecosystem: "npm", Name: "minimal", }, - Versions: []database.Version{}, + Versions: []PackageVersion{}, Vulnerabilities: []database.Vulnerability{}, LicenseCategory: "unknown", }}, diff --git a/internal/storage/blob.go b/internal/storage/blob.go index 7a34d7d..81af78f 100644 --- a/internal/storage/blob.go +++ b/internal/storage/blob.go @@ -22,6 +22,16 @@ import ( const osWindows = "windows" +// Upload buffering for cloud backends. The S3 driver otherwise allocates +// (5+1) x 8 MiB part buffers up front for every object over 16 MiB, and the +// Azure driver uses 5 x 8 MiB blocks; with several large artifacts being +// cached at once that adds up to hundreds of MiB. 5 MiB is the smallest part +// S3 accepts. The file backend ignores both. +const ( + uploadBufferSize = 5 << 20 + uploadConcurrency = 2 +) + // attrsExt is fileblob's sidecar suffix, kept only to clear sidecars an // earlier version wrote. const attrsExt = ".attrs" @@ -212,7 +222,10 @@ func (b *Blob) Store(ctx context.Context, path string, r io.Reader) (int64, stri writeCtx, abort := context.WithCancel(ctx) defer abort() - opts := &blob.WriterOptions{} + opts := &blob.WriterOptions{ + BufferSize: uploadBufferSize, + MaxConcurrency: uploadConcurrency, + } w, err := b.bucket.NewWriter(writeCtx, path, opts) if err != nil { return 0, "", fmt.Errorf("creating writer: %w", err) @@ -255,6 +268,11 @@ func (b *Blob) Open(ctx context.Context, path string) (io.ReadCloser, error) { return r, nil } +// ReadsSeekable reports that Open returns seekable readers: an *os.File for +// file:// buckets and a *blob.Reader, which seeks with a ranged read, +// otherwise. +func (b *Blob) ReadsSeekable() bool { return true } + func (b *Blob) Exists(ctx context.Context, path string) (bool, error) { exists, err := b.bucket.Exists(ctx, path) if err != nil { diff --git a/internal/storage/blob_test.go b/internal/storage/blob_test.go index 5533174..1a764de 100644 --- a/internal/storage/blob_test.go +++ b/internal/storage/blob_test.go @@ -84,6 +84,14 @@ func TestBlobOpen(t *testing.T) { } } +// Blob.ReadsSeekable promises seekable readers for every bucket: file:// +// objects open as *os.File (checked in TestBlobOpen) and remote ones as +// *blob.Reader. +var ( + _ io.Seeker = (*blob.Reader)(nil) + _ SeekableReads = (*Blob)(nil) +) + func TestBlobOpenNotFound(t *testing.T) { b := createTestBlob(t) ctx := context.Background() @@ -495,7 +503,7 @@ func seedLegacySidecar(t *testing.T, dir, key, payload string) string { // An interrupted setAttrs leaves a partial sidecar that fails every read of the // key, and nothing rewrites one now, so a store has to clear it. // -// One key per storage path the proxy builds: ArtifactPath across ecosystems, +// One key per storage path the proxy builds: legacy artifact keys across ecosystems, // metadata blobs, and the Gradle build cache. Scoped npm names, Go's "!" case // escaping and the ":" in OCI digests and Debian epochs are the characters // most likely to part fileblob's mapping from a plain path join. diff --git a/internal/storage/s3_upload_test.go b/internal/storage/s3_upload_test.go new file mode 100644 index 0000000..898b1f7 --- /dev/null +++ b/internal/storage/s3_upload_test.go @@ -0,0 +1,120 @@ +package storage + +import ( + "bytes" + "context" + "fmt" + "io" + "maps" + "net/http" + "net/http/httptest" + "slices" + "strconv" + "strings" + "sync" + "testing" +) + +// fakeS3 implements just enough of the S3 API for PutObject and multipart +// uploads, recording the size of each part it receives. +type fakeS3 struct { + mu sync.Mutex + objects map[string][]byte + parts map[int][]byte + partSizes []int + // discard drops bodies so a benchmark measures only the client. + discard bool +} + +func newFakeS3(t testing.TB) (*fakeS3, string) { + t.Helper() + f := &fakeS3{objects: map[string][]byte{}, parts: map[int][]byte{}} + server := httptest.NewServer(f) + t.Cleanup(server.Close) + url := "s3://bucket?endpoint=" + server.URL + "®ion=us-east-1&use_path_style=true&anonymous=true&request_checksum_calculation=when_required" + return f, url +} + +func (f *fakeS3) ServeHTTP(w http.ResponseWriter, r *http.Request) { + key := strings.TrimPrefix(r.URL.Path, "/bucket/") + q := r.URL.Query() + if f.discard { + _, _ = io.Copy(io.Discard, r.Body) + r.Body = http.NoBody + } + body, err := io.ReadAll(r.Body) + if err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + f.mu.Lock() + defer f.mu.Unlock() + switch { + case r.Method == http.MethodPost && q.Has("uploads"): + f.parts = map[int][]byte{} + _, _ = fmt.Fprintf(w, `bucket%supload`, key) + case r.Method == http.MethodPut && q.Has("partNumber"): + n, _ := strconv.Atoi(q.Get("partNumber")) + f.parts[n] = body + f.partSizes = append(f.partSizes, len(body)) + w.Header().Set("ETag", fmt.Sprintf(`"part%d"`, n)) + case r.Method == http.MethodPost && q.Has("uploadId"): + var object []byte + for _, n := range slices.Sorted(maps.Keys(f.parts)) { + object = append(object, f.parts[n]...) + } + f.objects[key] = object + _, _ = fmt.Fprintf(w, `bucket%s"object"`, key) + case r.Method == http.MethodPut: + f.objects[key] = body + w.Header().Set("ETag", `"object"`) + default: + http.Error(w, "unsupported", http.StatusNotImplemented) + } +} + +func TestS3StoreUsesSmallUploadParts(t *testing.T) { + fake, url := newFakeS3(t) + store, err := OpenBucket(context.Background(), url) + if err != nil { + t.Fatal(err) + } + defer func() { _ = store.Close() }() + + small := []byte("small object") + large := bytes.Repeat([]byte("0123456789abcdef"), 20<<20/16) + for name, data := range map[string][]byte{"small": small, "large": large} { + size, _, err := store.Store(context.Background(), name, bytes.NewReader(data)) + if err != nil { + t.Fatalf("Store(%s): %v", name, err) + } + if size != int64(len(data)) || !bytes.Equal(fake.objects[name], data) { + t.Errorf("Store(%s) wrote %d bytes, stored %d; want %d", name, size, len(fake.objects[name]), len(data)) + } + } + if len(fake.partSizes) == 0 { + t.Fatal("large object was not uploaded in parts") + } + for _, n := range fake.partSizes { + if n > uploadBufferSize { + t.Errorf("part of %d bytes, want at most %d", n, uploadBufferSize) + } + } +} + +func BenchmarkS3Store(b *testing.B) { + fake, url := newFakeS3(b) + fake.discard = true + store, err := OpenBucket(context.Background(), url) + if err != nil { + b.Fatal(err) + } + defer func() { _ = store.Close() }() + data := bytes.Repeat([]byte("0123456789abcdef"), 32<<20/16) + b.SetBytes(int64(len(data))) + for b.Loop() { + if _, _, err := store.Store(context.Background(), "object", bytes.NewReader(data)); err != nil { + b.Fatal(err) + } + } +} diff --git a/internal/storage/storage.go b/internal/storage/storage.go index 3b27ef4..edca684 100644 --- a/internal/storage/storage.go +++ b/internal/storage/storage.go @@ -77,16 +77,11 @@ type Storage interface { Close() error } -// ArtifactPath builds the storage path artifacts were cached under before each -// fetch got its own; records from then still point at such paths. Only tests -// call it, to build such records. -// Format: {ecosystem}/{namespace}/{name}/{version}/{filename} -// For packages without namespace: {ecosystem}/{name}/{version}/{filename} -func ArtifactPath(ecosystem, namespace, name, version, filename string) string { - if namespace != "" { - return ecosystem + "/" + namespace + "/" + name + "/" + version + "/" + filename - } - return ecosystem + "/" + name + "/" + version + "/" + filename +// SeekableReads is implemented by backends whose Open always returns a +// reader that implements io.Seeker. It tells a caller that byte ranges can be +// served from an object without opening it first. +type SeekableReads interface { + ReadsSeekable() bool } // FetchPath builds the storage path for one fetch of an artifact: diff --git a/internal/storage/storage_test.go b/internal/storage/storage_test.go index 67745d0..5d4f0b4 100644 --- a/internal/storage/storage_test.go +++ b/internal/storage/storage_test.go @@ -22,31 +22,6 @@ func TestIsFetchDir(t *testing.T) { } } -func TestArtifactPath(t *testing.T) { - tests := []struct { - ecosystem string - namespace string - name string - version string - filename string - want string - }{ - {"npm", "", "lodash", "4.17.21", "lodash-4.17.21.tgz", "npm/lodash/4.17.21/lodash-4.17.21.tgz"}, - {"npm", "babel", "core", "7.0.0", "core-7.0.0.tgz", "npm/babel/core/7.0.0/core-7.0.0.tgz"}, - {"cargo", "", "serde", "1.0.0", "serde-1.0.0.crate", "cargo/serde/1.0.0/serde-1.0.0.crate"}, - {"pypi", "", "requests", "2.28.0", "requests-2.28.0.tar.gz", "pypi/requests/2.28.0/requests-2.28.0.tar.gz"}, - {"maven", "org.apache", "commons-lang3", "3.12.0", "commons-lang3-3.12.0.jar", "maven/org.apache/commons-lang3/3.12.0/commons-lang3-3.12.0.jar"}, - } - - for _, tt := range tests { - got := ArtifactPath(tt.ecosystem, tt.namespace, tt.name, tt.version, tt.filename) - if got != tt.want { - t.Errorf("ArtifactPath(%q, %q, %q, %q, %q) = %q, want %q", - tt.ecosystem, tt.namespace, tt.name, tt.version, tt.filename, got, tt.want) - } - } -} - // assertLargeFileRoundTrip stores a 1MB file in the given storage, verifies size and // hash, then reads it back and confirms the content matches. func assertLargeFileRoundTrip(t *testing.T, s Storage) {