Watch
1
0
Fork
You've already forked pkg-proxy
1
mirror of https://github.com/git-pkgs/proxy.git synced 2026-08-24 04:44:56 -04:00

Compare commits

..
Author SHA1 Message Date
Andrew Nesbitt
c07c59c83e
Use shared database types and connection helpers from git-pkgs
Import Package and Version types from the git-pkgs database package
instead of defining them locally. Both projects now share the same
type definitions, keeping the packages and versions tables in sync.

Delegate SQLite connection setup to the shared Open function so
pragma settings (WAL, busy timeout, connection limit) stay aligned.
2026-03-04 19:21:42 +00:00
146 changed files with 3241 additions and 27085 deletions

View file

@ -8,14 +8,6 @@ updates:
cooldown: cooldown:
default-days: 7 default-days: 7
- package-ecosystem: docker
directory: /
schedule:
interval: weekly
open-pull-requests-limit: 5
cooldown:
default-days: 7
- package-ecosystem: github-actions - package-ecosystem: github-actions
directory: / directory: /
schedule: schedule:

View file

@ -13,17 +13,18 @@ jobs:
strategy: strategy:
matrix: matrix:
os: [ubuntu-latest, macos-latest, windows-latest] os: [ubuntu-latest, macos-latest, windows-latest]
go-version: ['1.25']
runs-on: ${{ matrix.os }} runs-on: ${{ matrix.os }}
steps: steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with: with:
persist-credentials: false persist-credentials: false
- name: Set up Go - name: Set up Go
uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 uses: actions/setup-go@7a3fe6cf4cb3a834922a1244abfce67bcef6a0c5 # v6.2.0
with: with:
go-version-file: go.mod go-version: ${{ matrix.go-version }}
- name: Build - name: Build
run: go build -v ./... run: go build -v ./...
@ -34,14 +35,14 @@ jobs:
lint: lint:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with: with:
persist-credentials: false persist-credentials: false
- name: Set up Go - name: Set up Go
uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 uses: actions/setup-go@7a3fe6cf4cb3a834922a1244abfce67bcef6a0c5 # v6.2.0
with: with:
go-version-file: go.mod go-version: '1.25'
- name: golangci-lint - name: golangci-lint
run: go tool golangci-lint run ./... run: go tool golangci-lint run ./...

View file

@ -1,98 +0,0 @@
name: Publish Docker image
on:
workflow_dispatch:
push:
tags:
- "v*"
permissions: {}
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
jobs:
push_to_registry:
name: Push Docker image to GHCR
runs-on: ubuntu-latest
permissions:
packages: write
contents: read
id-token: write
steps:
- name: Check out the repo
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1
with:
persist-credentials: false
- name: Set up QEMU
uses: docker/setup-qemu-action@96fe6ef7f33517b61c61be40b68a1882f3264fb8 # v4.2.0
with:
platforms: linux/amd64,linux/arm64
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@bb05f3f5519dd87d3ba754cc423b652a5edd6d2c # v4.2.0
- name: Log in to the Container registry
uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Extract metadata (tags, labels) for Docker
id: meta
uses: docker/metadata-action@dc802804100637a589fabce1cb79ff13a1411302
with:
images: ghcr.io/${{ github.repository }}
- uses: sigstore/cosign-installer@6f9f17788090df1f26f669e9d70d6ae9567deba6 # v4.1.2
- name: Build and push Docker image
id: build
uses: docker/build-push-action@53b7df96c91f9c12dcc8a07bcb9ccacbed38856a
with:
context: .
platforms: linux/amd64,linux/arm64
push: true
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
provenance: mode=max
sbom: true
- name: Sign image by digest
env:
DIGEST: ${{ steps.build.outputs.digest }}
IMAGE: ghcr.io/${{ github.repository }}
run: |
set -euo pipefail
[[ "$DIGEST" =~ ^sha256:[0-9a-f]{64}$ ]]
cosign sign --yes "${IMAGE}@${DIGEST}"
- name: Verify BuildKit attestations and extract SPDX predicates
env:
DIGEST: ${{ steps.build.outputs.digest }}
IMAGE: ghcr.io/${{ github.repository }}
run: |
set -euo pipefail
reference="${IMAGE}@${DIGEST}"
docker buildx imagetools inspect "$reference" --format '{{ json .Provenance }}' > provenance.json
docker buildx imagetools inspect "$reference" --format '{{ json .SBOM }}' > sbom.json
for platform in linux/amd64 linux/arm64; do
jq -e --arg p "$platform" '.[$p].SLSA | type == "object" and length > 0' \
provenance.json >/dev/null
jq -e --arg p "$platform" '.[$p].SPDX' sbom.json > "sbom-${platform//\//-}.spdx.json"
done
- name: Attest platform SBOMs by digest
env:
DIGEST: ${{ steps.build.outputs.digest }}
IMAGE: ghcr.io/${{ github.repository }}
run: |
set -euo pipefail
[[ "$DIGEST" =~ ^sha256:[0-9a-f]{64}$ ]]
reference="${IMAGE}@${DIGEST}"
for predicate in sbom-linux-amd64.spdx.json sbom-linux-arm64.spdx.json; do
cosign attest --yes --type spdxjson --predicate "$predicate" "$reference"
done

View file

@ -7,27 +7,24 @@ on:
permissions: permissions:
contents: write contents: write
id-token: write
jobs: jobs:
release: release:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with: with:
fetch-depth: 0 fetch-depth: 0
persist-credentials: false persist-credentials: false
- uses: sigstore/cosign-installer@6f9f17788090df1f26f669e9d70d6ae9567deba6 # v4.1.2
- name: Set up Go - name: Set up Go
uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 uses: actions/setup-go@7a3fe6cf4cb3a834922a1244abfce67bcef6a0c5 # v6.2.0
with: with:
go-version-file: go.mod go-version-file: go.mod
cache: false cache: false
- uses: goreleaser/goreleaser-action@f06c13b6b1a9625abc9e6e439d9c05a8f2190e94 # v7.2.3 - uses: goreleaser/goreleaser-action@ec59f474b9834571250b370d4735c50f8e2d1e29 # v7.0.0
with: with:
version: "~> v2" version: "~> v2"
args: release --clean args: release --clean

View file

@ -1,36 +0,0 @@
name: Swagger
on:
pull_request:
branches: [main]
push:
branches: [main]
permissions: {}
jobs:
swagger:
runs-on: ubuntu-latest
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
- name: Install swag
run: go install github.com/swaggo/swag/cmd/swag@latest
- name: Generate swagger
run: go generate ./internal/server
- name: Verify no changes
run: |
if [ -n "$(git status --porcelain)" ]; then
echo "Swagger docs are out of date. Run: go generate ./internal/server" >&2
git status --porcelain
exit 1
fi

View file

@ -21,9 +21,9 @@ jobs:
security-events: write security-events: write
steps: steps:
- name: Checkout - name: Checkout
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with: with:
persist-credentials: false persist-credentials: false
- name: Run zizmor - name: Run zizmor
uses: zizmorcore/zizmor-action@3dc1ecc9bcb9e94e9b2c709687979e1298497054 # v0.6.2 uses: zizmorcore/zizmor-action@0dce2577a4760a2749d8cfb7a84b7d5585ebcb7d # v0.5.0

4
.gitignore vendored
View file

@ -14,8 +14,8 @@ proxy
coverage.html coverage.html
coverage.txt coverage.txt
# Go vendor directory (repo root only; embedded UI vendor dirs are tracked) # Dependency directories
/vendor/ vendor/
# Go workspace file # Go workspace file
go.work go.work

View file

@ -1,28 +0,0 @@
version: "2"
linters:
enable:
- gocritic
- gocognit
- gocyclo
- maintidx
- dupl
- mnd
- unparam
- ireturn
- goconst
- errcheck
settings:
goconst:
min-len: 4
min-occurrences: 5
ignore-tests: true
ignore-string-values:
- "^[a-z]+$"
exclusions:
rules:
- path: _test\.go
linters:
- goconst
- dupl
- mnd

View file

@ -34,17 +34,6 @@ archives:
checksum: checksum:
name_template: "checksums.txt" name_template: "checksums.txt"
signs:
- cmd: cosign
signature: "${artifact}.cosign.bundle"
args:
- sign-blob
- "--bundle=${signature}"
- "${artifact}"
- "--yes"
artifacts: checksum
output: true
snapshot: snapshot:
version_template: "{{ incpatch .Version }}-next" version_template: "{{ incpatch .Version }}-next"

View file

@ -39,7 +39,7 @@ proxy/
│ │ └── queries.go # CRUD operations │ │ └── queries.go # CRUD operations
│ ├── storage/ # Artifact file storage │ ├── storage/ # Artifact file storage
│ │ ├── storage.go # Storage interface │ │ ├── storage.go # Storage interface
│ │ └── blob.go # gocloud.dev/blob backends (file, S3, Azure) │ │ └── filesystem.go # Local filesystem impl
│ ├── upstream/ # Upstream registry clients │ ├── upstream/ # Upstream registry clients
│ │ ├── fetcher.go # HTTP artifact fetching │ │ ├── fetcher.go # HTTP artifact fetching
│ │ └── resolver.go # Download URL resolution │ │ └── resolver.go # Download URL resolution
@ -72,7 +72,7 @@ Key types:
### `internal/storage` ### `internal/storage`
Artifact file storage abstraction backed by `gocloud.dev/blob`. Supports local filesystem (`file://`), S3 (`s3://`), and Azure (`azblob://`) URLs. Artifact file storage abstraction. Currently implements local filesystem storage. Designed to allow future backends (S3, GCS).
Interface: Interface:
```go ```go

View file

@ -1,4 +1,4 @@
FROM --platform=$BUILDPLATFORM golang:1.26.6-alpine AS builder FROM golang:1.24-alpine AS builder
WORKDIR /src WORKDIR /src
@ -12,11 +12,10 @@ RUN go mod download
# Copy source code # Copy source code
COPY . . COPY . .
# Build the binary for the target platform # Build the binary
ARG TARGETARCH RUN CGO_ENABLED=0 GOOS=linux go build -ldflags="-s -w" -o /proxy ./cmd/proxy
RUN CGO_ENABLED=0 GOOS=linux GOARCH=${TARGETARCH} go build -ldflags="-s -w" -o /proxy ./cmd/proxy
FROM alpine:3.24.1 FROM alpine:3.21
RUN apk add --no-cache ca-certificates RUN apk add --no-cache ca-certificates

232
LICENSE
View file

@ -1,232 +0,0 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright © 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for software and other kinds of works.
The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too.
When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.
Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions.
Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and modification follow.
TERMS AND CONDITIONS
0. Definitions.
“This License” refers to version 3 of the GNU General Public License.
“Copyright” also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.
“The Program” refers to any copyrightable work licensed under this License. Each licensee is addressed as “you”. “Licensees” and “recipients” may be individuals or organizations.
To “modify” a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a “modified version” of the earlier work or a work “based on” the earlier work.
A “covered work” means either the unmodified Program or a work based on the Program.
To “propagate” a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well.
To “convey” a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays “Appropriate Legal Notices” to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion.
1. Source Code.
The “source code” for a work means the preferred form of the work for making modifications to it. “Object code” means any non-source form of a work.
A “Standard Interface” means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language.
The “System Libraries” of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A “Major Component”, in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it.
The “Corresponding Source” for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work.
The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.
The Corresponding Source for a work in source code form is that same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures.
When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified it, and giving a relevant date.
b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to “keep intact all notices”.
c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.
A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an “aggregate” if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways:
a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.
d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.
A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work.
A “User Product” is either (1) a “consumer product”, which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, “normally used” refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product.
“Installation Information” for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made.
If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM).
The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying.
7. Additional Terms.
“Additional permissions” are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or authors of the material; or
e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.
All other non-permissive additional terms are considered “further restrictions” within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).
However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.
Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License.
An “entity transaction” is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it.
11. Patents.
A “contributor” is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's “contributor version”.
A contributor's “essential patent claims” are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, “control” includes the right to grant patent sublicenses in a manner consistent with the requirements of this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version.
In the following three paragraphs, a “patent license” is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To “grant” such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party.
If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. “Knowingly relying” means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it.
A patent license is “discriminatory” if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License “or any later version” applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation.
If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program.
Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the “copyright” line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an “about box”.
You should also get your employer (if you work as a programmer) or school, if any, to sign a “copyright disclaimer” for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see <https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read <https://www.gnu.org/philosophy/why-not-lgpl.html>.

441
README.md
View file

@ -2,65 +2,33 @@
A caching proxy for package registries. Speeds up package downloads by caching artifacts locally, reducing bandwidth usage and improving reliability. A caching proxy for package registries. Speeds up package downloads by caching artifacts locally, reducing bandwidth usage and improving reliability.
## Version Cooldown
Most supply chain attacks rely on speed: a malicious version gets published and consumed by automated pipelines within minutes, before anyone notices. The cooldown feature adds a quarantine period to newly published versions. When enabled, the proxy strips versions from metadata responses until they've aged past a configurable threshold.
```yaml
cooldown:
default: "3d" # hide versions published less than 3 days ago
ecosystems:
npm: "7d" # npm gets a longer window
cargo: "0" # disable for cargo
packages:
"pkg:npm/lodash": "0" # exempt trusted packages
```
A 3-day cooldown means that when `lodash` publishes version `4.18.0`, your builds keep using `4.17.21` until 3 days have passed. If the new release turns out to be compromised, you were never exposed.
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.
## Supported Registries ## Supported Registries
| Registry | Language/Platform | Cooldown | Completed | | Registry | Language/Platform | URL Resolution | Handler | Completed |
|----------|-------------------|:--------:|:---------:| |----------|-------------------|:--------------:|:-------:|:---------:|
| npm | JavaScript | Yes | ✓ | | npm | JavaScript | Yes | Yes | ✓ |
| Cargo | Rust | Yes | ✓ | | Cargo | Rust | Yes | Yes | ✓ |
| RubyGems | Ruby | Yes | ✓ | | RubyGems | Ruby | Yes | Yes | ✓ |
| Go proxy | Go | | ✓ | | Go proxy | Go | Yes | Yes | ✓ |
| Hex | Elixir | Yes* | ✓ | | Hex | Elixir | Yes | Yes | ✓ |
| pub.dev | Dart | Yes | ✓ | | pub.dev | Dart | Yes | Yes | ✓ |
| PyPI | Python | Yes | ✓ | | PyPI | Python | Yes | Yes | ✓ |
| Maven | Java | | ✓ | | Maven | Java | Yes | Yes | ✓ |
| Gradle Build Cache | Java/Kotlin | | ✓ | | NuGet | .NET | Yes | Yes | ✓ |
| NuGet | .NET | Yes | ✓ | | Composer | PHP | Yes | Yes | ✓ |
| Composer | PHP | Yes | ✓ | | Conan | C/C++ | Yes | Yes | ✓ |
| Conan | C/C++ | | ✓ | | Conda | Python/R | Yes | Yes | ✓ |
| Conda | Python/R | Yes | ✓ | | CRAN | R | Yes | Yes | ✓ |
| CRAN | R | | ✓ | | Container | Docker/OCI | Yes | Yes | ✓ |
| Julia | Julia | | ✓ | | Debian | Debian/Ubuntu | Yes | Yes | ✓ |
| Container | Docker/OCI | | ✓ | | RPM | RHEL/Fedora | Yes | Yes | ✓ |
| Debian | Debian/Ubuntu | | ✓ | | Alpine | Alpine Linux | No | No | ✗ |
| RPM | RHEL/Fedora | | ✓ | | Arch | Arch Linux | No | No | ✗ |
| Alpine | Alpine Linux | | ✗ | | Chef | Chef | No | No | ✗ |
| Arch | Arch Linux | | ✗ | | Generic | Any | No | No | ✗ |
| Chef | Chef | | ✗ | | Helm | Kubernetes | No | No | ✗ |
| Generic | Any | | ✗ | | Swift | Swift | No | No | ✗ |
| Helm | Kubernetes | | ✗ | | Vagrant | Vagrant | No | No | ✗ |
| Swift | Swift | | ✗ |
| 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.
## Install
```bash
brew install git-pkgs/git-pkgs/proxy
```
Or download a binary from the [releases page](https://github.com/git-pkgs/proxy/releases).
## Quick Start ## Quick Start
@ -77,25 +45,6 @@ go build -o proxy ./cmd/proxy
The proxy is now running. Configure your package managers to use it. The proxy is now running. Configure your package managers to use it.
## OpenAPI (Swagger)
This repo uses swaggo to generate an OpenAPI spec from annotated handlers.
Generate the spec:
```bash
go install github.com/swaggo/swag/cmd/swag@latest
go generate ./internal/server
```
Generated files are written to `docs/swagger/`.
When the proxy is running, fetch the live spec from:
- `http://localhost:8080/openapi.json`
Or replace `http://localhost:8080` with your configured base URL. This link is also shown on the dashboard.
## Configuring Package Managers ## Configuring Package Managers
### npm ### npm
@ -210,34 +159,6 @@ Add to your `~/.m2/settings.xml`:
</settings> </settings>
``` ```
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.
For Gradle plugin resolution via the same proxy endpoint:
```kotlin
pluginManagement {
repositories {
maven(url = "http://localhost:8080/maven/")
}
}
```
### Gradle HTTP Build Cache
Configure in `settings.gradle(.kts)`:
```kotlin
buildCache {
local {
enabled = false
}
remote<HttpBuildCache> {
url = uri("http://localhost:8080/gradle/")
push = true
}
}
```
### NuGet ### NuGet
Configure in `nuget.config`: Configure in `nuget.config`:
@ -325,21 +246,6 @@ local({
}) })
``` ```
### Julia
Set the Pkg server before starting Julia:
```bash
export JULIA_PKG_SERVER=http://localhost:8080/julia
```
Or inside a running session:
```julia
ENV["JULIA_PKG_SERVER"] = "http://localhost:8080/julia"
using Pkg; Pkg.update()
```
### Docker / Container Registry ### Docker / Container Registry
Configure Docker to use the proxy as a registry mirror in `/etc/docker/daemon.json`: Configure Docker to use the proxy as a registry mirror in `/etc/docker/daemon.json`:
@ -362,39 +268,6 @@ Or pull images directly:
docker pull localhost:8080/library/nginx:latest docker pull localhost:8080/library/nginx:latest
``` ```
### Helm
Configure each HTTP chart repository with a name, then add the matching proxy
URL to Helm:
```yaml
upstream:
helm:
bitnami: "https://charts.bitnami.com/bitnami"
```
```bash
helm repo add bitnami http://localhost:8080/helm/bitnami
helm repo update
helm pull bitnami/nginx
```
The proxy caches `index.yaml` using the normal metadata-cache settings and
caches chart archives after verifying their SHA-256 digest from the index.
For charts stored in an OCI registry, configure a named OCI upstream and add
the reserved `upstream/{name}` prefix to the chart reference:
```yaml
upstream:
oci:
ghcr: "https://ghcr.io"
```
```bash
helm pull oci://localhost:8080/upstream/ghcr/owner/charts/mychart --version 1.0.0 --plain-http
```
### Debian / APT ### Debian / APT
Configure APT to use the proxy in `/etc/apt/sources.list.d/proxy.list`: Configure APT to use the proxy in `/etc/apt/sources.list.d/proxy.list`:
@ -409,13 +282,6 @@ Replace your existing sources.list entries, then:
sudo apt update sudo apt update
``` ```
The upstream defaults to `http://deb.debian.org/debian`. To proxy a different APT repository (e.g. Ubuntu), set `upstream.debian` in the config file or `PROXY_UPSTREAM_DEBIAN` in the environment:
```yaml
upstream:
debian: "http://archive.ubuntu.com/ubuntu"
```
### RPM / Yum / DNF ### RPM / Yum / DNF
Configure yum/dnf to use the proxy in `/etc/yum.repos.d/proxy.repo`: Configure yum/dnf to use the proxy in `/etc/yum.repos.d/proxy.repo`:
@ -438,7 +304,6 @@ sudo dnf update
## Configuration ## Configuration
The proxy can be configured via: The proxy can be configured via:
1. Command line flags (highest priority) 1. Command line flags (highest priority)
2. Environment variables 2. Environment variables
3. Configuration file (YAML or JSON) 3. Configuration file (YAML or JSON)
@ -446,18 +311,14 @@ The proxy can be configured via:
### Command Line Flags ### Command Line Flags
``` ```
-config string Path to configuration file -config string Path to configuration file
-listen string Address to listen on (default ":8080") -listen string Address to listen on (default ":8080")
-base-url string Public URL of this proxy (default "http://localhost:8080") -base-url string Public URL of this proxy (default "http://localhost:8080")
-storage-url string Storage URL (file:// or s3://) -storage string Path to artifact storage directory (default "./cache/artifacts")
-storage-path string Path to artifact storage directory (deprecated, use -storage-url) -database string Path to SQLite database file (default "./cache/proxy.db")
-database-driver string Database driver: sqlite or postgres (default "sqlite") -log-level string Log level: debug, info, warn, error (default "info")
-database-path string Path to SQLite database file (default "./cache/proxy.db") -log-format string Log format: text, json (default "text")
-database-url string PostgreSQL connection URL -version Print version and exit
-log-level string Log level: debug, info, warn, error (default "info")
-log-format string Log format: text, json (default "text")
-access-log string Path to the JSONL access log
-version Print version and exit
``` ```
### Environment Variables ### Environment Variables
@ -465,14 +326,10 @@ The proxy can be configured via:
```bash ```bash
PROXY_LISTEN=:8080 PROXY_LISTEN=:8080
PROXY_BASE_URL=http://localhost:8080 PROXY_BASE_URL=http://localhost:8080
PROXY_UI_URL=http://localhost:8080 # Optional; defaults to PROXY_BASE_URL PROXY_STORAGE_PATH=./cache/artifacts
PROXY_STORAGE_URL=file:///var/cache/proxy/artifacts
PROXY_DATABASE_DRIVER=sqlite
PROXY_DATABASE_PATH=./cache/proxy.db PROXY_DATABASE_PATH=./cache/proxy.db
PROXY_DATABASE_URL=postgres://user:pass@localhost/proxy?sslmode=disable
PROXY_LOG_LEVEL=info PROXY_LOG_LEVEL=info
PROXY_LOG_FORMAT=text PROXY_LOG_FORMAT=text
PROXY_ACCESS_LOG_PATH=/var/log/proxy/access.jsonl
``` ```
### Configuration File ### Configuration File
@ -482,28 +339,20 @@ listen: ":8080"
base_url: "http://localhost:8080" base_url: "http://localhost:8080"
storage: storage:
url: "file:///var/cache/proxy/artifacts" path: "/var/cache/proxy/artifacts"
max_size: "10GB" # Optional: evict LRU when exceeded max_size: "10GB" # Optional: evict LRU when exceeded
database: database:
driver: "sqlite"
path: "/var/lib/proxy/cache.db" path: "/var/lib/proxy/cache.db"
log: log:
level: "info" level: "info"
format: "text" format: "text"
access_log:
path: "/var/log/proxy/access.jsonl" # Optional JSONL activity log
# Optional: override upstream URLs # Optional: override upstream URLs
upstream: upstream:
npm: "https://registry.npmjs.org" npm: "https://registry.npmjs.org"
cargo: "https://index.crates.io" cargo: "https://index.crates.io"
# Optional: version cooldown (see above)
cooldown:
default: "3d"
``` ```
Run with config file: Run with config file:
@ -512,43 +361,6 @@ Run with config file:
./proxy -config /etc/proxy/config.yaml ./proxy -config /etc/proxy/config.yaml
``` ```
### 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:
```yaml
database:
driver: "postgres"
url: "postgres://user:password@localhost:5432/proxy?sslmode=disable"
```
Or via environment variables:
```bash
PROXY_DATABASE_DRIVER=postgres
PROXY_DATABASE_URL=postgres://user:password@localhost:5432/proxy?sslmode=disable
```
The proxy creates tables automatically on first run.
### S3 Storage
The proxy can store cached artifacts in S3 or any S3-compatible service (MinIO, R2, etc.) instead of the local filesystem.
```yaml
storage:
url: "s3://my-bucket-name?region=us-east-1"
```
For S3-compatible services like MinIO:
```yaml
storage:
url: "s3://my-bucket?endpoint=http://localhost:9000&disableSSL=true&s3ForcePathStyle=true"
```
Set credentials via standard AWS environment variables (`AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, `AWS_REGION`).
## CLI Commands ## CLI Commands
### serve (default) ### serve (default)
@ -560,44 +372,6 @@ proxy serve [flags]
proxy [flags] # same as 'proxy serve' proxy [flags] # same as 'proxy serve'
``` ```
### mirror
Pre-populate the cache from PURLs, SBOM files, or entire registries. Useful for ensuring offline availability or warming the cache before deployments.
```bash
# Mirror specific package versions
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 from a CycloneDX or SPDX SBOM
proxy mirror --sbom sbom.cdx.json
# Preview what would be mirrored
proxy mirror --dry-run pkg:npm/lodash
# Control parallelism
proxy mirror --concurrency 8 pkg:npm/lodash@4.17.21
```
The mirror command accepts the same storage and database flags as `serve`. Already-cached artifacts are skipped.
A mirror API is also available when the server is running:
```bash
# Start a mirror job
curl -X POST http://localhost:8080/api/mirror \
-H "Content-Type: application/json" \
-d '{"purls": ["pkg:npm/lodash@4.17.21"]}'
# Check job status
curl http://localhost:8080/api/mirror/mirror-1
# Cancel a running job
curl -X DELETE http://localhost:8080/api/mirror/mirror-1
```
### stats ### stats
Show cache statistics without running the server. Show cache statistics without running the server.
@ -610,10 +384,7 @@ proxy stats
proxy stats -json proxy stats -json
# Custom database path # Custom database path
proxy stats -database-path /var/lib/proxy/cache.db proxy stats -database /var/lib/proxy/cache.db
# With PostgreSQL
proxy stats -database-driver postgres -database-url postgres://user:pass@localhost/proxy
# Show top 20 most popular packages # Show top 20 most popular packages
proxy stats -popular 20 proxy stats -popular 20
@ -651,10 +422,9 @@ Recently cached:
| Endpoint | Description | | Endpoint | Description |
|----------|-------------| |----------|-------------|
| `GET /` | Dashboard (web UI) | | `GET /` | Welcome message and endpoint list |
| `GET /health` | Health check (JSON; HTTP 200 healthy, 503 unhealthy) | | `GET /health` | Health check (returns "ok" if healthy) |
| `GET /stats` | Cache statistics (JSON) | | `GET /stats` | Cache statistics (JSON) |
| `GET /metrics` | Prometheus metrics |
| `GET /npm/*` | npm registry protocol | | `GET /npm/*` | npm registry protocol |
| `GET /cargo/*` | Cargo sparse index protocol | | `GET /cargo/*` | Cargo sparse index protocol |
| `GET /gem/*` | RubyGems protocol | | `GET /gem/*` | RubyGems protocol |
@ -668,20 +438,10 @@ Recently cached:
| `GET /conan/*` | Conan C/C++ protocol | | `GET /conan/*` | Conan C/C++ protocol |
| `GET /conda/*` | Conda/Anaconda protocol | | `GET /conda/*` | Conda/Anaconda protocol |
| `GET /cran/*` | CRAN (R) protocol | | `GET /cran/*` | CRAN (R) protocol |
| `GET /julia/*` | Julia Pkg server protocol |
| `GET /helm/{repository}/*` | HTTP Helm chart repository protocol |
| `GET /v2/*` | OCI/Docker registry protocol | | `GET /v2/*` | OCI/Docker registry protocol |
| `GET /debian/*` | Debian/APT repository protocol | | `GET /debian/*` | Debian/APT repository protocol |
| `GET /rpm/*` | RPM/Yum repository protocol | | `GET /rpm/*` | RPM/Yum repository protocol |
### Mirror API
| Endpoint | Description |
|----------|-------------|
| `POST /api/mirror` | Start a mirror job (JSON body with `purls`) |
| `GET /api/mirror/{id}` | Get job status and progress |
| `DELETE /api/mirror/{id}` | Cancel a running job |
### Enrichment API ### Enrichment API
The proxy provides REST endpoints for package metadata enrichment, vulnerability scanning, and outdated detection. The proxy provides REST endpoints for package metadata enrichment, vulnerability scanning, and outdated detection.
@ -836,7 +596,7 @@ Response:
"cached_artifacts": 142, "cached_artifacts": 142,
"total_size_bytes": 523456789, "total_size_bytes": 523456789,
"total_size": "499.2 MB", "total_size": "499.2 MB",
"storage_url": "file:///path/to/cache/artifacts", "storage_path": "./cache/artifacts",
"database_path": "./cache/proxy.db" "database_path": "./cache/proxy.db"
} }
``` ```
@ -864,67 +624,6 @@ Response:
└─────────┘ └─────────┘
``` ```
## Web Interface
The proxy serves a web UI under `/ui`. No separate frontend build is needed -- templates and assets are embedded in the binary. `GET /` redirects to `/ui/`. The UI is mounted under its own prefix so a reverse proxy can apply different access rules to it than to the package endpoints (for example, requiring auth for `PathPrefix(/ui)` while leaving `/npm`, `/pypi` etc. open to build machines).
- **Dashboard** (`/ui/`) -- cache stats, popular packages, recently cached artifacts, and vulnerability overview.
- **Install guide** (`/ui/install`) -- per-ecosystem configuration instructions, so you don't have to look them up here.
- **Package browser** (`/ui/packages`) -- browse all cached packages with filtering by ecosystem and sorting by hits, size, name, or vulnerability count.
- **Search** (`/ui/search?q=...`) -- search cached packages by name.
- **Package detail** (`/ui/package/{ecosystem}/{name}`) -- metadata, license, vulnerabilities, and version list for a package. You can select two versions to compare.
- **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.
## Monitoring
The proxy exposes Prometheus metrics at `GET /metrics`. All metric names are prefixed with `proxy_`.
| Metric | Type | Labels | Description |
|--------|------|--------|-------------|
| `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_size_bytes` | gauge | | Total size of cached artifacts |
| `proxy_cached_artifacts_total` | gauge | | Number of cached artifacts |
| `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 |
| `proxy_storage_errors_total` | counter | `operation` | Storage read/write failures |
| `proxy_active_requests` | gauge | | In-flight requests |
| `proxy_health_probe_failures_total` | counter | `step` | Storage health probe failures by failing step (`write`, `size`, `read`, `verify`, `delete`). |
Cache size and artifact count are refreshed every 60 seconds. The remaining metrics update on each request.
### Health Check
`/health` returns a structured JSON report of subsystem health. HTTP 200 if all checks pass; 503 if any fail.
```json
{
"status": "ok",
"checks": {
"database": {"status": "ok"},
"storage": {"status": "ok"}
}
}
```
Failing checks include an `"error"` field. Storage failures also include a `"step"` field identifying which probe step failed (`write`, `size`, `read`, `verify`, `delete`). When the database check fails, the storage entry reports `{"status": "skipped"}` so the response always carries the same key set.
Storage probe results are cached for `health.storage_probe_interval` (default 30s) to bound the cost of probing remote backends. A probe holds an internal mutex for up to 10 seconds (the hardcoded per-probe timeout), so `/health` is intended as a Kubernetes **readiness** probe rather than a liveness probe — a slow S3 round-trip should pull the pod from rotation, not restart it.
Scrape config for Prometheus:
```yaml
scrape_configs:
- job_name: git-pkgs-proxy
static_configs:
- targets: ["localhost:8080"]
```
## Production Deployment ## Production Deployment
### Systemd Service ### Systemd Service
@ -956,25 +655,27 @@ sudo systemctl start proxy
### Docker ### Docker
A Dockerfile is included in the repo. Build and run: ```dockerfile
FROM golang:1.23-alpine AS build
WORKDIR /app
COPY . .
RUN go build -o proxy ./cmd/proxy
FROM alpine:latest
RUN apk --no-cache add ca-certificates
COPY --from=build /app/proxy /usr/local/bin/
EXPOSE 8080
VOLUME ["/data"]
CMD ["proxy", "-storage", "/data/artifacts", "-database", "/data/proxy.db"]
```
Build and run:
```bash ```bash
docker build -t proxy . docker build -t proxy .
docker run -p 8080:8080 -v proxy-data:/data proxy docker run -p 8080:8080 -v proxy-data:/data proxy
``` ```
With Postgres and S3:
```bash
docker run -p 8080:8080 \
-e PROXY_DATABASE_DRIVER=postgres \
-e PROXY_DATABASE_URL=postgres://user:pass@db:5432/proxy \
-e PROXY_STORAGE_URL=s3://my-bucket?region=us-east-1 \
-e AWS_ACCESS_KEY_ID=... \
-e AWS_SECRET_ACCESS_KEY=... \
proxy
```
### Behind a Reverse Proxy ### Behind a Reverse Proxy
When running behind nginx, Apache, or another reverse proxy, set `base_url` to your public URL: When running behind nginx, Apache, or another reverse proxy, set `base_url` to your public URL:
@ -983,47 +684,22 @@ When running behind nginx, Apache, or another reverse proxy, set `base_url` to y
base_url: "https://proxy.example.com" base_url: "https://proxy.example.com"
``` ```
If the UI is reached on a different hostname than the package endpoints — for example, the UI exposed publicly on a domain while build machines hit a Docker network alias — set `ui_base_url` separately. `base_url` is the URL package managers and metadata rewriting use; `ui_base_url` is the URL advertised to humans visiting the web UI (canonical/`og:url` tags and the install guide banner): nginx example:
```yaml
base_url: "http://pkg-proxy:8080" # internal alias for build machines
ui_base_url: "https://proxy.example.com/ui" # public UI URL
```
When unset, `ui_base_url` defaults to `base_url`.
> **Warning:** the proxy serves the UI and package endpoints on the same listener. Setting `ui_base_url` only changes what URL the UI advertises to humans; it does not stop package endpoints from being reachable on the same hostname and port. When fronting the proxy with a public reverse proxy, restrict the public route to `PathPrefix(/ui)` (or your proxy's equivalent), otherwise `/npm`, `/pypi`, and the other package endpoints stay exposed alongside the UI.
nginx example, restricting the public host to the UI while leaving package endpoints reachable only on the internal listener:
```nginx ```nginx
server { server {
listen 443 ssl; listen 443 ssl;
server_name proxy.example.com; server_name proxy.example.com;
location /ui/ { location / {
proxy_pass http://127.0.0.1:8080; proxy_pass http://127.0.0.1:8080;
proxy_set_header Host $host; proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Real-IP $remote_addr;
proxy_buffering off; proxy_buffering off;
} }
location / {
return 404;
}
} }
``` ```
Traefik example using `PathPrefix(/ui)` so the public router only matches UI traffic:
```yaml
labels:
traefik.enable: "true"
traefik.http.services.pkg-proxy.loadbalancer.server.port: "8080"
traefik.http.routers.pkg-proxy.rule: "Host(`proxy.example.com`) && PathPrefix(`/ui`)"
traefik.http.routers.pkg-proxy.entrypoints: "websecure"
```
## Cache Management ## Cache Management
The proxy stores artifacts in the configured storage directory with this structure: The proxy stores artifacts in the configured storage directory with this structure:
@ -1052,7 +728,7 @@ cache/artifacts/
└── nginx-1.24.0-1.fc39.x86_64.rpm └── nginx-1.24.0-1.fc39.x86_64.rpm
``` ```
Cache metadata is stored in SQLite (default) or PostgreSQL. To clear a local cache: Cache metadata is stored in an SQLite database. To clear the cache:
```bash ```bash
rm -rf ./cache/artifacts/* rm -rf ./cache/artifacts/*
@ -1064,8 +740,7 @@ The proxy will recreate the database on next start.
## Building from Source ## Building from Source
Requirements: Requirements:
- Go 1.23 or later
- Go (the project version is declared in `go.mod`)
```bash ```bash
git clone https://github.com/git-pkgs/proxy.git git clone https://github.com/git-pkgs/proxy.git

View file

@ -1,10 +1,5 @@
// Command proxy runs the git-pkgs package registry proxy server. // Command proxy runs the git-pkgs package registry proxy server.
// //
// @title git-pkgs proxy API
// @version 0.1.0
// @description HTTP API for package enrichment, vulnerability lookup, cache stats, and source browsing.
// @BasePath /
//
// The proxy caches package artifacts from upstream registries (npm, cargo, etc.) // The proxy caches package artifacts from upstream registries (npm, cargo, etc.)
// providing faster, more reliable access for development teams. // providing faster, more reliable access for development teams.
// //
@ -16,7 +11,6 @@
// //
// serve Start the proxy server (default if no command given) // serve Start the proxy server (default if no command given)
// stats Show cache statistics // stats Show cache statistics
// mirror Pre-populate cache from PURLs, SBOMs, or registries
// //
// Serve Flags: // Serve Flags:
// //
@ -40,8 +34,6 @@
// Log level: debug, info, warn, error (default "info") // Log level: debug, info, warn, error (default "info")
// -log-format string // -log-format string
// Log format: text, json (default "text") // Log format: text, json (default "text")
// -access-log string
// Path to the JSONL access log (disabled by default)
// //
// Stats Flags: // Stats Flags:
// //
@ -74,15 +66,6 @@
// PROXY_DATABASE_URL - PostgreSQL connection URL // PROXY_DATABASE_URL - PostgreSQL connection URL
// PROXY_LOG_LEVEL - Log level // PROXY_LOG_LEVEL - Log level
// PROXY_LOG_FORMAT - Log format // PROXY_LOG_FORMAT - Log format
// PROXY_ACCESS_LOG_PATH - JSONL access log path
// PROXY_UPSTREAM_MAVEN - Maven repository upstream URL
// PROXY_UPSTREAM_GRADLE_PLUGIN_PORTAL - Gradle Plugin Portal upstream URL
// PROXY_GRADLE_BUILD_CACHE_READ_ONLY - Disable Gradle PUT uploads
// 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
// PROXY_GRADLE_BUILD_CACHE_SWEEP_INTERVAL - Gradle cache eviction sweep interval
// PROXY_HEALTH_STORAGE_PROBE_INTERVAL - Storage health probe cache interval (default "30s")
// //
// Example: // Example:
// //
@ -112,15 +95,9 @@ import (
"github.com/git-pkgs/proxy/internal/config" "github.com/git-pkgs/proxy/internal/config"
"github.com/git-pkgs/proxy/internal/database" "github.com/git-pkgs/proxy/internal/database"
"github.com/git-pkgs/proxy/internal/handler"
"github.com/git-pkgs/proxy/internal/mirror"
"github.com/git-pkgs/proxy/internal/server" "github.com/git-pkgs/proxy/internal/server"
"github.com/git-pkgs/proxy/internal/storage"
"github.com/git-pkgs/registries/fetch"
) )
const defaultTopN = 10
var ( var (
// Version is set at build time. // Version is set at build time.
Version = "dev" Version = "dev"
@ -140,10 +117,6 @@ func main() {
os.Args = append(os.Args[:1], os.Args[2:]...) os.Args = append(os.Args[:1], os.Args[2:]...)
runStats() runStats()
return return
case "mirror":
os.Args = append(os.Args[:1], os.Args[2:]...)
runMirror()
return
case "-version", "--version": case "-version", "--version":
fmt.Printf("proxy %s (%s)\n", Version, Commit) fmt.Printf("proxy %s (%s)\n", Version, Commit)
os.Exit(0) os.Exit(0)
@ -165,7 +138,6 @@ Usage: proxy [command] [flags]
Commands: Commands:
serve Start the proxy server (default) serve Start the proxy server (default)
stats Show cache statistics stats Show cache statistics
mirror Pre-populate cache from PURLs, SBOMs, or registries
Run 'proxy <command> -help' for more information on a command. Run 'proxy <command> -help' for more information on a command.
@ -187,7 +159,6 @@ func runServe() {
databaseURL := fs.String("database-url", "", "PostgreSQL connection URL") databaseURL := fs.String("database-url", "", "PostgreSQL connection URL")
logLevel := fs.String("log-level", "", "Log level: debug, info, warn, error") logLevel := fs.String("log-level", "", "Log level: debug, info, warn, error")
logFormat := fs.String("log-format", "", "Log format: text, json") logFormat := fs.String("log-format", "", "Log format: text, json")
accessLogPath := fs.String("access-log", "", "Path to the JSONL access log")
version := fs.Bool("version", false, "Print version and exit") version := fs.Bool("version", false, "Print version and exit")
fs.Usage = func() { fs.Usage = func() {
@ -205,15 +176,6 @@ func runServe() {
fmt.Fprintf(os.Stderr, " PROXY_DATABASE_URL PostgreSQL connection URL\n") fmt.Fprintf(os.Stderr, " PROXY_DATABASE_URL PostgreSQL connection URL\n")
fmt.Fprintf(os.Stderr, " PROXY_LOG_LEVEL Log level\n") fmt.Fprintf(os.Stderr, " PROXY_LOG_LEVEL Log level\n")
fmt.Fprintf(os.Stderr, " PROXY_LOG_FORMAT Log format\n") fmt.Fprintf(os.Stderr, " PROXY_LOG_FORMAT Log format\n")
fmt.Fprintf(os.Stderr, " PROXY_ACCESS_LOG_PATH JSONL access log path\n")
fmt.Fprintf(os.Stderr, " PROXY_UPSTREAM_MAVEN Maven repository upstream URL\n")
fmt.Fprintf(os.Stderr, " PROXY_UPSTREAM_GRADLE_PLUGIN_PORTAL Gradle Plugin Portal 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_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")
fmt.Fprintf(os.Stderr, " PROXY_GRADLE_BUILD_CACHE_SWEEP_INTERVAL Gradle cache eviction sweep interval\n")
fmt.Fprintf(os.Stderr, " PROXY_HEALTH_STORAGE_PROBE_INTERVAL Storage health probe cache interval\n")
} }
_ = fs.Parse(os.Args[1:]) _ = fs.Parse(os.Args[1:])
@ -244,7 +206,7 @@ func runServe() {
cfg.Storage.URL = *storageURL cfg.Storage.URL = *storageURL
} }
if *storagePath != "" { if *storagePath != "" {
cfg.Storage.Path = *storagePath //nolint:staticcheck // backwards compat cfg.Storage.Path = *storagePath
} }
if *databaseDriver != "" { if *databaseDriver != "" {
cfg.Database.Driver = *databaseDriver cfg.Database.Driver = *databaseDriver
@ -261,9 +223,6 @@ func runServe() {
if *logFormat != "" { if *logFormat != "" {
cfg.Log.Format = *logFormat cfg.Log.Format = *logFormat
} }
if *accessLogPath != "" {
cfg.AccessLog.Path = *accessLogPath
}
// Validate configuration // Validate configuration
if err := cfg.Validate(); err != nil { if err := cfg.Validate(); err != nil {
@ -275,10 +234,7 @@ func runServe() {
logger := setupLogger(cfg.Log.Level, cfg.Log.Format) logger := setupLogger(cfg.Log.Level, cfg.Log.Format)
// Create and start server // Create and start server
srv, err := server.New(cfg, logger, server.BuildInfo{ srv, err := server.New(cfg, logger)
Version: Version,
Commit: Commit,
})
if err != nil { if err != nil {
logger.Error("failed to create server", "error", err) logger.Error("failed to create server", "error", err)
os.Exit(1) os.Exit(1)
@ -286,6 +242,7 @@ func runServe() {
// Handle shutdown signals // Handle shutdown signals
ctx, cancel := context.WithCancel(context.Background()) ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go func() { go func() {
sigCh := make(chan os.Signal, 1) sigCh := make(chan os.Signal, 1)
@ -304,12 +261,10 @@ func runServe() {
// Wait for shutdown or error // Wait for shutdown or error
select { select {
case <-ctx.Done(): case <-ctx.Done():
cancel()
if err := srv.Shutdown(context.Background()); err != nil { if err := srv.Shutdown(context.Background()); err != nil {
logger.Error("shutdown error", "error", err) logger.Error("shutdown error", "error", err)
} }
case err := <-errCh: case err := <-errCh:
cancel()
if err != nil { if err != nil {
logger.Error("server error", "error", err) logger.Error("server error", "error", err)
os.Exit(1) os.Exit(1)
@ -323,8 +278,8 @@ func runStats() {
databasePath := fs.String("database-path", "./cache/proxy.db", "Path to SQLite database file") databasePath := fs.String("database-path", "./cache/proxy.db", "Path to SQLite database file")
databaseURL := fs.String("database-url", "", "PostgreSQL connection URL") databaseURL := fs.String("database-url", "", "PostgreSQL connection URL")
asJSON := fs.Bool("json", false, "Output as JSON") asJSON := fs.Bool("json", false, "Output as JSON")
popular := fs.Int("popular", defaultTopN, "Show top N most popular packages") popular := fs.Int("popular", 10, "Show top N most popular packages")
recent := fs.Int("recent", defaultTopN, "Show N recently cached packages") recent := fs.Int("recent", 10, "Show N recently cached packages")
fs.Usage = func() { fs.Usage = func() {
fmt.Fprintf(os.Stderr, "git-pkgs proxy - Show cache statistics\n\n") fmt.Fprintf(os.Stderr, "git-pkgs proxy - Show cache statistics\n\n")
@ -366,187 +321,36 @@ func runStats() {
db, err = database.Open(*databasePath) db, err = database.Open(*databasePath)
} }
if err != nil {
fmt.Fprintf(os.Stderr, "error opening database: %v\n", err)
os.Exit(1)
}
if err := printStats(db, *popular, *recent, *asJSON); err != nil {
fmt.Fprintf(os.Stderr, "%v\n", err)
os.Exit(1)
}
}
func runMirror() {
fs := flag.NewFlagSet("mirror", flag.ExitOnError)
configPath := fs.String("config", "", "Path to configuration file")
storageURL := fs.String("storage-url", "", "Storage URL (file:// or s3://)")
databaseDriver := fs.String("database-driver", "", "Database driver: sqlite or postgres")
databasePath := fs.String("database-path", "", "Path to SQLite database file")
databaseURL := fs.String("database-url", "", "PostgreSQL connection URL")
sbomPath := fs.String("sbom", "", "Path to CycloneDX or SPDX SBOM file")
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")
fs.Usage = func() {
fmt.Fprintf(os.Stderr, "git-pkgs proxy - Pre-populate cache\n\n")
fmt.Fprintf(os.Stderr, "Usage: proxy mirror [flags] [purl...]\n\n")
fmt.Fprintf(os.Stderr, "Examples:\n")
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\n")
fmt.Fprintf(os.Stderr, "Flags:\n")
fs.PrintDefaults()
}
_ = fs.Parse(os.Args[1:])
purls := fs.Args()
// Determine source
var source mirror.Source
switch {
case *sbomPath != "":
source = &mirror.SBOMSource{Path: *sbomPath}
case len(purls) > 0:
source = &mirror.PURLSource{PURLs: purls}
default:
fmt.Fprintf(os.Stderr, "error: provide PURLs or --sbom\n")
fs.Usage()
os.Exit(1)
}
// Load config
cfg, err := loadConfig(*configPath)
if err != nil {
fmt.Fprintf(os.Stderr, "error loading config: %v\n", err)
os.Exit(1)
}
cfg.LoadFromEnv()
if *storageURL != "" {
cfg.Storage.URL = *storageURL
}
if *databaseDriver != "" {
cfg.Database.Driver = *databaseDriver
}
if *databasePath != "" {
cfg.Database.Path = *databasePath
}
if *databaseURL != "" {
cfg.Database.URL = *databaseURL
}
if err := cfg.Validate(); err != nil {
fmt.Fprintf(os.Stderr, "invalid configuration: %v\n", err)
os.Exit(1)
}
logger := setupLogger("info", "text")
// Open database
var db *database.DB
switch cfg.Database.Driver {
case "postgres":
db, err = database.OpenPostgresOrCreate(cfg.Database.URL)
default:
db, err = database.OpenOrCreate(cfg.Database.Path)
}
if err != nil { if err != nil {
fmt.Fprintf(os.Stderr, "error opening database: %v\n", err) fmt.Fprintf(os.Stderr, "error opening database: %v\n", err)
os.Exit(1) os.Exit(1)
} }
defer func() { _ = db.Close() }() defer func() { _ = db.Close() }()
if err := db.MigrateSchema(); err != nil { // Get stats
_ = db.Close()
fmt.Fprintf(os.Stderr, "error migrating schema: %v\n", err)
os.Exit(1) //nolint:gocritic // db closed above
}
// Open storage
sURL := cfg.Storage.URL
if sURL == "" {
sURL = "file://" + cfg.Storage.Path //nolint:staticcheck // backwards compat
}
store, err := storage.OpenBucket(context.Background(), sURL)
if err != nil {
_ = db.Close()
fmt.Fprintf(os.Stderr, "error opening storage: %v\n", err)
os.Exit(1) //nolint:gocritic // db closed above
}
// Build proxy (reuses same pipeline as serve)
fetcher := fetch.NewFetcher()
resolver := fetch.NewResolver()
proxy := handler.NewProxy(db, store, fetcher, resolver, logger)
proxy.CacheMetadata = true // mirror always caches metadata
proxy.MetadataTTL = cfg.ParseMetadataTTL()
proxy.MetadataMaxSize = cfg.ParseMetadataMaxSize()
m := mirror.New(proxy, db, store, logger, *concurrency)
ctx, cancel := context.WithCancel(context.Background())
go func() {
sigCh := make(chan os.Signal, 1)
signal.Notify(sigCh, syscall.SIGINT, syscall.SIGTERM)
<-sigCh
cancel()
}()
if *dryRun {
items, err := m.RunDryRun(ctx, source)
if err != nil {
fmt.Fprintf(os.Stderr, "error: %v\n", err)
os.Exit(1)
}
fmt.Printf("Would mirror %d package versions:\n", len(items))
for _, item := range items {
fmt.Printf(" %s\n", item)
}
return
}
progress, err := m.Run(ctx, source)
if err != nil {
fmt.Fprintf(os.Stderr, "error: %v\n", err)
os.Exit(1)
}
fmt.Printf("Mirror complete: %d downloaded, %d skipped (cached), %d failed, %s total\n",
progress.Completed, progress.Skipped, progress.Failed, formatSize(progress.Bytes))
if len(progress.Errors) > 0 {
fmt.Fprintf(os.Stderr, "\nErrors:\n")
for _, e := range progress.Errors {
fmt.Fprintf(os.Stderr, " %s/%s@%s: %s\n", e.Ecosystem, e.Name, e.Version, e.Error)
}
}
}
func printStats(db *database.DB, popular, recent int, asJSON bool) error {
defer func() { _ = db.Close() }()
stats, err := db.GetCacheStats() stats, err := db.GetCacheStats()
if err != nil { if err != nil {
return fmt.Errorf("error getting stats: %w", err) fmt.Fprintf(os.Stderr, "error getting stats: %v\n", err)
os.Exit(1)
} }
popularPkgs, err := db.GetMostPopularPackages(popular) popularPkgs, err := db.GetMostPopularPackages(*popular)
if err != nil { if err != nil {
return fmt.Errorf("error getting popular packages: %w", err) fmt.Fprintf(os.Stderr, "error getting popular packages: %v\n", err)
os.Exit(1)
} }
recentPkgs, err := db.GetRecentlyCachedPackages(recent) recentPkgs, err := db.GetRecentlyCachedPackages(*recent)
if err != nil { if err != nil {
return fmt.Errorf("error getting recent packages: %w", err) fmt.Fprintf(os.Stderr, "error getting recent packages: %v\n", err)
os.Exit(1)
} }
if asJSON { if *asJSON {
outputJSON(stats, popularPkgs, recentPkgs) outputJSON(stats, popularPkgs, recentPkgs)
} else { } else {
outputText(stats, popularPkgs, recentPkgs) outputText(stats, popularPkgs, recentPkgs)
} }
return nil
} }
type jsonOutput struct { type jsonOutput struct {

View file

@ -4,22 +4,10 @@
# Server listen address # Server listen address
listen: ":8080" listen: ":8080"
# Public URL where package endpoints are reachable. # Public URL where this proxy is accessible
# Used for rewriting package metadata URLs and shown in install guide snippets # Used for rewriting package metadata URLs
# so users know what to point their package manager at.
base_url: "http://localhost:8080" base_url: "http://localhost:8080"
# Timeout for individual upstream HTTP requests made by protocol handlers
# (metadata fetches, pass-through file requests). Uses Go duration syntax.
# Set to "0" to disable the timeout. Default: "30s".
# http_timeout: "30s"
# Public URL where the web UI is reached. Defaults to base_url when unset.
# Set this separately when the UI is served on a different hostname than the
# package endpoints — for example, the UI on a public domain behind auth while
# build machines hit a Docker network alias for the package endpoints.
# ui_base_url: "https://proxy.example.com/ui"
# Artifact storage configuration # Artifact storage configuration
storage: storage:
# Storage backend URL # Storage backend URL
@ -41,23 +29,6 @@ storage:
# Empty or "0" means unlimited # Empty or "0" means unlimited
max_size: "" max_size: ""
# Redirect cached artifact downloads to presigned storage URLs (HTTP 302)
# instead of streaming through the proxy. Only effective for S3 and Azure.
# Leave disabled if clients reach the proxy through an authenticating gateway,
# since presigned URLs bypass it.
direct_serve: false
# How long presigned URLs remain valid (e.g. "5m", "1h"). Default: "15m".
direct_serve_ttl: "15m"
# Public base URL to substitute into presigned URLs. Set this when the
# proxy reaches storage at an internal address (127.0.0.1, a Docker
# service name) but clients must use a public hostname. Only scheme and
# host are used; the signed path and query are preserved. For S3/MinIO
# the reverse proxy at this address must forward requests with the
# internal Host header or the SigV4 signature will not validate.
# direct_serve_base_url: "https://minio.example.com"
# Database configuration # Database configuration
database: database:
# Database driver: "sqlite" (default) or "postgres" # Database driver: "sqlite" (default) or "postgres"
@ -78,42 +49,19 @@ log:
# Log format: "text" or "json" # Log format: "text" or "json"
format: "text" format: "text"
# JSONL access log. Leave path empty to disable it.
access_log:
path: ""
# Upstream registry URLs and authentication # Upstream registry URLs and authentication
upstream: upstream:
# npm registry URL # npm registry URL
npm: "https://registry.npmjs.org" npm: "https://registry.npmjs.org"
# Maven repository URL (used by /maven endpoint)
maven: "https://repo1.maven.org/maven2"
# Gradle Plugin Portal Maven URL (fallback for plugin marker artifacts)
gradle_plugin_portal: "https://plugins.gradle.org/m2"
# Cargo sparse index URL # Cargo sparse index URL
cargo: "https://index.crates.io" cargo: "https://index.crates.io"
# Cargo crate download URL # Cargo crate download URL
cargo_download: "https://static.crates.io/crates" cargo_download: "https://static.crates.io/crates"
# Debian/APT repository URL (used by /debian endpoint)
debian: "http://deb.debian.org/debian"
# Named HTTP Helm chart repositories (used by /helm/{name}/)
# helm:
# bitnami: "https://charts.bitnami.com/bitnami"
# Named OCI registries. Use the upstream/{name}/ repository prefix, e.g.
# oci://proxy.example.com/upstream/ghcr/owner/chart.
# oci:
# ghcr: "https://ghcr.io"
# Authentication for upstream registries # Authentication for upstream registries
# Keys are absolute URL scopes. Scheme, host, effective port, and path # Keys are URL prefixes matched against request URLs.
# segment boundaries must match; the longest matching scope wins.
# Values can reference environment variables using ${VAR_NAME} syntax. # Values can reference environment variables using ${VAR_NAME} syntax.
# #
# Supported auth types: # Supported auth types:
@ -142,51 +90,3 @@ upstream:
# type: header # type: header
# header_name: "X-Auth-Token" # header_name: "X-Auth-Token"
# header_value: "${MAVEN_TOKEN}" # header_value: "${MAVEN_TOKEN}"
# Gradle HttpBuildCache configuration
gradle:
build_cache:
# Set to true to disable PUT uploads (read-only cache mode)
read_only: false
# Maximum accepted Gradle cache upload body size
# Required and must be > 0
max_upload_size: "100MB"
# Evict entries older than this age (set to "0" to disable age-based eviction)
max_age: "168h"
# Cap total Gradle cache size; oldest entries are deleted first
# ("0" disables size-based eviction)
# max_size: "20GB"
# How often eviction runs when max_age or max_size is set
sweep_interval: "10m"
# Health endpoint configuration.
health:
# Minimum time between storage backend probes.
# The /health endpoint runs a write/read/verify/delete round-trip
# against the configured storage backend and caches the result for
# this interval. Set to "0" to probe on every request.
# Default: "30s".
storage_probe_interval: "30s"
# Version cooldown configuration
# Hides package versions published too recently, giving the community time
# to spot malicious releases before they're pulled into projects.
# Supported durations: "7d" (days), "48h" (hours), "30m" (minutes), "0" (disabled)
cooldown:
# Global default cooldown for all ecosystems
# default: "3d"
# Per-ecosystem overrides
# ecosystems:
# npm: "7d"
# cargo: "0"
# Per-package overrides (keyed by PURL). Keys are normalized, so npm scopes
# may use either @scope or the canonical %40scope form.
# packages:
# "pkg:npm/lodash": "0"
# "pkg:npm/@babel/core": "14d"

View file

@ -7,24 +7,29 @@ This document describes the internal architecture of the git-pkgs proxy.
The proxy is a caching HTTP server that sits between package manager clients and upstream registries. It intercepts requests, checks a local cache, and either serves cached content or fetches from upstream. The proxy is a caching HTTP server that sits between package manager clients and upstream registries. It intercepts requests, checks a local cache, and either serves cached content or fetches from upstream.
``` ```
┌──────────────────────────────────────────────────────────────────┐ ┌─────────────────────────────────────────────────────────────────┐
│ HTTP Server │ │ HTTP Server │
│ ┌──────────────────────────────────────────────────────────┐ │ │ ┌─────────────────────────────────────────────────────────┐ │
│ │ Router (Chi) │ │ │ │ Router (ServeMux) │ │
│ │ /npm/* -> NPMHandler /health -> healthHandler │ │ │ │ /npm/* -> NPMHandler │ │
│ │ /cargo/* -> CargoHandler /stats -> statsHandler │ │ │ │ /cargo/* -> CargoHandler │ │
│ │ /gem/* -> GemHandler /metrics -> prometheus │ │ │ │ /health -> healthHandler │ │
│ │ ...17 ecosystems /api/* -> APIHandler │ │ │ │ /stats -> statsHandler │ │
│ │ /ui/* -> Web UI │ │ │ └─────────────────────────────────────────────────────────┘ │
│ └──────────────────────────────────────────────────────────┘ │ │ │ │
│ │ │ │ │ │ ▼ │
│ ▼ ▼ ▼ │ │ ┌─────────────────────────────────────────────────────────┐ │
│ │ Proxy │ │
│ │ - GetOrFetchArtifact() │ │
│ │ - Coordinates DB, Storage, Fetcher │ │
│ └─────────────────────────────────────────────────────────┘ │
│ │ │ │ │
│ ▼ ▼ ▼ │
│ ┌───────────┐ ┌─────────────┐ ┌─────────────┐ │ │ ┌───────────┐ ┌─────────────┐ ┌─────────────┐ │
│ │ Database │ │ Storage │ │ Upstream │ │ │ │ Database │ │ Storage │ │ Upstream │ │
│ │ SQLite or │ │ Filesystem │ │ Registries │ │ │ │ (SQLite) │ │ (Filesystem)│ │ (Fetcher) │ │
│ │ Postgres │ │ or S3 │ │ (Fetcher) │ │
│ └───────────┘ └─────────────┘ └─────────────┘ │ │ └───────────┘ └─────────────┘ └─────────────┘ │
└──────────────────────────────────────────────────────────────────┘ └─────────────────────────────────────────────────────────────────┘
``` ```
## Request Flow ## Request Flow
@ -86,101 +91,29 @@ Metadata is not cached - always fetched fresh. This ensures clients see new vers
### `internal/database` ### `internal/database`
SQLite or PostgreSQL database for cache metadata. SQLite uses `modernc.org/sqlite` (pure Go, no CGO). PostgreSQL uses `lib/pq`. SQLite database for cache metadata. Uses `modernc.org/sqlite` (pure Go, no CGO).
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:** **Tables:**
```sql ```sql
packages ( packages (
id INTEGER PRIMARY KEY, -- SERIAL on Postgres id, purl, ecosystem, name, namespace, latest_version,
purl TEXT NOT NULL, -- unique, e.g. pkg:npm/lodash license, description, homepage, repository_url, upstream_url,
ecosystem TEXT NOT NULL, metadata_fetched_at, created_at, updated_at
name TEXT NOT NULL,
latest_version TEXT,
license TEXT,
description TEXT,
homepage TEXT,
repository_url TEXT,
registry_url TEXT,
supplier_name TEXT,
supplier_type TEXT,
source TEXT,
enriched_at DATETIME,
vulns_synced_at DATETIME,
created_at DATETIME,
updated_at DATETIME
) )
-- indexes: purl (unique), (ecosystem, name)
versions ( versions (
id INTEGER PRIMARY KEY, id, purl, package_id, version, license, integrity,
purl TEXT NOT NULL, -- unique, e.g. pkg:npm/lodash@4.17.21 published_at, yanked, metadata_fetched_at, created_at, updated_at
package_purl TEXT NOT NULL, -- FK to packages.purl
license TEXT,
published_at DATETIME,
integrity TEXT, -- subresource integrity hash
yanked INTEGER DEFAULT 0, -- BOOLEAN on Postgres
source TEXT,
enriched_at DATETIME,
created_at DATETIME,
updated_at DATETIME
) )
-- indexes: purl (unique), package_purl
artifacts ( artifacts (
id INTEGER PRIMARY KEY, id, version_id, filename, upstream_url, storage_path,
version_purl TEXT NOT NULL, content_hash, size, content_type, fetched_at,
filename TEXT NOT NULL, hit_count, last_accessed_at, created_at, updated_at
upstream_url TEXT NOT NULL,
storage_path TEXT, -- null until cached
content_hash TEXT, -- SHA-256
size INTEGER, -- BIGINT on Postgres
content_type TEXT,
fetched_at DATETIME,
hit_count INTEGER DEFAULT 0, -- BIGINT on Postgres
last_accessed_at DATETIME,
created_at DATETIME,
updated_at DATETIME
) )
-- indexes: (version_purl, filename) unique, storage_path, last_accessed_at
vulnerabilities (
id INTEGER PRIMARY KEY,
vuln_id TEXT NOT NULL, -- e.g. CVE-2021-1234
ecosystem TEXT NOT NULL,
package_name TEXT NOT NULL,
severity TEXT,
summary TEXT,
fixed_version TEXT,
cvss_score REAL,
"references" TEXT, -- JSON array
fetched_at DATETIME,
created_at DATETIME,
updated_at DATETIME
)
-- indexes: (vuln_id, ecosystem, package_name) unique, (ecosystem, package_name)
metadata_cache (
id INTEGER PRIMARY KEY,
ecosystem TEXT NOT NULL,
name TEXT NOT NULL,
storage_path TEXT NOT NULL,
etag TEXT,
content_type TEXT,
size INTEGER, -- BIGINT on Postgres
fetched_at DATETIME,
created_at DATETIME,
updated_at DATETIME
)
-- indexes: (ecosystem, name) unique
``` ```
On PostgreSQL, `INTEGER PRIMARY KEY` becomes `SERIAL`, `DATETIME` becomes `TIMESTAMP`, `INTEGER DEFAULT 0` booleans become `BOOLEAN DEFAULT FALSE`, and size/count columns use `BIGINT`.
The `MigrateSchema()` function handles backward compatibility with older git-pkgs databases by running named migrations that add missing columns and tables. See [migrations.md](migrations.md) for how to add new schema changes.
**Key operations:** **Key operations:**
- `GetPackageByPURL()` - Look up package by PURL - `GetPackageByPURL()` - Look up package by PURL
- `GetVersionByPURL()` - Look up version by PURL - `GetVersionByPURL()` - Look up version by PURL
@ -188,7 +121,6 @@ The `MigrateSchema()` function handles backward compatibility with older git-pkg
- `UpsertPackage/Version/Artifact()` - Insert or update records - `UpsertPackage/Version/Artifact()` - Insert or update records
- `RecordArtifactHit()` - Increment hit counter, update access time - `RecordArtifactHit()` - Increment hit counter, update access time
- `GetLeastRecentlyUsedArtifacts()` - For cache eviction - `GetLeastRecentlyUsedArtifacts()` - For cache eviction
- `SearchPackages()` - Full-text search across cached packages
### `internal/storage` ### `internal/storage`
@ -240,8 +172,6 @@ Fetches artifacts from upstream registries.
- Exponential backoff retry on 429 (rate limit) and 5xx errors - Exponential backoff retry on 429 (rate limit) and 5xx errors
- Returns streaming reader (doesn't load into memory) - Returns streaming reader (doesn't load into memory)
- Configurable user-agent - Configurable user-agent
- Shares an authentication-aware transport with metadata requests so URL-scoped credentials apply consistently
- Discovers and caches scoped OCI Bearer tokens from registry challenges
**Resolver:** **Resolver:**
- Determines download URL for a package/version - Determines download URL for a package/version
@ -271,33 +201,12 @@ HTTP protocol handlers for each registry type.
### `internal/server` ### `internal/server`
HTTP server setup, web UI, and API handlers. HTTP server setup.
- Creates and wires together all components - Creates and wires together all components
- Mounts protocol handlers at ecosystem-specific paths - Mounts handlers at appropriate paths
- Middleware: request ID, real IP, logging, panic recovery, active request tracking - Adds logging middleware
- Web UI under `/ui`: dashboard, package browser, source browser, version comparison - Health and stats endpoints
- Templates are embedded in the binary via `//go:embed`
- 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.
### `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.
### `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.
### `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.
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/config` ### `internal/config`
@ -348,12 +257,10 @@ Eviction can be implemented as:
- Ensures clients fetch artifacts through proxy - Ensures clients fetch artifacts through proxy
- Alternative: Let clients fetch directly, miss cache opportunity - Alternative: Let clients fetch directly, miss cache opportunity
**Why not cache metadata (by default)?** **Why not cache metadata?**
- Simplicity - no invalidation logic needed - Simplicity - no invalidation logic needed
- Fresh data - new versions visible immediately - Fresh data - new versions visible immediately
- Metadata is small, upstream fetch is fast - Metadata is small, upstream fetch is fast
- Set `cache_metadata: true` or use the mirror command to enable metadata caching for offline use via the `metadata_cache` table
- OCI manifests are the exception: they are cached automatically so previously fetched images remain pullable when the registry or token service is unavailable
**Why stream artifacts?** **Why stream artifacts?**
- Memory efficient - don't load large files into RAM - Memory efficient - don't load large files into RAM

View file

@ -17,8 +17,7 @@ See `config.example.yaml` in the repository root for a complete example.
| Config | Environment | Flag | Default | Description | | Config | Environment | Flag | Default | Description |
|--------|-------------|------|---------|-------------| |--------|-------------|------|---------|-------------|
| `listen` | `PROXY_LISTEN` | `-listen` | `:8080` | Address to listen on | | `listen` | `PROXY_LISTEN` | `-listen` | `:8080` | Address to listen on |
| `base_url` | `PROXY_BASE_URL` | `-base-url` | `http://localhost:8080` | Public URL package managers use to reach this proxy | | `base_url` | `PROXY_BASE_URL` | `-base-url` | `http://localhost:8080` | Public URL for the proxy |
| `ui_base_url` | `PROXY_UI_URL` | - | (defaults to `base_url`) | Public URL where the web UI is reached. Set separately when the UI lives behind a different hostname than package endpoints (e.g. public domain vs Docker network alias). Used for canonical/og:url tags and the install guide banner. The proxy still serves package endpoints on the same listener, so any reverse proxy fronting the UI publicly should restrict the public route to `PathPrefix(/ui)` to avoid exposing package endpoints. |
## Storage ## Storage
@ -108,30 +107,6 @@ log:
| `log.level` | `PROXY_LOG_LEVEL` | `-log-level` | `debug`, `info`, `warn`, `error` | | `log.level` | `PROXY_LOG_LEVEL` | `-log-level` | `debug`, `info`, `warn`, `error` |
| `log.format` | `PROXY_LOG_FORMAT` | `-log-format` | `text`, `json` | | `log.format` | `PROXY_LOG_FORMAT` | `-log-format` | `text`, `json` |
## Access Log
The optional access log records client requests and each HTTP exchange with an upstream registry. It is always written as JSONL, with one JSON object per line. Records for the same client request share a `request_id`.
```yaml
access_log:
path: "/var/log/proxy/access.jsonl"
```
| Config | Environment | Flag | Description |
|--------|-------------|------|-------------|
| `access_log.path` | `PROXY_ACCESS_LOG_PATH` | `-access-log` | File to append JSONL records to; empty disables the log |
The parent directory must exist and be writable when the proxy starts. A newly created log file is readable and writable only by the proxy process owner.
A request that receives a rate limit response from an upstream can produce records like these:
```json
{"time":"2026-08-16T12:00:00Z","event":"upstream","request_id":"host/example-000001","method":"GET","url":"https://registry.example/packages/example","status_code":429,"duration_ms":42}
{"time":"2026-08-16T12:00:00Z","event":"request","request_id":"host/example-000001","method":"GET","path":"/npm/example","status_code":502,"duration_ms":43,"remote_addr":"192.0.2.10:41234"}
```
Upstream retries and OCI authentication calls are separate `upstream` records, so the log preserves every status returned over the wire. Network failures have an `error` field and no `status_code`. URL credentials, query strings, and fragments are omitted from both upstream URLs and client paths.
## Upstream Registries ## Upstream Registries
Override default upstream registry URLs: Override default upstream registry URLs:
@ -139,37 +114,13 @@ Override default upstream registry URLs:
```yaml ```yaml
upstream: upstream:
npm: "https://registry.npmjs.org" npm: "https://registry.npmjs.org"
maven: "https://repo1.maven.org/maven2"
gradle_plugin_portal: "https://plugins.gradle.org/m2"
cargo: "https://index.crates.io" cargo: "https://index.crates.io"
cargo_download: "https://static.crates.io/crates" cargo_download: "https://static.crates.io/crates"
# Named HTTP Helm chart repositories, served at /helm/{name}/.
helm:
bitnami: "https://charts.bitnami.com/bitnami"
# Named OCI registries. Select one with the repository prefix
# upstream/{name}/, e.g. oci://proxy.example.com/upstream/ghcr/owner/chart.
oci:
ghcr: "https://ghcr.io"
``` ```
Helm HTTP repositories are read-only. The proxy fetches and rewrites each
repository's `index.yaml` so chart archives are downloaded through the proxy.
Chart archives are retained only when their SHA-256 digest matches the digest
listed in the index. Relative and absolute chart URLs are both supported.
Named OCI registries preserve the existing unprefixed Docker Hub mirror. A
reference such as `oci://proxy.example.com/upstream/ghcr/owner/chart` is sent
to the registry configured as `ghcr` with `owner/chart` as its repository.
When the proxy uses plain HTTP (for example `localhost:8080`), pass
`--plain-http` to Helm OCI commands.
## Authentication ## 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. Configure authentication for private upstream registries. Auth is matched by URL prefix, 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.
### Bearer Token ### Bearer Token
@ -218,7 +169,7 @@ upstream:
### URL Matching ### URL Matching
Auth keys must be absolute URLs. Matching compares the scheme, host, effective port, and path-segment prefix, preventing credentials for `registry.example.com` from being sent to a lookalike host such as `registry.example.com.evil.test`. The longest matching scope wins, so you can configure different credentials for different paths: Auth configs are matched by URL prefix. The longest matching prefix wins, so you can configure different credentials for different paths:
```yaml ```yaml
upstream: upstream:
@ -233,144 +184,6 @@ upstream:
token: "${PRIVATE_TOKEN}" token: "${PRIVATE_TOKEN}"
``` ```
## Gradle Build Cache
The `/gradle` endpoint supports optional safeguards for upload control and cache retention.
```yaml
gradle:
build_cache:
read_only: false
max_upload_size: "100MB"
max_age: "168h"
max_size: "20GB"
sweep_interval: "10m"
```
| 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.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`, 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 |
`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
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.
```yaml
cooldown:
default: "3d"
ecosystems:
npm: "7d"
cargo: "0"
packages:
"pkg:npm/lodash": "0"
"pkg:npm/@babel/core": "14d"
```
| Config | Environment | Description |
|--------|-------------|-------------|
| `cooldown.default` | `PROXY_COOLDOWN_DEFAULT` | Global default cooldown |
| `cooldown.ecosystems` | - | Per-ecosystem overrides |
| `cooldown.packages` | - | Per-package overrides (keyed by PURL) |
Durations support days (`7d`), hours (`48h`), and minutes (`30m`). Set to `0` to disable.
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.
Resolution order: package override, then ecosystem override, then global default. This lets you set a conservative default while exempting trusted packages.
Currently supported for npm, PyPI, pub.dev, Composer, Cargo, NuGet, Conda, RubyGems, and Hex. These ecosystems include publish timestamps in their metadata.
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`.
## Metadata Caching
By default the proxy fetches metadata fresh from upstream on every request. Enable `cache_metadata` to store metadata responses in the database and storage backend for offline fallback. When upstream is unreachable, the proxy serves the last cached copy. ETag-based revalidation avoids re-downloading unchanged metadata.
OCI manifests are always cached because cached image blobs cannot be pulled without their manifests. Digest-addressed manifests are immutable and served directly from cache. Tag-addressed manifests follow `metadata_ttl`, revalidate when stale, and fall back to the last cached response when the registry is unavailable.
```yaml
cache_metadata: true
```
Or via environment variable: `PROXY_CACHE_METADATA=true`.
The `proxy mirror` command always enables metadata caching regardless of this setting.
### Metadata TTL
When metadata caching is enabled, `metadata_ttl` controls how long a cached response is considered fresh before revalidating with upstream. During the TTL window, cached metadata is served directly without contacting upstream, reducing latency and upstream load.
```yaml
metadata_ttl: "5m" # default
```
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.
### 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.
```yaml
metadata_max_size: "100MB" # default
```
Or via environment variable: `PROXY_METADATA_MAX_SIZE=250MB`.
## Upstream HTTP timeout
Protocol handlers use a shared HTTP client for upstream requests such as metadata fetches and pass-through file downloads. `http_timeout` sets that client's per-request timeout. Raise it if slow upstreams or large metadata responses cause `context deadline exceeded` errors.
```yaml
http_timeout: "30s" # default
```
Or via environment variable: `PROXY_HTTP_TIMEOUT=2m`.
Set to `"0"` to disable the timeout entirely (requests then rely only on the server's write timeout).
## Mirror API
The `/api/mirror` endpoints are disabled by default. Enable them to allow starting mirror jobs via HTTP:
```yaml
mirror_api: true
```
Or via environment variable: `PROXY_MIRROR_API=true`.
When disabled, the endpoints are not registered and return 404.
## Mirror Command
The `proxy mirror` command pre-populates the cache from various sources. It accepts the same storage and database flags as `serve`.
| 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 |
| `--config` | | Path to configuration file |
| `--storage-url` | | Storage URL |
| `--database-driver` | | Database driver |
| `--database-path` | | SQLite database file |
| `--database-url` | | PostgreSQL connection URL |
Positional arguments are treated as PURLs:
```bash
proxy mirror pkg:npm/lodash@4.17.21 pkg:cargo/serde@1.0.0
```
## Docker ## Docker
### SQLite with Local Storage ### SQLite with Local Storage

View file

@ -1,51 +0,0 @@
# Database Migrations
Schema changes are tracked in a `migrations` table. Each migration has a name and a function. On startup, `MigrateSchema()` loads the set of already-applied names in one query and runs anything new.
Fresh databases created via `Create()` get the full schema and all migrations are recorded as already applied.
## Adding a migration
In `internal/database/schema.go`:
1. Write a migration function:
```go
func migrateAddWidgetColumn(db *DB) error {
hasCol, err := db.HasColumn("packages", "widget")
if err != nil {
return fmt.Errorf("checking column widget: %w", err)
}
if !hasCol {
colType := "TEXT"
if db.dialect == DialectPostgres {
colType = "TEXT" // adjust if types differ
}
if _, err := db.Exec(fmt.Sprintf("ALTER TABLE packages ADD COLUMN widget %s", colType)); err != nil {
return fmt.Errorf("adding column widget: %w", err)
}
}
return nil
}
```
2. Append it to the `migrations` slice with the next sequential prefix:
```go
var migrations = []migration{
{"001_add_packages_enrichment_columns", migrateAddPackagesEnrichmentColumns},
{"002_add_versions_enrichment_columns", migrateAddVersionsEnrichmentColumns},
{"003_ensure_artifacts_table", migrateEnsureArtifactsTable},
{"004_ensure_vulnerabilities_table", migrateEnsureVulnerabilitiesTable},
{"005_add_widget_column", migrateAddWidgetColumn}, // new
}
```
3. Add the same column to both `schemaSQLite` and `schemaPostgres` at the top of the file so fresh databases start with the full schema.
## Rules
- Migration functions must be idempotent. Use `HasColumn`/`HasTable` checks or `IF NOT EXISTS` clauses so they're safe to run against a database that already has the change.
- Handle both SQLite and Postgres dialects. Common differences: `DATETIME` vs `TIMESTAMP`, `INTEGER DEFAULT 0` vs `BOOLEAN DEFAULT FALSE`, `INTEGER PRIMARY KEY` vs `SERIAL PRIMARY KEY`.
- Never reorder or rename existing entries. The name string is the migration's identity in the database.
- Never remove old migrations from the list. They won't run on already-migrated databases, but they need to exist for older databases upgrading for the first time.

View file

@ -1,777 +0,0 @@
// Package swagger Code generated by swaggo/swag. DO NOT EDIT
package swagger
import "github.com/swaggo/swag"
const docTemplate = `{
"schemes": {{ marshal .Schemes }},
"swagger": "2.0",
"info": {
"description": "{{escape .Description}}",
"title": "{{.Title}}",
"contact": {},
"version": "{{.Version}}"
},
"host": "{{.Host}}",
"basePath": "{{.BasePath}}",
"paths": {
"/api/bulk": {
"post": {
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"tags": [
"api"
],
"summary": "Bulk package lookup by PURL",
"parameters": [
{
"description": "PURLs",
"name": "request",
"in": "body",
"required": true,
"schema": {
"$ref": "#/definitions/server.BulkRequest"
}
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/server.BulkResponse"
}
},
"400": {
"description": "Bad Request",
"schema": {
"$ref": "#/definitions/server.ErrorResponse"
}
},
"500": {
"description": "Internal Server Error",
"schema": {
"$ref": "#/definitions/server.ErrorResponse"
}
}
}
}
},
"/api/outdated": {
"post": {
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"tags": [
"api"
],
"summary": "Check outdated packages",
"parameters": [
{
"description": "Packages to check",
"name": "request",
"in": "body",
"required": true,
"schema": {
"$ref": "#/definitions/server.OutdatedRequest"
}
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/server.OutdatedResponse"
}
},
"400": {
"description": "Bad Request",
"schema": {
"$ref": "#/definitions/server.ErrorResponse"
}
},
"500": {
"description": "Internal Server Error",
"schema": {
"$ref": "#/definitions/server.ErrorResponse"
}
}
}
}
},
"/api/packages": {
"get": {
"produces": [
"application/json"
],
"tags": [
"api"
],
"summary": "List cached packages",
"parameters": [
{
"type": "string",
"description": "Ecosystem",
"name": "ecosystem",
"in": "query"
},
{
"enum": [
"hits",
"name",
"size",
"cached_at",
"ecosystem",
"vulns"
],
"type": "string",
"description": "Sort",
"name": "sort",
"in": "query"
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/server.PackagesListResponse"
}
},
"400": {
"description": "Bad Request",
"schema": {
"$ref": "#/definitions/server.ErrorResponse"
}
},
"500": {
"description": "Internal Server Error",
"schema": {
"$ref": "#/definitions/server.ErrorResponse"
}
}
}
}
},
"/api/search": {
"get": {
"produces": [
"application/json"
],
"tags": [
"api"
],
"summary": "Search cached packages",
"parameters": [
{
"type": "string",
"description": "Query",
"name": "q",
"in": "query",
"required": true
},
{
"type": "string",
"description": "Ecosystem",
"name": "ecosystem",
"in": "query"
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/server.SearchResponse"
}
},
"400": {
"description": "Bad Request",
"schema": {
"$ref": "#/definitions/server.ErrorResponse"
}
},
"500": {
"description": "Internal Server Error",
"schema": {
"$ref": "#/definitions/server.ErrorResponse"
}
}
}
}
},
"/health": {
"get": {
"produces": [
"application/json"
],
"tags": [
"meta"
],
"summary": "Health check",
"responses": {
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/server.HealthResponse"
}
},
"503": {
"description": "Service Unavailable",
"schema": {
"$ref": "#/definitions/server.HealthResponse"
}
}
}
}
},
"/stats": {
"get": {
"produces": [
"application/json"
],
"tags": [
"meta"
],
"summary": "Cache statistics",
"responses": {
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/server.StatsResponse"
}
},
"500": {
"description": "Internal Server Error",
"schema": {
"$ref": "#/definitions/server.ErrorResponse"
}
}
}
}
},
"/ui/api/browse/{ecosystem}/{name}/{version}": {
"get": {
"description": "Lists files from the first cached artifact for a package version.",
"produces": [
"application/json"
],
"tags": [
"browse"
],
"summary": "List files inside a cached artifact",
"parameters": [
{
"type": "string",
"description": "Ecosystem",
"name": "ecosystem",
"in": "path",
"required": true
},
{
"type": "string",
"description": "Package name",
"name": "name",
"in": "path",
"required": true
},
{
"type": "string",
"description": "Version",
"name": "version",
"in": "path",
"required": true
},
{
"type": "string",
"description": "Directory path inside the archive",
"name": "path",
"in": "query"
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/server.BrowseListResponse"
}
},
"404": {
"description": "Not Found",
"schema": {
"$ref": "#/definitions/server.ErrorResponse"
}
},
"500": {
"description": "Internal Server Error",
"schema": {
"$ref": "#/definitions/server.ErrorResponse"
}
}
}
}
},
"/ui/api/browse/{ecosystem}/{name}/{version}/file/{filepath}": {
"get": {
"description": "Streams a single file from the cached artifact. The file path may contain slashes.",
"produces": [
"application/octet-stream"
],
"tags": [
"browse"
],
"summary": "Fetch a file inside a cached artifact",
"parameters": [
{
"type": "string",
"description": "Ecosystem",
"name": "ecosystem",
"in": "path",
"required": true
},
{
"type": "string",
"description": "Package name",
"name": "name",
"in": "path",
"required": true
},
{
"type": "string",
"description": "Version",
"name": "version",
"in": "path",
"required": true
},
{
"type": "string",
"description": "File path inside the archive",
"name": "filepath",
"in": "path",
"required": true
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"type": "file"
}
},
"400": {
"description": "Bad Request",
"schema": {
"$ref": "#/definitions/server.ErrorResponse"
}
},
"404": {
"description": "Not Found",
"schema": {
"$ref": "#/definitions/server.ErrorResponse"
}
},
"500": {
"description": "Internal Server Error",
"schema": {
"$ref": "#/definitions/server.ErrorResponse"
}
}
}
}
},
"/ui/api/compare/{ecosystem}/{name}/{fromVersion}/{toVersion}": {
"get": {
"description": "Returns a structured diff for two cached versions.",
"produces": [
"application/json"
],
"tags": [
"browse"
],
"summary": "Compare two cached versions",
"parameters": [
{
"type": "string",
"description": "Ecosystem",
"name": "ecosystem",
"in": "path",
"required": true
},
{
"type": "string",
"description": "Package name",
"name": "name",
"in": "path",
"required": true
},
{
"type": "string",
"description": "From version",
"name": "fromVersion",
"in": "path",
"required": true
},
{
"type": "string",
"description": "To version",
"name": "toVersion",
"in": "path",
"required": true
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"type": "object",
"additionalProperties": true
}
},
"404": {
"description": "Not Found",
"schema": {
"$ref": "#/definitions/server.ErrorResponse"
}
},
"500": {
"description": "Internal Server Error",
"schema": {
"$ref": "#/definitions/server.ErrorResponse"
}
}
}
}
}
},
"definitions": {
"server.BrowseFileInfo": {
"type": "object",
"properties": {
"is_dir": {
"type": "boolean"
},
"mod_time": {
"type": "string"
},
"name": {
"type": "string"
},
"path": {
"type": "string"
},
"size": {
"type": "integer"
}
}
},
"server.BrowseListResponse": {
"type": "object",
"properties": {
"files": {
"type": "array",
"items": {
"$ref": "#/definitions/server.BrowseFileInfo"
}
},
"path": {
"type": "string"
}
}
},
"server.BulkRequest": {
"type": "object",
"properties": {
"purls": {
"type": "array",
"items": {
"type": "string"
}
}
}
},
"server.BulkResponse": {
"type": "object",
"properties": {
"packages": {
"type": "object",
"additionalProperties": {
"$ref": "#/definitions/server.PackageResponse"
}
}
}
},
"server.ErrorResponse": {
"type": "object",
"properties": {
"code": {
"type": "string"
},
"message": {
"type": "string"
}
}
},
"server.HealthCheck": {
"type": "object",
"properties": {
"error": {
"type": "string"
},
"status": {
"type": "string"
},
"step": {
"type": "string"
}
}
},
"server.HealthResponse": {
"type": "object",
"properties": {
"checks": {
"type": "object",
"additionalProperties": {
"$ref": "#/definitions/server.HealthCheck"
}
},
"status": {
"type": "string"
}
}
},
"server.OutdatedPackage": {
"type": "object",
"properties": {
"ecosystem": {
"type": "string"
},
"name": {
"type": "string"
},
"version": {
"type": "string"
}
}
},
"server.OutdatedRequest": {
"type": "object",
"properties": {
"packages": {
"type": "array",
"items": {
"$ref": "#/definitions/server.OutdatedPackage"
}
}
}
},
"server.OutdatedResponse": {
"type": "object",
"properties": {
"results": {
"type": "array",
"items": {
"$ref": "#/definitions/server.OutdatedResult"
}
}
}
},
"server.OutdatedResult": {
"type": "object",
"properties": {
"ecosystem": {
"type": "string"
},
"is_outdated": {
"type": "boolean"
},
"latest_version": {
"type": "string"
},
"name": {
"type": "string"
},
"version": {
"type": "string"
}
}
},
"server.PackageListResult": {
"type": "object",
"properties": {
"cached_at": {
"type": "string"
},
"ecosystem": {
"type": "string"
},
"hits": {
"type": "integer"
},
"latest_version": {
"type": "string"
},
"license": {
"type": "string"
},
"license_category": {
"type": "string"
},
"name": {
"type": "string"
},
"size": {
"type": "integer"
},
"vuln_count": {
"type": "integer"
}
}
},
"server.PackageResponse": {
"type": "object",
"properties": {
"description": {
"type": "string"
},
"ecosystem": {
"type": "string"
},
"homepage": {
"type": "string"
},
"latest_version": {
"type": "string"
},
"license": {
"type": "string"
},
"license_category": {
"type": "string"
},
"name": {
"type": "string"
},
"registry_url": {
"type": "string"
},
"repository": {
"type": "string"
}
}
},
"server.PackagesListResponse": {
"type": "object",
"properties": {
"count": {
"type": "integer"
},
"ecosystem": {
"type": "string"
},
"page": {
"type": "integer"
},
"per_page": {
"type": "integer"
},
"results": {
"type": "array",
"items": {
"$ref": "#/definitions/server.PackageListResult"
}
},
"sort_by": {
"type": "string"
},
"total": {
"type": "integer"
}
}
},
"server.SearchPackageResult": {
"type": "object",
"properties": {
"cached_at": {
"type": "string"
},
"ecosystem": {
"type": "string"
},
"hits": {
"type": "integer"
},
"latest_version": {
"type": "string"
},
"license": {
"type": "string"
},
"name": {
"type": "string"
},
"size": {
"type": "integer"
}
}
},
"server.SearchResponse": {
"type": "object",
"properties": {
"count": {
"type": "integer"
},
"query": {
"type": "string"
},
"results": {
"type": "array",
"items": {
"$ref": "#/definitions/server.SearchPackageResult"
}
}
}
},
"server.StatsResponse": {
"type": "object",
"properties": {
"cached_artifacts": {
"type": "integer"
},
"database_path": {
"type": "string"
},
"storage_url": {
"type": "string"
},
"total_size": {
"type": "string"
},
"total_size_bytes": {
"type": "integer"
}
}
}
}
}`
// SwaggerInfo holds exported Swagger Info so clients can modify it
var SwaggerInfo = &swag.Spec{
Version: "0.1.0",
Host: "",
BasePath: "/",
Schemes: []string{},
Title: "git-pkgs proxy API",
Description: "HTTP API for package enrichment, vulnerability lookup, cache stats, and source browsing.",
InfoInstanceName: "swagger",
SwaggerTemplate: docTemplate,
LeftDelim: "{{",
RightDelim: "}}",
}
func init() {
swag.Register(SwaggerInfo.InstanceName(), SwaggerInfo)
}

View file

@ -1,752 +0,0 @@
{
"swagger": "2.0",
"info": {
"description": "HTTP API for package enrichment, vulnerability lookup, cache stats, and source browsing.",
"title": "git-pkgs proxy API",
"contact": {},
"version": "0.1.0"
},
"basePath": "/",
"paths": {
"/api/bulk": {
"post": {
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"tags": [
"api"
],
"summary": "Bulk package lookup by PURL",
"parameters": [
{
"description": "PURLs",
"name": "request",
"in": "body",
"required": true,
"schema": {
"$ref": "#/definitions/server.BulkRequest"
}
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/server.BulkResponse"
}
},
"400": {
"description": "Bad Request",
"schema": {
"$ref": "#/definitions/server.ErrorResponse"
}
},
"500": {
"description": "Internal Server Error",
"schema": {
"$ref": "#/definitions/server.ErrorResponse"
}
}
}
}
},
"/api/outdated": {
"post": {
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"tags": [
"api"
],
"summary": "Check outdated packages",
"parameters": [
{
"description": "Packages to check",
"name": "request",
"in": "body",
"required": true,
"schema": {
"$ref": "#/definitions/server.OutdatedRequest"
}
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/server.OutdatedResponse"
}
},
"400": {
"description": "Bad Request",
"schema": {
"$ref": "#/definitions/server.ErrorResponse"
}
},
"500": {
"description": "Internal Server Error",
"schema": {
"$ref": "#/definitions/server.ErrorResponse"
}
}
}
}
},
"/api/packages": {
"get": {
"produces": [
"application/json"
],
"tags": [
"api"
],
"summary": "List cached packages",
"parameters": [
{
"type": "string",
"description": "Ecosystem",
"name": "ecosystem",
"in": "query"
},
{
"enum": [
"hits",
"name",
"size",
"cached_at",
"ecosystem",
"vulns"
],
"type": "string",
"description": "Sort",
"name": "sort",
"in": "query"
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/server.PackagesListResponse"
}
},
"400": {
"description": "Bad Request",
"schema": {
"$ref": "#/definitions/server.ErrorResponse"
}
},
"500": {
"description": "Internal Server Error",
"schema": {
"$ref": "#/definitions/server.ErrorResponse"
}
}
}
}
},
"/api/search": {
"get": {
"produces": [
"application/json"
],
"tags": [
"api"
],
"summary": "Search cached packages",
"parameters": [
{
"type": "string",
"description": "Query",
"name": "q",
"in": "query",
"required": true
},
{
"type": "string",
"description": "Ecosystem",
"name": "ecosystem",
"in": "query"
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/server.SearchResponse"
}
},
"400": {
"description": "Bad Request",
"schema": {
"$ref": "#/definitions/server.ErrorResponse"
}
},
"500": {
"description": "Internal Server Error",
"schema": {
"$ref": "#/definitions/server.ErrorResponse"
}
}
}
}
},
"/health": {
"get": {
"produces": [
"application/json"
],
"tags": [
"meta"
],
"summary": "Health check",
"responses": {
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/server.HealthResponse"
}
},
"503": {
"description": "Service Unavailable",
"schema": {
"$ref": "#/definitions/server.HealthResponse"
}
}
}
}
},
"/stats": {
"get": {
"produces": [
"application/json"
],
"tags": [
"meta"
],
"summary": "Cache statistics",
"responses": {
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/server.StatsResponse"
}
},
"500": {
"description": "Internal Server Error",
"schema": {
"$ref": "#/definitions/server.ErrorResponse"
}
}
}
}
},
"/ui/api/browse/{ecosystem}/{name}/{version}": {
"get": {
"description": "Lists files from the first cached artifact for a package version.",
"produces": [
"application/json"
],
"tags": [
"browse"
],
"summary": "List files inside a cached artifact",
"parameters": [
{
"type": "string",
"description": "Ecosystem",
"name": "ecosystem",
"in": "path",
"required": true
},
{
"type": "string",
"description": "Package name",
"name": "name",
"in": "path",
"required": true
},
{
"type": "string",
"description": "Version",
"name": "version",
"in": "path",
"required": true
},
{
"type": "string",
"description": "Directory path inside the archive",
"name": "path",
"in": "query"
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/server.BrowseListResponse"
}
},
"404": {
"description": "Not Found",
"schema": {
"$ref": "#/definitions/server.ErrorResponse"
}
},
"500": {
"description": "Internal Server Error",
"schema": {
"$ref": "#/definitions/server.ErrorResponse"
}
}
}
}
},
"/ui/api/browse/{ecosystem}/{name}/{version}/file/{filepath}": {
"get": {
"description": "Streams a single file from the cached artifact. The file path may contain slashes.",
"produces": [
"application/octet-stream"
],
"tags": [
"browse"
],
"summary": "Fetch a file inside a cached artifact",
"parameters": [
{
"type": "string",
"description": "Ecosystem",
"name": "ecosystem",
"in": "path",
"required": true
},
{
"type": "string",
"description": "Package name",
"name": "name",
"in": "path",
"required": true
},
{
"type": "string",
"description": "Version",
"name": "version",
"in": "path",
"required": true
},
{
"type": "string",
"description": "File path inside the archive",
"name": "filepath",
"in": "path",
"required": true
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"type": "file"
}
},
"400": {
"description": "Bad Request",
"schema": {
"$ref": "#/definitions/server.ErrorResponse"
}
},
"404": {
"description": "Not Found",
"schema": {
"$ref": "#/definitions/server.ErrorResponse"
}
},
"500": {
"description": "Internal Server Error",
"schema": {
"$ref": "#/definitions/server.ErrorResponse"
}
}
}
}
},
"/ui/api/compare/{ecosystem}/{name}/{fromVersion}/{toVersion}": {
"get": {
"description": "Returns a structured diff for two cached versions.",
"produces": [
"application/json"
],
"tags": [
"browse"
],
"summary": "Compare two cached versions",
"parameters": [
{
"type": "string",
"description": "Ecosystem",
"name": "ecosystem",
"in": "path",
"required": true
},
{
"type": "string",
"description": "Package name",
"name": "name",
"in": "path",
"required": true
},
{
"type": "string",
"description": "From version",
"name": "fromVersion",
"in": "path",
"required": true
},
{
"type": "string",
"description": "To version",
"name": "toVersion",
"in": "path",
"required": true
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"type": "object",
"additionalProperties": true
}
},
"404": {
"description": "Not Found",
"schema": {
"$ref": "#/definitions/server.ErrorResponse"
}
},
"500": {
"description": "Internal Server Error",
"schema": {
"$ref": "#/definitions/server.ErrorResponse"
}
}
}
}
}
},
"definitions": {
"server.BrowseFileInfo": {
"type": "object",
"properties": {
"is_dir": {
"type": "boolean"
},
"mod_time": {
"type": "string"
},
"name": {
"type": "string"
},
"path": {
"type": "string"
},
"size": {
"type": "integer"
}
}
},
"server.BrowseListResponse": {
"type": "object",
"properties": {
"files": {
"type": "array",
"items": {
"$ref": "#/definitions/server.BrowseFileInfo"
}
},
"path": {
"type": "string"
}
}
},
"server.BulkRequest": {
"type": "object",
"properties": {
"purls": {
"type": "array",
"items": {
"type": "string"
}
}
}
},
"server.BulkResponse": {
"type": "object",
"properties": {
"packages": {
"type": "object",
"additionalProperties": {
"$ref": "#/definitions/server.PackageResponse"
}
}
}
},
"server.ErrorResponse": {
"type": "object",
"properties": {
"code": {
"type": "string"
},
"message": {
"type": "string"
}
}
},
"server.HealthCheck": {
"type": "object",
"properties": {
"error": {
"type": "string"
},
"status": {
"type": "string"
},
"step": {
"type": "string"
}
}
},
"server.HealthResponse": {
"type": "object",
"properties": {
"checks": {
"type": "object",
"additionalProperties": {
"$ref": "#/definitions/server.HealthCheck"
}
},
"status": {
"type": "string"
}
}
},
"server.OutdatedPackage": {
"type": "object",
"properties": {
"ecosystem": {
"type": "string"
},
"name": {
"type": "string"
},
"version": {
"type": "string"
}
}
},
"server.OutdatedRequest": {
"type": "object",
"properties": {
"packages": {
"type": "array",
"items": {
"$ref": "#/definitions/server.OutdatedPackage"
}
}
}
},
"server.OutdatedResponse": {
"type": "object",
"properties": {
"results": {
"type": "array",
"items": {
"$ref": "#/definitions/server.OutdatedResult"
}
}
}
},
"server.OutdatedResult": {
"type": "object",
"properties": {
"ecosystem": {
"type": "string"
},
"is_outdated": {
"type": "boolean"
},
"latest_version": {
"type": "string"
},
"name": {
"type": "string"
},
"version": {
"type": "string"
}
}
},
"server.PackageListResult": {
"type": "object",
"properties": {
"cached_at": {
"type": "string"
},
"ecosystem": {
"type": "string"
},
"hits": {
"type": "integer"
},
"latest_version": {
"type": "string"
},
"license": {
"type": "string"
},
"license_category": {
"type": "string"
},
"name": {
"type": "string"
},
"size": {
"type": "integer"
},
"vuln_count": {
"type": "integer"
}
}
},
"server.PackageResponse": {
"type": "object",
"properties": {
"description": {
"type": "string"
},
"ecosystem": {
"type": "string"
},
"homepage": {
"type": "string"
},
"latest_version": {
"type": "string"
},
"license": {
"type": "string"
},
"license_category": {
"type": "string"
},
"name": {
"type": "string"
},
"registry_url": {
"type": "string"
},
"repository": {
"type": "string"
}
}
},
"server.PackagesListResponse": {
"type": "object",
"properties": {
"count": {
"type": "integer"
},
"ecosystem": {
"type": "string"
},
"page": {
"type": "integer"
},
"per_page": {
"type": "integer"
},
"results": {
"type": "array",
"items": {
"$ref": "#/definitions/server.PackageListResult"
}
},
"sort_by": {
"type": "string"
},
"total": {
"type": "integer"
}
}
},
"server.SearchPackageResult": {
"type": "object",
"properties": {
"cached_at": {
"type": "string"
},
"ecosystem": {
"type": "string"
},
"hits": {
"type": "integer"
},
"latest_version": {
"type": "string"
},
"license": {
"type": "string"
},
"name": {
"type": "string"
},
"size": {
"type": "integer"
}
}
},
"server.SearchResponse": {
"type": "object",
"properties": {
"count": {
"type": "integer"
},
"query": {
"type": "string"
},
"results": {
"type": "array",
"items": {
"$ref": "#/definitions/server.SearchPackageResult"
}
}
}
},
"server.StatsResponse": {
"type": "object",
"properties": {
"cached_artifacts": {
"type": "integer"
},
"database_path": {
"type": "string"
},
"storage_url": {
"type": "string"
},
"total_size": {
"type": "string"
},
"total_size_bytes": {
"type": "integer"
}
}
}
}
}

291
go.mod
View file

@ -1,147 +1,118 @@
module github.com/git-pkgs/proxy module github.com/git-pkgs/proxy
go 1.26.0 go 1.25.7
toolchain go1.26.6
require ( require (
github.com/BurntSushi/toml v1.6.0 github.com/git-pkgs/archives v0.2.0
github.com/CycloneDX/cyclonedx-go v0.11.0 github.com/git-pkgs/enrichment v0.1.5
github.com/git-pkgs/archives v0.5.1 github.com/git-pkgs/git-pkgs v0.15.1-0.20260304191500-e296d0146017
github.com/git-pkgs/cooldown v0.1.1 github.com/git-pkgs/purl v0.1.9
github.com/git-pkgs/enrichment v0.6.5 github.com/git-pkgs/registries v0.3.0
github.com/git-pkgs/integrity v0.1.1 github.com/git-pkgs/spdx v0.1.1
github.com/git-pkgs/magic v0.2.0 github.com/git-pkgs/vers v0.2.3
github.com/git-pkgs/purl v0.1.17 github.com/git-pkgs/vulns v0.1.3
github.com/git-pkgs/registries v0.8.1 github.com/go-chi/chi/v5 v5.2.5
github.com/git-pkgs/spdx v0.3.1
github.com/git-pkgs/vers v0.3.1
github.com/git-pkgs/vulns v0.2.2
github.com/go-chi/chi/v5 v5.3.1
github.com/jmoiron/sqlx v1.4.0 github.com/jmoiron/sqlx v1.4.0
github.com/lib/pq v1.12.3 github.com/lib/pq v1.11.2
github.com/prometheus/client_golang v1.24.1 github.com/prometheus/client_golang v1.23.2
github.com/prometheus/client_model v0.6.2 github.com/prometheus/client_model v0.6.2
github.com/spdx/tools-golang v0.5.7 gocloud.dev v0.45.0
github.com/swaggo/swag v1.16.6
gocloud.dev v0.46.0
golang.org/x/sync v0.22.0
google.golang.org/protobuf v1.36.12
gopkg.in/yaml.v3 v3.0.1 gopkg.in/yaml.v3 v3.0.1
modernc.org/sqlite v1.56.0 modernc.org/sqlite v1.46.1
) )
require ( require (
4d63.com/gocheckcompilerdirectives v1.4.0 // indirect 4d63.com/gocheckcompilerdirectives v1.3.0 // indirect
4d63.com/gochecknoglobals v0.2.2 // indirect 4d63.com/gochecknoglobals v0.2.2 // indirect
charm.land/lipgloss/v2 v2.0.6 // indirect
cloud.google.com/go/auth v0.21.0 // indirect
cloud.google.com/go/auth/oauth2adapt v0.2.8 // indirect
cloud.google.com/go/compute/metadata v0.9.0 // indirect cloud.google.com/go/compute/metadata v0.9.0 // indirect
codeberg.org/chavacava/garif v0.2.0 // indirect codeberg.org/chavacava/garif v0.2.0 // indirect
codeberg.org/polyfloyd/go-errorlint v1.9.0 // indirect codeberg.org/polyfloyd/go-errorlint v1.9.0 // indirect
dev.gaijin.team/go/exhaustruct/v4 v4.0.0 // indirect dev.gaijin.team/go/exhaustruct/v4 v4.0.0 // indirect
dev.gaijin.team/go/exhaustruct/v5 v5.0.3 // indirect dev.gaijin.team/go/golib v0.6.0 // indirect
dev.gaijin.team/go/golib v0.8.1 // indirect
github.com/4meepo/tagalign v1.4.3 // indirect github.com/4meepo/tagalign v1.4.3 // indirect
github.com/Abirdcfly/dupword v0.1.8 // indirect github.com/Abirdcfly/dupword v0.1.7 // indirect
github.com/AdminBenni/iota-mixing v1.0.0 // indirect github.com/AdminBenni/iota-mixing v1.0.0 // indirect
github.com/AlwxSin/noinlineerr v1.0.6 // indirect github.com/AlwxSin/noinlineerr v1.0.5 // indirect
github.com/Antonboom/errname v1.1.2 // indirect github.com/Antonboom/errname v1.1.1 // indirect
github.com/Antonboom/nilnil v1.1.2 // indirect github.com/Antonboom/nilnil v1.1.1 // indirect
github.com/Antonboom/testifylint v1.6.4 // indirect github.com/Antonboom/testifylint v1.6.4 // indirect
github.com/Azure/azure-sdk-for-go/sdk/azcore v1.21.0 // indirect github.com/BurntSushi/toml v1.6.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/ClickHouse/clickhouse-go-linter v1.2.1 // indirect
github.com/Djarvur/go-err113 v0.1.1 // indirect github.com/Djarvur/go-err113 v0.1.1 // indirect
github.com/KyleBanks/depth v1.2.1 // indirect github.com/Masterminds/semver/v3 v3.4.0 // indirect
github.com/Masterminds/semver/v3 v3.5.0 // indirect github.com/MirrexOne/unqueryvet v1.5.3 // indirect
github.com/MirrexOne/unqueryvet v1.5.4 // indirect
github.com/OpenPeeDeeP/depguard/v2 v2.2.1 // indirect github.com/OpenPeeDeeP/depguard/v2 v2.2.1 // indirect
github.com/PuerkitoBio/purell v1.1.1 // indirect github.com/alecthomas/chroma/v2 v2.23.1 // indirect
github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578 // indirect
github.com/alecthomas/chroma/v2 v2.27.0 // indirect
github.com/alecthomas/go-check-sumtype v0.3.1 // indirect github.com/alecthomas/go-check-sumtype v0.3.1 // indirect
github.com/alexkohler/nakedret/v2 v2.0.6 // indirect github.com/alexkohler/nakedret/v2 v2.0.6 // indirect
github.com/alexkohler/prealloc v1.1.0 // indirect github.com/alexkohler/prealloc v1.0.2 // indirect
github.com/alfatraining/structtag v1.0.0 // indirect github.com/alfatraining/structtag v1.0.0 // indirect
github.com/alingse/asasalint v0.0.11 // indirect github.com/alingse/asasalint v0.0.11 // indirect
github.com/alingse/nilnesserr v0.2.0 // indirect github.com/alingse/nilnesserr v0.2.0 // indirect
github.com/anchore/go-struct-converter v0.1.0 // indirect
github.com/apapsch/go-jsonmerge/v2 v2.0.0 // indirect github.com/apapsch/go-jsonmerge/v2 v2.0.0 // indirect
github.com/ashanbrown/forbidigo/v2 v2.3.1 // indirect github.com/ashanbrown/forbidigo/v2 v2.3.0 // indirect
github.com/ashanbrown/makezero/v2 v2.2.1 // indirect github.com/ashanbrown/makezero/v2 v2.1.0 // indirect
github.com/aws/aws-sdk-go-v2 v1.41.9 // indirect github.com/aws/aws-sdk-go-v2 v1.41.3 // indirect
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.11 // indirect github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.6 // indirect
github.com/aws/aws-sdk-go-v2/config v1.32.20 // indirect github.com/aws/aws-sdk-go-v2/config v1.32.11 // indirect
github.com/aws/aws-sdk-go-v2/credentials v1.19.19 // indirect github.com/aws/aws-sdk-go-v2/credentials v1.19.11 // indirect
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.25 // indirect github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.19 // indirect
github.com/aws/aws-sdk-go-v2/feature/s3/transfermanager v0.2.3 // indirect github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.22.5 // indirect
github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.25 // indirect github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.19 // indirect
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.25 // indirect github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.19 // indirect
github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.26 // indirect github.com/aws/aws-sdk-go-v2/internal/ini v1.8.5 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.10 // indirect github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.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/accept-encoding v1.13.6 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.25 // indirect github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.11 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.25 // indirect github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.19 // indirect
github.com/aws/aws-sdk-go-v2/service/s3 v1.102.2 // indirect github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.19 // indirect
github.com/aws/aws-sdk-go-v2/service/signin v1.1.1 // indirect github.com/aws/aws-sdk-go-v2/service/s3 v1.96.3 // indirect
github.com/aws/aws-sdk-go-v2/service/sso v1.30.19 // indirect github.com/aws/aws-sdk-go-v2/service/signin v1.0.7 // indirect
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.36.2 // indirect github.com/aws/aws-sdk-go-v2/service/sso v1.30.12 // indirect
github.com/aws/aws-sdk-go-v2/service/sts v1.42.3 // indirect github.com/aws/aws-sdk-go-v2/service/ssooidc v1.35.16 // indirect
github.com/aws/smithy-go v1.26.0 // indirect github.com/aws/aws-sdk-go-v2/service/sts v1.41.8 // indirect
github.com/aws/smithy-go v1.24.2 // indirect
github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect
github.com/beorn7/perks v1.0.1 // indirect github.com/beorn7/perks v1.0.1 // indirect
github.com/bkielbasa/cyclop v1.2.3 // indirect github.com/bkielbasa/cyclop v1.2.3 // indirect
github.com/blizzy78/varnamelen v0.8.0 // indirect github.com/blizzy78/varnamelen v0.8.0 // indirect
github.com/bombsimon/wsl/v4 v4.7.0 // indirect github.com/bombsimon/wsl/v4 v4.7.0 // indirect
github.com/bombsimon/wsl/v5 v5.9.0 // indirect github.com/bombsimon/wsl/v5 v5.6.0 // indirect
github.com/breml/bidichk v0.3.3 // indirect github.com/breml/bidichk v0.3.3 // indirect
github.com/breml/errchkjson v0.4.1 // indirect github.com/breml/errchkjson v0.4.1 // indirect
github.com/butuzov/ireturn v0.4.1 // indirect github.com/butuzov/ireturn v0.4.0 // indirect
github.com/butuzov/mirror v1.3.3 // indirect github.com/butuzov/mirror v1.3.0 // indirect
github.com/catenacyber/perfsprint v0.10.1 // indirect github.com/catenacyber/perfsprint v0.10.1 // indirect
github.com/ccojocar/zxcvbn-go v1.0.4 // indirect github.com/ccojocar/zxcvbn-go v1.0.4 // indirect
github.com/cenk/backoff v2.2.1+incompatible // indirect github.com/cenk/backoff v2.2.1+incompatible // indirect
github.com/cespare/xxhash/v2 v2.3.0 // indirect github.com/cespare/xxhash/v2 v2.3.0 // indirect
github.com/charithe/durationcheck v0.0.11 // indirect github.com/charithe/durationcheck v0.0.11 // indirect
github.com/charmbracelet/colorprofile v0.4.3 // indirect github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc // indirect
github.com/charmbracelet/ultraviolet v0.0.0-20260811164956-006e29f97886 // indirect github.com/charmbracelet/lipgloss v1.1.0 // indirect
github.com/charmbracelet/x/ansi v0.11.8 // indirect github.com/charmbracelet/x/ansi v0.10.1 // indirect
github.com/charmbracelet/x/term v0.2.2 // indirect github.com/charmbracelet/x/cellbuf v0.0.13-0.20250311204145-2c3ea96c31dd // indirect
github.com/charmbracelet/x/termios v0.1.1 // indirect github.com/charmbracelet/x/term v0.2.1 // indirect
github.com/charmbracelet/x/windows v0.2.2 // indirect
github.com/ckaznocha/intrange v0.3.1 // indirect github.com/ckaznocha/intrange v0.3.1 // indirect
github.com/clipperhouse/displaywidth v0.11.0 // indirect
github.com/clipperhouse/uax29/v2 v2.7.0 // indirect
github.com/cpuguy83/go-md2man/v2 v2.0.6 // indirect
github.com/curioswitch/go-reassign v0.3.0 // indirect github.com/curioswitch/go-reassign v0.3.0 // indirect
github.com/daixiang0/gci v0.13.7 // indirect github.com/daixiang0/gci v0.13.7 // indirect
github.com/dave/dst v0.27.3 // indirect github.com/dave/dst v0.27.3 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/denis-tingaikin/go-header v0.5.0 // indirect github.com/denis-tingaikin/go-header v0.5.0 // indirect
github.com/dlclark/regexp2/v2 v2.2.1 // indirect github.com/dlclark/regexp2 v1.11.5 // indirect
github.com/dustin/go-humanize v1.0.1 // indirect github.com/dustin/go-humanize v1.0.1 // indirect
github.com/ecosyste-ms/ecosystems-go v0.4.0 // indirect github.com/ecosyste-ms/ecosystems-go v0.1.1 // indirect
github.com/ettle/strcase v0.2.0 // indirect github.com/ettle/strcase v0.2.0 // indirect
github.com/facebookgo/clock v0.0.0-20150410010913-600d898af40a // indirect github.com/facebookgo/clock v0.0.0-20150410010913-600d898af40a // indirect
github.com/fatih/color v1.19.0 // indirect github.com/fatih/color v1.18.0 // indirect
github.com/fatih/structtag v1.2.0 // indirect github.com/fatih/structtag v1.2.0 // indirect
github.com/firefart/nonamedreturns v1.0.8 // indirect github.com/firefart/nonamedreturns v1.0.6 // indirect
github.com/fsnotify/fsnotify v1.9.0 // indirect github.com/fsnotify/fsnotify v1.9.0 // indirect
github.com/fzipp/gocyclo v0.6.0 // indirect github.com/fzipp/gocyclo v0.6.0 // indirect
github.com/ghostiam/protogetter v0.3.21 // indirect github.com/ghostiam/protogetter v0.3.20 // indirect
github.com/git-pkgs/packageurl-go v0.3.1 // indirect github.com/git-pkgs/packageurl-go v0.3.1 // indirect
github.com/git-pkgs/pom v0.1.5 // indirect github.com/github/go-spdx/v2 v2.4.0 // indirect
github.com/github/go-spdx/v2 v2.7.0 // indirect github.com/go-critic/go-critic v0.14.3 // indirect
github.com/go-critic/go-critic v0.14.4 // indirect
github.com/go-logr/logr v1.4.3 // indirect github.com/go-logr/logr v1.4.3 // indirect
github.com/go-logr/stdr v1.2.2 // indirect github.com/go-logr/stdr v1.2.2 // indirect
github.com/go-openapi/jsonpointer v0.19.5 // indirect
github.com/go-openapi/jsonreference v0.19.6 // indirect
github.com/go-openapi/spec v0.20.4 // indirect
github.com/go-openapi/swag v0.19.15 // indirect
github.com/go-toolsmith/astcast v1.1.0 // indirect github.com/go-toolsmith/astcast v1.1.0 // indirect
github.com/go-toolsmith/astcopy v1.1.0 // indirect github.com/go-toolsmith/astcopy v1.1.0 // indirect
github.com/go-toolsmith/astequal v1.2.0 // indirect github.com/go-toolsmith/astequal v1.2.0 // indirect
@ -154,110 +125,100 @@ require (
github.com/gobwas/glob v0.2.3 // indirect github.com/gobwas/glob v0.2.3 // indirect
github.com/godoc-lint/godoc-lint v0.11.2 // indirect github.com/godoc-lint/godoc-lint v0.11.2 // indirect
github.com/gofrs/flock v0.13.0 // indirect github.com/gofrs/flock v0.13.0 // indirect
github.com/golang-jwt/jwt/v5 v5.3.1 // indirect
github.com/golangci/asciicheck v0.5.0 // indirect github.com/golangci/asciicheck v0.5.0 // indirect
github.com/golangci/dupl v0.0.0-20260401084720-c99c5cf5c202 // indirect github.com/golangci/dupl v0.0.0-20250308024227-f665c8d69b32 // indirect
github.com/golangci/go-printf-func-name v0.1.1 // indirect github.com/golangci/go-printf-func-name v0.1.1 // indirect
github.com/golangci/gofmt v0.0.0-20260820135601-e84e05053792 // indirect github.com/golangci/gofmt v0.0.0-20250106114630-d62b90e6713d // indirect
github.com/golangci/golangci-lint/v2 v2.13.1 // indirect github.com/golangci/golangci-lint/v2 v2.10.1 // indirect
github.com/golangci/golines v0.15.0 // indirect github.com/golangci/golines v0.15.0 // indirect
github.com/golangci/misspell v0.8.0 // indirect github.com/golangci/misspell v0.8.0 // indirect
github.com/golangci/plugin-module-register v0.1.2 // indirect github.com/golangci/plugin-module-register v0.1.2 // indirect
github.com/golangci/revgrep v0.8.0 // indirect github.com/golangci/revgrep v0.8.0 // indirect
github.com/golangci/rowserrcheck v0.0.0-20260419091836-c5f79b8a11ba // indirect
github.com/golangci/swaggoswag v0.0.0-20250504205917-77f2aca3143e // indirect github.com/golangci/swaggoswag v0.0.0-20250504205917-77f2aca3143e // indirect
github.com/golangci/unconvert v0.0.0-20250410112200-a129a6e6413e // indirect github.com/golangci/unconvert v0.0.0-20250410112200-a129a6e6413e // indirect
github.com/google/go-cmp v0.7.0 // indirect github.com/google/go-cmp v0.7.0 // indirect
github.com/google/s2a-go v0.1.9 // indirect
github.com/google/uuid v1.6.0 // indirect github.com/google/uuid v1.6.0 // indirect
github.com/google/wire v0.7.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.17.0 // indirect
github.com/googleapis/gax-go/v2 v2.23.0 // indirect
github.com/gordonklaus/ineffassign v0.2.0 // indirect github.com/gordonklaus/ineffassign v0.2.0 // indirect
github.com/gostaticanalysis/analysisutil v0.7.1 // indirect github.com/gostaticanalysis/analysisutil v0.7.1 // indirect
github.com/gostaticanalysis/comment v1.5.0 // indirect github.com/gostaticanalysis/comment v1.5.0 // indirect
github.com/gostaticanalysis/forcetypeassert v0.2.0 // indirect github.com/gostaticanalysis/forcetypeassert v0.2.0 // indirect
github.com/gostaticanalysis/nilerr v0.1.2 // indirect github.com/gostaticanalysis/nilerr v0.1.2 // indirect
github.com/hashicorp/go-immutable-radix/v2 v2.1.0 // indirect github.com/hashicorp/go-immutable-radix/v2 v2.1.0 // indirect
github.com/hashicorp/go-version v1.9.0 // indirect github.com/hashicorp/go-version v1.8.0 // indirect
github.com/hashicorp/golang-lru/v2 v2.0.7 // indirect github.com/hashicorp/golang-lru/v2 v2.0.7 // indirect
github.com/hashicorp/hcl v1.0.0 // indirect github.com/hashicorp/hcl v1.0.0 // indirect
github.com/hexops/gotextdiff v1.0.3 // indirect github.com/hexops/gotextdiff v1.0.3 // indirect
github.com/inconshreveable/mousetrap v1.1.0 // indirect github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/jgautheron/goconst v1.11.0 // indirect github.com/jgautheron/goconst v1.8.2 // indirect
github.com/jingyugao/rowserrcheck v1.1.1 // indirect
github.com/jjti/go-spancheck v0.6.5 // indirect github.com/jjti/go-spancheck v0.6.5 // indirect
github.com/josharian/intern v1.0.0 // indirect
github.com/julz/importas v0.2.0 // indirect github.com/julz/importas v0.2.0 // indirect
github.com/karamaru-alpha/copyloopvar v1.2.2 // indirect github.com/karamaru-alpha/copyloopvar v1.2.2 // indirect
github.com/kisielk/errcheck v1.20.0 // indirect github.com/kisielk/errcheck v1.9.0 // indirect
github.com/kkHAIKE/contextcheck v1.1.6 // indirect github.com/kkHAIKE/contextcheck v1.1.6 // indirect
github.com/kulti/thelper v0.7.1 // indirect github.com/kulti/thelper v0.7.1 // indirect
github.com/kunwardeep/paralleltest v1.0.15 // indirect github.com/kunwardeep/paralleltest v1.0.15 // indirect
github.com/kylelemons/godebug v1.1.0 // indirect
github.com/lasiar/canonicalheader v1.1.2 // indirect github.com/lasiar/canonicalheader v1.1.2 // indirect
github.com/ldez/exptostd v0.4.5 // indirect github.com/ldez/exptostd v0.4.5 // indirect
github.com/ldez/gomoddirectives v0.9.0 // indirect github.com/ldez/gomoddirectives v0.8.0 // indirect
github.com/ldez/grignotin v0.10.1 // indirect github.com/ldez/grignotin v0.10.1 // indirect
github.com/ldez/structtags v0.6.1 // indirect github.com/ldez/structtags v0.6.1 // indirect
github.com/ldez/tagliatelle v0.7.2 // indirect github.com/ldez/tagliatelle v0.7.2 // indirect
github.com/ldez/usetesting v0.5.0 // indirect github.com/ldez/usetesting v0.5.0 // indirect
github.com/leonklingele/grouper v1.1.2 // indirect github.com/leonklingele/grouper v1.1.2 // indirect
github.com/lucasb-eyer/go-colorful v1.4.1 // indirect github.com/lucasb-eyer/go-colorful v1.2.0 // indirect
github.com/macabu/inamedparam v0.2.0 // indirect github.com/macabu/inamedparam v0.2.0 // indirect
github.com/magiconair/properties v1.8.6 // indirect github.com/magiconair/properties v1.8.6 // indirect
github.com/mailru/easyjson v0.7.7 // indirect
github.com/manuelarte/embeddedstructfieldcheck v0.4.0 // indirect github.com/manuelarte/embeddedstructfieldcheck v0.4.0 // indirect
github.com/manuelarte/funcorder v0.6.0 // indirect github.com/manuelarte/funcorder v0.5.0 // indirect
github.com/maratori/testableexamples v1.0.1 // indirect github.com/maratori/testableexamples v1.0.1 // indirect
github.com/maratori/testpackage v1.1.2 // indirect github.com/maratori/testpackage v1.1.2 // indirect
github.com/matoous/godox v1.1.0 // indirect github.com/matoous/godox v1.1.0 // indirect
github.com/mattn/go-colorable v0.1.15 // indirect github.com/mattn/go-colorable v0.1.14 // indirect
github.com/mattn/go-isatty v0.0.24 // indirect github.com/mattn/go-isatty v0.0.20 // indirect
github.com/mattn/go-runewidth v0.0.24 // indirect github.com/mattn/go-runewidth v0.0.16 // indirect
github.com/mgechev/revive v1.15.0 // indirect github.com/mgechev/revive v1.14.0 // indirect
github.com/mitchellh/go-homedir v1.1.0 // indirect github.com/mitchellh/go-homedir v1.1.0 // indirect
github.com/mitchellh/mapstructure v1.5.0 // indirect github.com/mitchellh/mapstructure v1.5.0 // indirect
github.com/moricho/tparallel v0.3.2 // indirect github.com/moricho/tparallel v0.3.2 // indirect
github.com/muesli/cancelreader v0.2.2 // indirect github.com/muesli/termenv v0.16.0 // indirect
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
github.com/nakabonne/nestif v0.3.1 // indirect github.com/nakabonne/nestif v0.3.1 // indirect
github.com/ncruces/go-strftime v1.0.0 // indirect github.com/ncruces/go-strftime v1.0.0 // indirect
github.com/nishanths/exhaustive v0.12.0 // indirect github.com/nishanths/exhaustive v0.12.0 // indirect
github.com/nishanths/predeclared v0.2.2 // indirect github.com/nishanths/predeclared v0.2.2 // indirect
github.com/nunnatsa/ginkgolinter v0.24.0 // indirect github.com/nunnatsa/ginkgolinter v0.23.0 // indirect
github.com/oapi-codegen/nullable v1.2.0 // indirect github.com/oapi-codegen/runtime v1.2.0 // indirect
github.com/oapi-codegen/runtime v1.6.0 // indirect
github.com/package-url/packageurl-go v0.1.6 // indirect
github.com/pandatix/go-cvss v0.6.2 // indirect github.com/pandatix/go-cvss v0.6.2 // indirect
github.com/pelletier/go-toml v1.9.5 // indirect github.com/pelletier/go-toml v1.9.5 // indirect
github.com/pelletier/go-toml/v2 v2.4.3 // indirect github.com/pelletier/go-toml/v2 v2.2.4 // indirect
github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c // indirect github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/prometheus/common v0.70.1 // indirect github.com/prometheus/common v0.67.5 // indirect
github.com/prometheus/procfs v0.21.1 // indirect github.com/prometheus/procfs v0.20.1 // indirect
github.com/quasilyte/go-ruleguard v0.4.5 // indirect github.com/quasilyte/go-ruleguard v0.4.5 // indirect
github.com/quasilyte/go-ruleguard/dsl v0.3.23 // indirect github.com/quasilyte/go-ruleguard/dsl v0.3.23 // indirect
github.com/quasilyte/gogrep v0.5.0 // indirect github.com/quasilyte/gogrep v0.5.0 // indirect
github.com/quasilyte/regex/syntax v0.0.0-20210819130434-b3f0c404a727 // indirect github.com/quasilyte/regex/syntax v0.0.0-20210819130434-b3f0c404a727 // indirect
github.com/quasilyte/stdinfo v0.0.0-20220114132959-f7386bf02567 // indirect github.com/quasilyte/stdinfo v0.0.0-20220114132959-f7386bf02567 // indirect
github.com/raeperd/recvcheck v0.3.0 // indirect github.com/raeperd/recvcheck v0.2.0 // indirect
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
github.com/rivo/uniseg v0.4.7 // indirect github.com/rivo/uniseg v0.4.7 // indirect
github.com/rogpeppe/go-internal v1.16.0 // indirect github.com/rogpeppe/go-internal v1.14.1 // indirect
github.com/rs/dnscache v0.0.0-20230804202142-fc85eb664529 // indirect github.com/rs/dnscache v0.0.0-20230804202142-fc85eb664529 // indirect
github.com/rubyist/circuitbreaker v2.2.1+incompatible // indirect github.com/rubyist/circuitbreaker v2.2.1+incompatible // indirect
github.com/russross/blackfriday/v2 v2.1.0 // indirect
github.com/ryancurrah/gomodguard v1.4.1 // indirect github.com/ryancurrah/gomodguard v1.4.1 // indirect
github.com/ryancurrah/gomodguard/v2 v2.1.3 // indirect github.com/ryanrolds/sqlclosecheck v0.5.1 // indirect
github.com/ryanrolds/sqlclosecheck v0.6.0 // indirect
github.com/sanposhiho/wastedassign/v2 v2.1.0 // indirect github.com/sanposhiho/wastedassign/v2 v2.1.0 // indirect
github.com/santhosh-tekuri/jsonschema/v6 v6.0.3 // indirect github.com/santhosh-tekuri/jsonschema/v6 v6.0.2 // indirect
github.com/sashamelentyev/interfacebloat v1.1.0 // indirect github.com/sashamelentyev/interfacebloat v1.1.0 // indirect
github.com/sashamelentyev/usestdlibvars v1.29.0 // indirect github.com/sashamelentyev/usestdlibvars v1.29.0 // indirect
github.com/securego/gosec/v2 v2.28.0 // indirect github.com/securego/gosec/v2 v2.23.0 // indirect
github.com/sirupsen/logrus v1.10.1 // indirect github.com/sirupsen/logrus v1.9.4 // indirect
github.com/sivchari/containedctx v1.0.3 // indirect github.com/sivchari/containedctx v1.0.3 // indirect
github.com/sonatard/noctx v0.5.1 // indirect github.com/sonatard/noctx v0.4.0 // indirect
github.com/sourcegraph/go-diff v0.8.0 // indirect github.com/sourcegraph/go-diff v0.7.0 // indirect
github.com/spf13/afero v1.15.0 // indirect github.com/spf13/afero v1.15.0 // indirect
github.com/spf13/cast v1.5.0 // indirect github.com/spf13/cast v1.5.0 // indirect
github.com/spf13/cobra v1.10.2 // indirect github.com/spf13/cobra v1.10.2 // indirect
@ -266,20 +227,19 @@ require (
github.com/spf13/viper v1.12.0 // indirect github.com/spf13/viper v1.12.0 // indirect
github.com/ssgreg/nlreturn/v2 v2.2.1 // indirect github.com/ssgreg/nlreturn/v2 v2.2.1 // indirect
github.com/stbenjam/no-sprintf-host-port v0.3.1 // indirect github.com/stbenjam/no-sprintf-host-port v0.3.1 // indirect
github.com/stretchr/objx v0.5.3 // indirect github.com/stretchr/objx v0.5.2 // indirect
github.com/stretchr/testify v1.12.1 // indirect github.com/stretchr/testify v1.11.1 // indirect
github.com/subosito/gotenv v1.4.1 // indirect github.com/subosito/gotenv v1.4.1 // indirect
github.com/tetafro/godot v1.5.6 // indirect github.com/tetafro/godot v1.5.4 // indirect
github.com/timakin/bodyclose v0.0.0-20260129054331-73d1f95b84b4 // indirect github.com/timakin/bodyclose v0.0.0-20241222091800-1db5c5ca4d67 // indirect
github.com/timonwong/loggercheck v0.11.0 // indirect github.com/timonwong/loggercheck v0.11.0 // indirect
github.com/tomarrell/wrapcheck/v2 v2.12.0 // indirect github.com/tomarrell/wrapcheck/v2 v2.12.0 // indirect
github.com/tommy-muehle/go-mnd/v2 v2.5.1 // indirect github.com/tommy-muehle/go-mnd/v2 v2.5.1 // indirect
github.com/ulikunitz/xz v0.5.16 // indirect github.com/ulikunitz/xz v0.5.15 // indirect
github.com/ultraware/funlen v0.2.0 // indirect github.com/ultraware/funlen v0.2.0 // indirect
github.com/ultraware/whitespace v0.2.0 // indirect github.com/ultraware/whitespace v0.2.0 // indirect
github.com/urfave/cli/v2 v2.3.0 // indirect github.com/uudashr/gocognit v1.2.0 // indirect
github.com/uudashr/gocognit v1.2.1 // indirect github.com/uudashr/iface v1.4.1 // indirect
github.com/uudashr/iface v1.5.0 // indirect
github.com/xen0n/gosmopolitan v1.3.0 // indirect github.com/xen0n/gosmopolitan v1.3.0 // indirect
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect
github.com/yagipy/maintidx v1.0.0 // indirect github.com/yagipy/maintidx v1.0.0 // indirect
@ -287,41 +247,40 @@ require (
github.com/ykadowak/zerologlint v0.1.5 // indirect github.com/ykadowak/zerologlint v0.1.5 // indirect
gitlab.com/bosi/decorder v0.4.2 // indirect gitlab.com/bosi/decorder v0.4.2 // indirect
go-simpler.org/musttag v0.14.0 // indirect go-simpler.org/musttag v0.14.0 // indirect
go-simpler.org/sloglint v0.12.0 // indirect go-simpler.org/sloglint v0.11.1 // indirect
go.augendre.info/arangolint v0.4.0 // indirect go.augendre.info/arangolint v0.4.0 // indirect
go.augendre.info/fatcontext v0.10.0 // indirect go.augendre.info/fatcontext v0.9.0 // indirect
go.opentelemetry.io/auto/sdk v1.2.1 // indirect go.opentelemetry.io/auto/sdk v1.2.1 // indirect
go.opentelemetry.io/otel v1.44.0 // indirect go.opentelemetry.io/otel v1.41.0 // indirect
go.opentelemetry.io/otel/metric v1.44.0 // indirect go.opentelemetry.io/otel/metric v1.41.0 // indirect
go.opentelemetry.io/otel/sdk v1.44.0 // indirect go.opentelemetry.io/otel/sdk v1.41.0 // indirect
go.opentelemetry.io/otel/sdk/metric v1.44.0 // indirect go.opentelemetry.io/otel/sdk/metric v1.41.0 // indirect
go.opentelemetry.io/otel/trace v1.44.0 // indirect go.opentelemetry.io/otel/trace v1.41.0 // indirect
go.uber.org/multierr v1.11.0 // indirect go.uber.org/multierr v1.11.0 // indirect
go.uber.org/zap v1.27.1 // indirect go.uber.org/zap v1.27.1 // indirect
go.yaml.in/yaml/v2 v2.4.4 // indirect go.yaml.in/yaml/v2 v2.4.3 // indirect
go.yaml.in/yaml/v3 v3.0.5 // indirect go.yaml.in/yaml/v3 v3.0.4 // indirect
golang.org/x/crypto v0.55.0 // indirect
golang.org/x/exp v0.0.0-20260218203240-3dfff04db8fa // indirect golang.org/x/exp v0.0.0-20260218203240-3dfff04db8fa // indirect
golang.org/x/exp/typeparams v0.0.0-20260811152304-ee035b5b010f // indirect golang.org/x/exp/typeparams v0.0.0-20260209203927-2842357ff358 // indirect
golang.org/x/mod v0.40.0 // indirect golang.org/x/mod v0.33.0 // indirect
golang.org/x/net v0.58.0 // indirect golang.org/x/net v0.51.0 // indirect
golang.org/x/oauth2 v0.36.0 // indirect golang.org/x/sync v0.19.0 // indirect
golang.org/x/sys v0.47.0 // indirect golang.org/x/sys v0.41.0 // indirect
golang.org/x/text v0.41.0 // indirect golang.org/x/text v0.34.0 // indirect
golang.org/x/tools v0.49.0 // indirect golang.org/x/tools v0.42.0 // indirect
golang.org/x/xerrors v0.0.0-20240903120638-7835f813f4da // indirect golang.org/x/xerrors v0.0.0-20240903120638-7835f813f4da // indirect
google.golang.org/api v0.288.0 // indirect google.golang.org/api v0.269.0 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20260706201446-f0a921348800 // indirect google.golang.org/genproto/googleapis/rpc v0.0.0-20260226221140-a57be14db171 // indirect
google.golang.org/grpc v1.82.1 // indirect google.golang.org/grpc v1.79.1 // indirect
google.golang.org/protobuf v1.36.11 // indirect
gopkg.in/ini.v1 v1.67.0 // indirect gopkg.in/ini.v1 v1.67.0 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect gopkg.in/yaml.v2 v2.4.0 // indirect
honnef.co/go/tools v0.8.0 // indirect honnef.co/go/tools v0.7.0 // indirect
modernc.org/libc v1.74.4 // indirect modernc.org/libc v1.69.0 // indirect
modernc.org/mathutil v1.7.1 // indirect modernc.org/mathutil v1.7.1 // indirect
modernc.org/memory v1.11.0 // indirect modernc.org/memory v1.11.0 // indirect
mvdan.cc/gofumpt v0.11.0 // indirect mvdan.cc/gofumpt v0.9.2 // indirect
mvdan.cc/unparam v0.0.0-20260818115549-3f964bcb5673 // indirect mvdan.cc/unparam v0.0.0-20251027182757-5beb8c8f8f15 // indirect
sigs.k8s.io/yaml v1.6.0 // indirect
) )
tool github.com/golangci/golangci-lint/v2/cmd/golangci-lint tool github.com/golangci/golangci-lint/v2/cmd/golangci-lint

753
go.sum

File diff suppressed because it is too large Load diff

View file

@ -1,109 +0,0 @@
// Package accesslog writes proxy activity as JSON Lines.
package accesslog
import (
"context"
"encoding/json"
"fmt"
"net/url"
"os"
"sync"
"time"
)
const (
accessLogFileMode os.FileMode = 0o600
// EventRequest identifies the response sent by the proxy to a client.
EventRequest = "request"
// EventUpstream identifies one HTTP exchange with an upstream service.
EventUpstream = "upstream"
)
type requestIDKey struct{}
// Entry is one proxy activity record.
type Entry struct {
Time time.Time `json:"time"`
Event string `json:"event"`
RequestID string `json:"request_id,omitempty"`
Method string `json:"method"`
Path string `json:"path,omitempty"`
URL string `json:"url,omitempty"`
StatusCode int `json:"status_code,omitempty"`
DurationMS int64 `json:"duration_ms"`
RemoteAddr string `json:"remote_addr,omitempty"`
Error string `json:"error,omitempty"`
}
// Logger appends complete JSON objects to a file, one per line.
type Logger struct {
mu sync.Mutex
file *os.File
encoder *json.Encoder
}
// Open opens path for append, creating it with owner-only permissions when needed.
func Open(path string) (*Logger, error) {
file, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, accessLogFileMode)
if err != nil {
return nil, fmt.Errorf("opening access log: %w", err)
}
return &Logger{
file: file,
encoder: json.NewEncoder(file),
}, nil
}
// Write appends an entry to the log.
func (l *Logger) Write(entry Entry) error {
if entry.Time.IsZero() {
entry.Time = time.Now().UTC()
}
l.mu.Lock()
defer l.mu.Unlock()
if err := l.encoder.Encode(entry); err != nil {
return fmt.Errorf("writing access log: %w", err)
}
return nil
}
// Close closes the log file after any active writer finishes.
func (l *Logger) Close() error {
l.mu.Lock()
defer l.mu.Unlock()
if err := l.file.Close(); err != nil {
return fmt.Errorf("closing access log: %w", err)
}
return nil
}
// WithRequestID stores a proxy request ID in ctx.
func WithRequestID(ctx context.Context, requestID string) context.Context {
return context.WithValue(ctx, requestIDKey{}, requestID)
}
// RequestID returns the proxy request ID stored in ctx.
func RequestID(ctx context.Context) string {
requestID, _ := ctx.Value(requestIDKey{}).(string)
return requestID
}
// URLWithoutSecrets returns a URL without user information, query values, or fragments.
func URLWithoutSecrets(value *url.URL) string {
if value == nil {
return ""
}
clean := *value
clean.User = nil
clean.RawQuery = ""
clean.ForceQuery = false
clean.Fragment = ""
clean.RawFragment = ""
return clean.String()
}

View file

@ -1,91 +0,0 @@
package accesslog
import (
"bufio"
"context"
"encoding/json"
"net/url"
"os"
"path/filepath"
"sync"
"testing"
)
func TestLoggerWritesJSONLines(t *testing.T) {
path := filepath.Join(t.TempDir(), "access.jsonl")
logger, err := Open(path)
if err != nil {
t.Fatal(err)
}
const entries = 20
var wg sync.WaitGroup
for range entries {
wg.Add(1)
go func() {
defer wg.Done()
if err := logger.Write(Entry{
Event: EventUpstream,
RequestID: "request-id",
Method: "GET",
URL: "https://registry.example/packages/example",
StatusCode: 429,
}); err != nil {
t.Errorf("Write: %v", err)
}
}()
}
wg.Wait()
if err := logger.Close(); err != nil {
t.Fatal(err)
}
file, err := os.Open(path)
if err != nil {
t.Fatal(err)
}
defer func() { _ = file.Close() }()
scanner := bufio.NewScanner(file)
count := 0
for scanner.Scan() {
var entry Entry
if err := json.Unmarshal(scanner.Bytes(), &entry); err != nil {
t.Fatalf("line %d is not JSON: %v", count+1, err)
}
if entry.Time.IsZero() {
t.Errorf("line %d has no time", count+1)
}
if entry.StatusCode != 429 {
t.Errorf("line %d status_code = %d, want 429", count+1, entry.StatusCode)
}
count++
}
if err := scanner.Err(); err != nil {
t.Fatal(err)
}
if count != entries {
t.Errorf("lines = %d, want %d", count, entries)
}
}
func TestRequestID(t *testing.T) {
ctx := WithRequestID(context.Background(), "abc-123")
if got := RequestID(ctx); got != "abc-123" {
t.Errorf("RequestID = %q, want %q", got, "abc-123")
}
}
func TestURLWithoutSecrets(t *testing.T) {
value, err := url.Parse("https://user:password@registry.example/package.tgz?token=secret#fragment")
if err != nil {
t.Fatal(err)
}
got := URLWithoutSecrets(value)
want := "https://registry.example/package.tgz"
if got != want {
t.Errorf("URLWithoutSecrets = %q, want %q", got, want)
}
}

View file

@ -51,15 +51,11 @@ import (
"encoding/base64" "encoding/base64"
"encoding/json" "encoding/json"
"fmt" "fmt"
"net/url"
"os" "os"
"path/filepath" "path/filepath"
"sort"
"strconv" "strconv"
"strings" "strings"
"time"
"github.com/git-pkgs/purl"
"gopkg.in/yaml.v3" "gopkg.in/yaml.v3"
) )
@ -68,20 +64,11 @@ type Config struct {
// Listen is the address to listen on (e.g., ":8080", "127.0.0.1:8080"). // Listen is the address to listen on (e.g., ":8080", "127.0.0.1:8080").
Listen string `json:"listen" yaml:"listen"` Listen string `json:"listen" yaml:"listen"`
// BaseURL is the public URL where package endpoints are reachable. // BaseURL is the public URL where this proxy is accessible.
// Used for rewriting package metadata URLs and shown to humans on the // Used for rewriting package metadata URLs.
// install guide so they know what to point their package manager at.
// Example: "https://proxy.example.com" or "http://localhost:8080" // Example: "https://proxy.example.com" or "http://localhost:8080"
BaseURL string `json:"base_url" yaml:"base_url"` BaseURL string `json:"base_url" yaml:"base_url"`
// UIBaseURL is the public URL where the web UI is reachable. Defaults to
// BaseURL when unset. Set this separately when the UI is served on a
// different hostname than the package endpoints — for example, the UI on a
// public domain behind auth while build machines hit a Docker network alias
// for the package endpoints.
// Example: "https://proxy.example.com/ui"
UIBaseURL string `json:"ui_base_url" yaml:"ui_base_url"`
// Storage configures artifact storage. // Storage configures artifact storage.
Storage StorageConfig `json:"storage" yaml:"storage"` Storage StorageConfig `json:"storage" yaml:"storage"`
@ -91,87 +78,8 @@ type Config struct {
// Log configures logging. // Log configures logging.
Log LogConfig `json:"log" yaml:"log"` Log LogConfig `json:"log" yaml:"log"`
// AccessLog configures the JSONL activity log.
AccessLog AccessLogConfig `json:"access_log" yaml:"access_log"`
// Upstream configures upstream registry URLs (optional overrides). // Upstream configures upstream registry URLs (optional overrides).
Upstream UpstreamConfig `json:"upstream" yaml:"upstream"` Upstream UpstreamConfig `json:"upstream" yaml:"upstream"`
// Cooldown configures version age filtering to mitigate supply chain attacks.
Cooldown CooldownConfig `json:"cooldown" yaml:"cooldown"`
// CacheMetadata enables caching of upstream metadata responses for offline fallback.
// When enabled, metadata is stored in the database and storage backend.
// The mirror command always enables this regardless of this setting.
CacheMetadata bool `json:"cache_metadata" yaml:"cache_metadata"`
// MetadataTTL is how long cached metadata is considered fresh before
// revalidating with upstream. Uses Go duration syntax (e.g. "5m", "1h").
// Default: "5m". Set to "0" to always revalidate.
MetadataTTL string `json:"metadata_ttl" yaml:"metadata_ttl"`
// MetadataMaxSize is the maximum size of an upstream metadata response
// the proxy will buffer (e.g. "100MB", "250MB"). Responses over this
// size return ErrMetadataTooLarge. Default: "100MB".
MetadataMaxSize string `json:"metadata_max_size" yaml:"metadata_max_size"`
// HTTPTimeout is the timeout for individual upstream HTTP requests made
// by protocol handlers (metadata fetches, pass-through file requests).
// Uses Go duration syntax (e.g. "30s", "2m"). Default: "30s".
// Set to "0" to disable the timeout entirely.
HTTPTimeout string `json:"http_timeout" yaml:"http_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"`
// Gradle configures Gradle HttpBuildCache behavior.
Gradle GradleConfig `json:"gradle" yaml:"gradle"`
// Health configures the /health endpoint behavior.
Health HealthConfig `json:"health" yaml:"health"`
}
// CooldownConfig configures version cooldown periods.
// Versions published more recently than the cooldown are hidden from metadata responses.
type CooldownConfig struct {
// Default is the global default cooldown (e.g., "3d", "48h", "0" to disable).
Default string `json:"default" yaml:"default"`
// Ecosystems overrides the default for specific ecosystems.
Ecosystems map[string]string `json:"ecosystems" yaml:"ecosystems"`
// Packages overrides the cooldown for specific packages (keyed by PURL).
// Valid PURL keys are normalized to canonical form before use.
Packages map[string]string `json:"packages" yaml:"packages"`
}
// NormalizedPackages returns a copy of the package overrides with valid PURL
// keys in canonical form. An explicitly canonical key wins over an equivalent
// noncanonical key, and invalid keys are preserved unchanged.
func (c *CooldownConfig) NormalizedPackages() map[string]string {
if c == nil || c.Packages == nil {
return nil
}
keys := make([]string, 0, len(c.Packages))
for key := range c.Packages {
keys = append(keys, key)
}
sort.Strings(keys)
normalized := make(map[string]string, len(c.Packages))
for _, key := range keys {
canonical := key
if parsed, err := purl.Parse(key); err == nil {
canonical = parsed.String()
}
if _, exists := normalized[canonical]; exists && key != canonical {
continue
}
normalized[canonical] = c.Packages[key]
}
return normalized
} }
// StorageConfig configures artifact storage. // StorageConfig configures artifact storage.
@ -185,66 +93,14 @@ type StorageConfig struct {
URL string `json:"url" yaml:"url"` URL string `json:"url" yaml:"url"`
// Path is the directory where cached artifacts are stored. // Path is the directory where cached artifacts are stored.
// If URL is empty, this is used as file://{Path}.
//
// Deprecated: Use URL with file:// scheme instead. // Deprecated: Use URL with file:// scheme instead.
// If URL is empty, this is used as file://{Path}.
Path string `json:"path" yaml:"path"` Path string `json:"path" yaml:"path"`
// MaxSize is the maximum cache size (e.g., "10GB", "500MB"). // MaxSize is the maximum cache size (e.g., "10GB", "500MB").
// When exceeded, least recently used artifacts are evicted. // When exceeded, least recently used artifacts are evicted.
// Empty or "0" means unlimited. // Empty or "0" means unlimited.
MaxSize string `json:"max_size" yaml:"max_size"` MaxSize string `json:"max_size" yaml:"max_size"`
// DirectServe enables redirecting cached artifact downloads to presigned
// storage URLs (HTTP 302) instead of streaming bytes through the proxy.
// Only effective for backends that support URL signing (S3, Azure).
DirectServe bool `json:"direct_serve" yaml:"direct_serve"`
// DirectServeTTL is how long presigned URLs remain valid.
// Uses Go duration syntax (e.g. "5m", "1h"). Default: "15m".
DirectServeTTL string `json:"direct_serve_ttl" yaml:"direct_serve_ttl"`
// DirectServeBaseURL overrides the scheme and host of presigned URLs
// before returning them to clients. Useful when the proxy reaches
// storage at an internal address (e.g. 127.0.0.1 or a Docker hostname)
// but clients must use a public one.
DirectServeBaseURL string `json:"direct_serve_base_url" yaml:"direct_serve_base_url"`
}
// GradleConfig configures Gradle-specific features.
type GradleConfig struct {
// BuildCache configures the /gradle HttpBuildCache endpoint.
BuildCache GradleBuildCacheConfig `json:"build_cache" yaml:"build_cache"`
}
// GradleBuildCacheConfig configures Gradle HttpBuildCache safeguards.
type GradleBuildCacheConfig struct {
// ReadOnly disables PUT uploads and keeps cache reads (GET/HEAD) enabled.
ReadOnly bool `json:"read_only" yaml:"read_only"`
// MaxUploadSize caps a single PUT body size (e.g., "100MB"). Must be > 0.
// Default: "100MB".
MaxUploadSize string `json:"max_upload_size" yaml:"max_upload_size"`
// MaxAge evicts entries older than this duration (e.g., "24h", "7d").
// Empty or "0" disables age-based eviction.
MaxAge string `json:"max_age" yaml:"max_age"`
// MaxSize evicts oldest entries until total Gradle cache size is <= MaxSize.
// Empty or "0" disables size-based eviction.
MaxSize string `json:"max_size" yaml:"max_size"`
// SweepInterval controls periodic eviction frequency.
// Default: "10m".
SweepInterval string `json:"sweep_interval" yaml:"sweep_interval"`
}
// HealthConfig configures the /health endpoint.
type HealthConfig struct {
// StorageProbeInterval is the minimum time between storage backend probes.
// Uses Go duration syntax (e.g. "30s", "1m"). Default: "30s".
// Set to "0" to probe on every /health request (useful for low-traffic deployments).
StorageProbeInterval string `json:"storage_probe_interval" yaml:"storage_probe_interval"`
} }
// DatabaseConfig configures the cache database. // DatabaseConfig configures the cache database.
@ -259,21 +115,6 @@ type DatabaseConfig struct {
URL string `json:"url" yaml:"url"` URL string `json:"url" yaml:"url"`
} }
// String returns a human-readable description of the configured database
// suitable for logging. For postgres the password in the connection URL is
// redacted; if the URL cannot be parsed only the driver name is returned to
// avoid leaking credentials.
func (d DatabaseConfig) String() string {
if d.Driver == "postgres" {
u, err := url.Parse(d.URL)
if err != nil || u.Host == "" {
return "postgres"
}
return u.Redacted()
}
return d.Path
}
// LogConfig configures logging. // LogConfig configures logging.
type LogConfig struct { type LogConfig struct {
// Level is the minimum log level: "debug", "info", "warn", "error". // Level is the minimum log level: "debug", "info", "warn", "error".
@ -283,12 +124,6 @@ type LogConfig struct {
Format string `json:"format" yaml:"format"` Format string `json:"format" yaml:"format"`
} }
// AccessLogConfig configures the JSONL activity log.
type AccessLogConfig struct {
// Path is the file to append activity records to. Empty disables the access log.
Path string `json:"path" yaml:"path"`
}
// UpstreamConfig configures upstream registry URLs and authentication. // UpstreamConfig configures upstream registry URLs and authentication.
// Leave empty to use defaults. // Leave empty to use defaults.
type UpstreamConfig struct { type UpstreamConfig struct {
@ -296,15 +131,6 @@ type UpstreamConfig struct {
// Default: https://registry.npmjs.org // Default: https://registry.npmjs.org
NPM string `json:"npm" yaml:"npm"` NPM string `json:"npm" yaml:"npm"`
// Maven is the upstream Maven repository URL.
// Default: https://repo1.maven.org/maven2
Maven string `json:"maven" yaml:"maven"`
// GradlePluginPortal is the upstream Gradle Plugin Portal Maven URL.
// Used to resolve Gradle plugin marker artifacts.
// Default: https://plugins.gradle.org/m2
GradlePluginPortal string `json:"gradle_plugin_portal" yaml:"gradle_plugin_portal"`
// Cargo is the upstream cargo index URL. // Cargo is the upstream cargo index URL.
// Default: https://index.crates.io // Default: https://index.crates.io
Cargo string `json:"cargo" yaml:"cargo"` Cargo string `json:"cargo" yaml:"cargo"`
@ -313,45 +139,24 @@ type UpstreamConfig struct {
// Default: https://static.crates.io/crates // Default: https://static.crates.io/crates
CargoDownload string `json:"cargo_download" yaml:"cargo_download"` CargoDownload string `json:"cargo_download" yaml:"cargo_download"`
// Debian is the upstream APT repository base URL.
// Example: http://archive.ubuntu.com/ubuntu would get Ubuntu.
// Default: http://deb.debian.org/debian
Debian string `json:"debian" yaml:"debian"`
// Helm maps repository names to HTTP Helm chart repository URLs.
// Requests use /helm/{name}/index.yaml and chart URLs in the index are
// rewritten to the same named proxy endpoint.
Helm map[string]string `json:"helm" yaml:"helm"`
// 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.
OCI map[string]string `json:"oci" yaml:"oci"`
// Auth configures authentication for upstream registries. // Auth configures authentication for upstream registries.
// Keys are absolute URL scopes matched by scheme, host, effective port, // Keys are URL prefixes that are matched against request URLs.
// and path-segment prefix.
// Example: "https://npm.pkg.github.com" matches all requests to that host. // Example: "https://npm.pkg.github.com" matches all requests to that host.
Auth map[string]AuthConfig `json:"auth" yaml:"auth"` Auth map[string]AuthConfig `json:"auth" yaml:"auth"`
} }
// AuthForURL returns the auth config that matches the given URL. // AuthForURL returns the auth config that matches the given URL.
// The longest matching URL scope wins. // Matches are based on URL prefix - the longest matching prefix wins.
func (u *UpstreamConfig) AuthForURL(url string) *AuthConfig { func (u *UpstreamConfig) AuthForURL(url string) *AuthConfig {
if u.Auth == nil { if u.Auth == nil {
return nil return nil
} }
target, err := parseAuthURL(url)
if err != nil {
return nil
}
var bestMatch *AuthConfig var bestMatch *AuthConfig
var bestLen int var bestLen int
for pattern, auth := range u.Auth { for pattern, auth := range u.Auth {
configured, err := parseAuthURL(pattern) if strings.HasPrefix(url, pattern) && len(pattern) > bestLen {
if err == nil && authURLMatches(configured, target) && len(pattern) > bestLen {
a := auth // copy to avoid loop variable capture a := auth // copy to avoid loop variable capture
bestMatch = &a bestMatch = &a
bestLen = len(pattern) bestLen = len(pattern)
@ -361,73 +166,6 @@ func (u *UpstreamConfig) AuthForURL(url string) *AuthConfig {
return bestMatch return bestMatch
} }
// Validate checks upstream authentication URL scopes.
func (u *UpstreamConfig) Validate() error {
for pattern := range u.Auth {
if _, err := parseAuthURL(pattern); err != nil {
return fmt.Errorf("invalid upstream.auth URL %q: %w", pattern, err)
}
}
if err := validateNamedUpstreams("upstream.helm", u.Helm); err != nil {
return err
}
if err := validateNamedUpstreams("upstream.oci", u.OCI); err != nil {
return err
}
return nil
}
func validateNamedUpstreams(field string, upstreams map[string]string) error {
for name, upstreamURL := range upstreams {
if name == "" || name == "." || name == ".." || strings.ContainsAny(name, `/\\`) {
return fmt.Errorf("invalid %s name %q", field, name)
}
if err := validateAbsoluteURL(field+"."+name, upstreamURL); err != nil {
return err
}
}
return nil
}
func parseAuthURL(value string) (*url.URL, error) {
parsed, err := url.Parse(value)
if err != nil || !parsed.IsAbs() || parsed.Hostname() == "" || parsed.Opaque != "" {
return nil, fmt.Errorf("invalid authentication URL")
}
return parsed, nil
}
func authURLMatches(configured, target *url.URL) bool {
if !strings.EqualFold(configured.Scheme, target.Scheme) ||
!strings.EqualFold(configured.Hostname(), target.Hostname()) ||
authURLPort(configured) != authURLPort(target) {
return false
}
if configured.RawQuery != "" && configured.RawQuery != target.RawQuery {
return false
}
configuredPath := strings.TrimSuffix(configured.EscapedPath(), "/")
if configuredPath == "" {
return true
}
targetPath := strings.TrimSuffix(target.EscapedPath(), "/")
return targetPath == configuredPath || strings.HasPrefix(targetPath, configuredPath+"/")
}
func authURLPort(value *url.URL) string {
if port := value.Port(); port != "" {
return port
}
if strings.EqualFold(value.Scheme, "https") {
return "443"
}
if strings.EqualFold(value.Scheme, "http") {
return "80"
}
return ""
}
// AuthConfig configures authentication for an upstream registry. // AuthConfig configures authentication for an upstream registry.
type AuthConfig struct { type AuthConfig struct {
// Type is the authentication type: "bearer", "basic", or "header". // Type is the authentication type: "bearer", "basic", or "header".
@ -470,21 +208,9 @@ func Default() *Config {
Format: "text", Format: "text",
}, },
Upstream: UpstreamConfig{ Upstream: UpstreamConfig{
NPM: "https://registry.npmjs.org", NPM: "https://registry.npmjs.org",
Maven: "https://repo1.maven.org/maven2", Cargo: "https://index.crates.io",
GradlePluginPortal: "https://plugins.gradle.org/m2", CargoDownload: "https://static.crates.io/crates",
Cargo: "https://index.crates.io",
CargoDownload: "https://static.crates.io/crates",
Debian: "http://deb.debian.org/debian",
},
Gradle: GradleConfig{
BuildCache: GradleBuildCacheConfig{
ReadOnly: false,
MaxUploadSize: defaultGradleMaxUploadSizeStr,
MaxAge: "168h",
MaxSize: "",
SweepInterval: defaultGradleSweepIntervalStr,
},
}, },
} }
} }
@ -520,74 +246,46 @@ func Load(path string) (*Config, error) {
return cfg, nil return cfg, nil
} }
// setEnvString sets *dst from the named environment variable, leaving it
// untouched if the variable is unset or empty.
func setEnvString(dst *string, key string) {
if v := os.Getenv(key); v != "" {
*dst = v
}
}
// setEnvBool is setEnvString for boolean fields, parsed via envBool.
func setEnvBool(dst *bool, key string) {
if v := os.Getenv(key); v != "" {
*dst = envBool(v)
}
}
// LoadFromEnv applies environment variable overrides to a Config. // LoadFromEnv applies environment variable overrides to a Config.
// Environment variables use the PROXY_ prefix: // Environment variables use the PROXY_ prefix:
// - PROXY_LISTEN // - PROXY_LISTEN
// - PROXY_BASE_URL // - PROXY_BASE_URL
// - PROXY_UI_URL
// - PROXY_STORAGE_PATH // - PROXY_STORAGE_PATH
// - PROXY_STORAGE_MAX_SIZE // - PROXY_STORAGE_MAX_SIZE
// - PROXY_DATABASE_PATH // - PROXY_DATABASE_PATH
// - PROXY_LOG_LEVEL // - PROXY_LOG_LEVEL
// - PROXY_LOG_FORMAT // - PROXY_LOG_FORMAT
// - PROXY_ACCESS_LOG_PATH
// - PROXY_HEALTH_STORAGE_PROBE_INTERVAL
func (c *Config) LoadFromEnv() { func (c *Config) LoadFromEnv() {
setEnvString(&c.Listen, "PROXY_LISTEN") if v := os.Getenv("PROXY_LISTEN"); v != "" {
setEnvString(&c.BaseURL, "PROXY_BASE_URL") c.Listen = v
setEnvString(&c.UIBaseURL, "PROXY_UI_URL") }
setEnvString(&c.Storage.URL, "PROXY_STORAGE_URL") if v := os.Getenv("PROXY_BASE_URL"); v != "" {
setEnvString(&c.Storage.Path, "PROXY_STORAGE_PATH") c.BaseURL = v
setEnvString(&c.Storage.MaxSize, "PROXY_STORAGE_MAX_SIZE") }
setEnvBool(&c.Storage.DirectServe, "PROXY_STORAGE_DIRECT_SERVE") if v := os.Getenv("PROXY_STORAGE_URL"); v != "" {
setEnvString(&c.Storage.DirectServeTTL, "PROXY_STORAGE_DIRECT_SERVE_TTL") c.Storage.URL = v
setEnvString(&c.Storage.DirectServeBaseURL, "PROXY_STORAGE_DIRECT_SERVE_BASE_URL") }
setEnvString(&c.Database.Driver, "PROXY_DATABASE_DRIVER") if v := os.Getenv("PROXY_STORAGE_PATH"); v != "" {
setEnvString(&c.Database.Path, "PROXY_DATABASE_PATH") c.Storage.Path = v
setEnvString(&c.Database.URL, "PROXY_DATABASE_URL") }
setEnvString(&c.Log.Level, "PROXY_LOG_LEVEL") if v := os.Getenv("PROXY_STORAGE_MAX_SIZE"); v != "" {
setEnvString(&c.Log.Format, "PROXY_LOG_FORMAT") c.Storage.MaxSize = v
setEnvString(&c.AccessLog.Path, "PROXY_ACCESS_LOG_PATH") }
setEnvString(&c.Upstream.Maven, "PROXY_UPSTREAM_MAVEN") if v := os.Getenv("PROXY_DATABASE_DRIVER"); v != "" {
setEnvString(&c.Upstream.GradlePluginPortal, "PROXY_UPSTREAM_GRADLE_PLUGIN_PORTAL") c.Database.Driver = v
setEnvString(&c.Upstream.Debian, "PROXY_UPSTREAM_DEBIAN") }
setEnvString(&c.Cooldown.Default, "PROXY_COOLDOWN_DEFAULT") if v := os.Getenv("PROXY_DATABASE_PATH"); v != "" {
setEnvBool(&c.CacheMetadata, "PROXY_CACHE_METADATA") c.Database.Path = v
setEnvBool(&c.MirrorAPI, "PROXY_MIRROR_API") }
setEnvString(&c.MetadataTTL, "PROXY_METADATA_TTL") if v := os.Getenv("PROXY_DATABASE_URL"); v != "" {
setEnvString(&c.MetadataMaxSize, "PROXY_METADATA_MAX_SIZE") c.Database.URL = v
setEnvString(&c.HTTPTimeout, "PROXY_HTTP_TIMEOUT") }
setEnvBool(&c.Gradle.BuildCache.ReadOnly, "PROXY_GRADLE_BUILD_CACHE_READ_ONLY") if v := os.Getenv("PROXY_LOG_LEVEL"); v != "" {
setEnvString(&c.Gradle.BuildCache.MaxUploadSize, "PROXY_GRADLE_BUILD_CACHE_MAX_UPLOAD_SIZE") c.Log.Level = v
setEnvString(&c.Gradle.BuildCache.MaxAge, "PROXY_GRADLE_BUILD_CACHE_MAX_AGE") }
setEnvString(&c.Gradle.BuildCache.MaxSize, "PROXY_GRADLE_BUILD_CACHE_MAX_SIZE") if v := os.Getenv("PROXY_LOG_FORMAT"); v != "" {
setEnvString(&c.Gradle.BuildCache.SweepInterval, "PROXY_GRADLE_BUILD_CACHE_SWEEP_INTERVAL") c.Log.Format = v
setEnvString(&c.Health.StorageProbeInterval, "PROXY_HEALTH_STORAGE_PROBE_INTERVAL")
}
// validateAbsoluteURL returns an error if value is not a parseable URL with
// both a scheme and host. fieldName is used in the error message.
func validateAbsoluteURL(fieldName, value string) error {
u, err := url.Parse(value)
if err != nil || u.Scheme == "" || u.Host == "" {
return fmt.Errorf("invalid %s %q: must be an absolute URL", fieldName, value)
} }
return nil
} }
// Validate checks the configuration for errors. // Validate checks the configuration for errors.
@ -598,11 +296,6 @@ func (c *Config) Validate() error {
if c.BaseURL == "" { if c.BaseURL == "" {
return fmt.Errorf("base_url is required") return fmt.Errorf("base_url is required")
} }
if c.UIBaseURL == "" {
c.UIBaseURL = c.BaseURL
} else if err := validateAbsoluteURL("ui_base_url", c.UIBaseURL); err != nil {
return err
}
if c.Storage.URL == "" && c.Storage.Path == "" { if c.Storage.URL == "" && c.Storage.Path == "" {
return fmt.Errorf("storage.url or storage.path is required") return fmt.Errorf("storage.url or storage.path is required")
} }
@ -642,267 +335,9 @@ 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)
}
}
// Validate direct serve base URL if specified
if c.Storage.DirectServeBaseURL != "" {
if err := validateAbsoluteURL("storage.direct_serve_base_url", c.Storage.DirectServeBaseURL); err != nil {
return err
}
}
// 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 := validateMetadataMaxSize(c.MetadataMaxSize); err != nil {
return err
}
if err := validateHTTPTimeout(c.HTTPTimeout); err != nil {
return err
}
return c.validateComponents()
}
func (c *Config) validateComponents() error {
if err := c.Upstream.Validate(); err != nil {
return err
}
if err := c.Health.Validate(); err != nil {
return err
}
return c.Gradle.BuildCache.Validate()
}
// Validate checks the /health configuration. An unset interval is allowed
// (the cache uses its default); explicit values must parse and be non-negative.
func (h *HealthConfig) Validate() error {
if h.StorageProbeInterval == "" || h.StorageProbeInterval == "0" {
return nil
}
d, err := time.ParseDuration(h.StorageProbeInterval)
if err != nil {
return fmt.Errorf("invalid health.storage_probe_interval %q: %w", h.StorageProbeInterval, err)
}
if d < 0 {
return fmt.Errorf("invalid health.storage_probe_interval %q: must be non-negative", h.StorageProbeInterval)
}
return nil return nil
} }
// Validate checks Gradle build cache settings, applying the default upload
// size if unset.
func (g *GradleBuildCacheConfig) Validate() error {
if g.MaxUploadSize == "" {
g.MaxUploadSize = defaultGradleMaxUploadSizeStr
}
uploadSize, err := ParseSize(g.MaxUploadSize)
if err != nil {
return fmt.Errorf("invalid gradle.build_cache.max_upload_size: %w", err)
}
if uploadSize <= 0 {
return fmt.Errorf("invalid gradle.build_cache.max_upload_size %q: must be > 0", g.MaxUploadSize)
}
if g.MaxAge != "" && g.MaxAge != "0" {
if _, err := time.ParseDuration(g.MaxAge); err != nil {
return fmt.Errorf("invalid gradle.build_cache.max_age %q: %w", g.MaxAge, err)
}
}
if g.MaxSize != "" {
if _, err := ParseSize(g.MaxSize); err != nil {
return fmt.Errorf("invalid gradle.build_cache.max_size: %w", err)
}
}
if g.SweepInterval != "" {
d, err := time.ParseDuration(g.SweepInterval)
if err != nil {
return fmt.Errorf("invalid gradle.build_cache.sweep_interval %q: %w", g.SweepInterval, err)
}
if d <= 0 {
return fmt.Errorf("invalid gradle.build_cache.sweep_interval %q: must be > 0", g.SweepInterval)
}
}
return nil
}
const (
defaultMetadataTTL = 5 * time.Minute //nolint:mnd // sensible default
defaultDirectServeTTL = 15 * time.Minute //nolint:mnd // sensible default
defaultHTTPTimeout = 30 * time.Second //nolint:mnd // sensible default
defaultMetadataMaxSize = 100 << 20
defaultGradleBuildCacheMaxUploadSize = 100 << 20
defaultGradleBuildCacheSweepInterval = 10 * time.Minute
defaultGradleMaxUploadSizeStr = "100MB"
defaultGradleSweepIntervalStr = "10m"
)
// ParseMaxSize returns the maximum cache size in bytes.
// Returns 0 if unset or explicitly disabled (meaning unlimited).
func (c *Config) ParseMaxSize() int64 {
if c.Storage.MaxSize == "" || c.Storage.MaxSize == "0" {
return 0
}
size, err := ParseSize(c.Storage.MaxSize)
if err != nil {
return 0
}
return size
}
func validateHTTPTimeout(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)
}
if d < 0 {
return fmt.Errorf("invalid http_timeout %q: must be non-negative", s)
}
return nil
}
func validateMetadataMaxSize(s string) error {
if s == "" {
return nil
}
size, err := ParseSize(s)
if err != nil {
return fmt.Errorf("invalid metadata_max_size: %w", err)
}
if size <= 0 {
return fmt.Errorf("invalid metadata_max_size %q: must be positive", s)
}
return nil
}
// ParseMetadataMaxSize returns the maximum metadata response size in bytes.
// Returns 100MB if unset or invalid.
func (c *Config) ParseMetadataMaxSize() int64 {
if c.MetadataMaxSize == "" {
return defaultMetadataMaxSize
}
size, err := ParseSize(c.MetadataMaxSize)
if err != nil || size <= 0 {
return defaultMetadataMaxSize
}
return size
}
// 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
}
if c.HTTPTimeout == "0" {
return 0
}
d, err := time.ParseDuration(c.HTTPTimeout)
if err != nil || d < 0 {
return defaultHTTPTimeout
}
return d
}
// ParseMetadataTTL returns the metadata TTL duration.
// Returns 5 minutes if unset, 0 if explicitly disabled.
func (c *Config) ParseMetadataTTL() time.Duration {
if c.MetadataTTL == "" {
return defaultMetadataTTL
}
if c.MetadataTTL == "0" {
return 0
}
d, err := time.ParseDuration(c.MetadataTTL)
if err != nil {
return defaultMetadataTTL
}
return d
}
// ParseGradleBuildCacheMaxUploadSize returns the max accepted PUT body size.
// Defaults to 100MB if unset or invalid.
func (c *Config) ParseGradleBuildCacheMaxUploadSize() int64 {
if c.Gradle.BuildCache.MaxUploadSize == "" {
return defaultGradleBuildCacheMaxUploadSize
}
size, err := ParseSize(c.Gradle.BuildCache.MaxUploadSize)
if err != nil || size <= 0 {
return defaultGradleBuildCacheMaxUploadSize
}
return size
}
// ParseGradleBuildCacheMaxAge returns age-based eviction threshold.
// Returns 0 when disabled or invalid.
func (c *Config) ParseGradleBuildCacheMaxAge() time.Duration {
if c.Gradle.BuildCache.MaxAge == "" || c.Gradle.BuildCache.MaxAge == "0" {
return 0
}
d, err := time.ParseDuration(c.Gradle.BuildCache.MaxAge)
if err != nil || d <= 0 {
return 0
}
return d
}
// ParseGradleBuildCacheMaxSize returns total-size cap in bytes.
// Returns 0 when disabled or invalid.
func (c *Config) ParseGradleBuildCacheMaxSize() int64 {
if c.Gradle.BuildCache.MaxSize == "" || c.Gradle.BuildCache.MaxSize == "0" {
return 0
}
size, err := ParseSize(c.Gradle.BuildCache.MaxSize)
if err != nil || size <= 0 {
return 0
}
return size
}
// ParseGradleBuildCacheSweepInterval returns eviction sweep cadence.
// Defaults to 10m if unset or invalid.
func (c *Config) ParseGradleBuildCacheSweepInterval() time.Duration {
if c.Gradle.BuildCache.SweepInterval == "" {
return defaultGradleBuildCacheSweepInterval
}
d, err := time.ParseDuration(c.Gradle.BuildCache.SweepInterval)
if err != nil || d <= 0 {
return defaultGradleBuildCacheSweepInterval
}
return d
}
// ParseDirectServeTTL returns the presigned URL expiry duration.
// Returns 15 minutes if unset.
func (c *Config) ParseDirectServeTTL() time.Duration {
if c.Storage.DirectServeTTL == "" {
return defaultDirectServeTTL
}
d, err := time.ParseDuration(c.Storage.DirectServeTTL)
if err != nil {
return defaultDirectServeTTL
}
return d
}
// ParseSize parses a human-readable size string (e.g., "10GB", "500MB"). // ParseSize parses a human-readable size string (e.g., "10GB", "500MB").
// Returns the size in bytes. // Returns the size in bytes.
func ParseSize(s string) (int64, error) { func ParseSize(s string) (int64, error) {
@ -928,7 +363,8 @@ func ParseSize(s string) (int64, error) {
} }
for _, s2 := range suffixes { for _, s2 := range suffixes {
if numStr, ok := strings.CutSuffix(s, s2.suffix); ok { if strings.HasSuffix(s, s2.suffix) {
numStr := strings.TrimSuffix(s, s2.suffix)
num, err := strconv.ParseFloat(numStr, 64) num, err := strconv.ParseFloat(numStr, 64)
if err != nil { if err != nil {
return 0, fmt.Errorf("invalid number %q", numStr) return 0, fmt.Errorf("invalid number %q", numStr)
@ -982,7 +418,3 @@ func (a *AuthConfig) Header() (name, value string) {
func expandEnv(s string) string { func expandEnv(s string) string {
return os.Expand(s, os.Getenv) return os.Expand(s, os.Getenv)
} }
func envBool(v string) bool {
return v == "true" || v == "1"
}

View file

@ -3,15 +3,7 @@ package config
import ( import (
"os" "os"
"path/filepath" "path/filepath"
"strings"
"testing" "testing"
"time"
)
const (
testDriverPostgres = "postgres"
testInvalid = "invalid"
testLevelDebug = "debug"
) )
func TestDefault(t *testing.T) { func TestDefault(t *testing.T) {
@ -26,24 +18,6 @@ func TestDefault(t *testing.T) {
if cfg.Database.Path == "" { if cfg.Database.Path == "" {
t.Error("Database.Path should not be empty") t.Error("Database.Path should not be empty")
} }
if cfg.AccessLog.Path != "" {
t.Errorf("AccessLog.Path = %q, want disabled by default", cfg.AccessLog.Path)
}
if cfg.Gradle.BuildCache.MaxUploadSize != "100MB" {
t.Errorf("Gradle.BuildCache.MaxUploadSize = %q, want %q", cfg.Gradle.BuildCache.MaxUploadSize, "100MB")
}
if cfg.Gradle.BuildCache.MaxAge != "168h" {
t.Errorf("Gradle.BuildCache.MaxAge = %q, want %q", cfg.Gradle.BuildCache.MaxAge, "168h")
}
if cfg.Upstream.Maven != "https://repo1.maven.org/maven2" {
t.Errorf("Upstream.Maven = %q, want %q", cfg.Upstream.Maven, "https://repo1.maven.org/maven2")
}
if cfg.Upstream.GradlePluginPortal != "https://plugins.gradle.org/m2" {
t.Errorf("Upstream.GradlePluginPortal = %q, want %q", cfg.Upstream.GradlePluginPortal, "https://plugins.gradle.org/m2")
}
if cfg.Upstream.Debian != "http://deb.debian.org/debian" {
t.Errorf("Upstream.Debian = %q, want %q", cfg.Upstream.Debian, "http://deb.debian.org/debian")
}
} }
func TestValidate(t *testing.T) { func TestValidate(t *testing.T) {
@ -89,27 +63,27 @@ func TestValidate(t *testing.T) {
}, },
{ {
name: "postgres without url", name: "postgres without url",
modify: func(c *Config) { c.Database.Driver = testDriverPostgres; c.Database.URL = "" }, modify: func(c *Config) { c.Database.Driver = "postgres"; c.Database.URL = "" },
wantErr: true, wantErr: true,
}, },
{ {
name: "postgres with url", name: "postgres with url",
modify: func(c *Config) { c.Database.Driver = testDriverPostgres; c.Database.URL = "postgres://localhost/test" }, modify: func(c *Config) { c.Database.Driver = "postgres"; c.Database.URL = "postgres://localhost/test" },
wantErr: false, wantErr: false,
}, },
{ {
name: "invalid log level", name: "invalid log level",
modify: func(c *Config) { c.Log.Level = testInvalid }, modify: func(c *Config) { c.Log.Level = "invalid" },
wantErr: true, wantErr: true,
}, },
{ {
name: "invalid log format", name: "invalid log format",
modify: func(c *Config) { c.Log.Format = testInvalid }, modify: func(c *Config) { c.Log.Format = "invalid" },
wantErr: true, wantErr: true,
}, },
{ {
name: "invalid max size", name: "invalid max size",
modify: func(c *Config) { c.Storage.MaxSize = testInvalid }, modify: func(c *Config) { c.Storage.MaxSize = "invalid" },
wantErr: true, wantErr: true,
}, },
{ {
@ -117,41 +91,6 @@ func TestValidate(t *testing.T) {
modify: func(c *Config) { c.Storage.MaxSize = "10GB" }, modify: func(c *Config) { c.Storage.MaxSize = "10GB" },
wantErr: false, wantErr: false,
}, },
{
name: "invalid gradle upload size",
modify: func(c *Config) { c.Gradle.BuildCache.MaxUploadSize = testInvalid },
wantErr: true,
},
{
name: "zero gradle upload size",
modify: func(c *Config) { c.Gradle.BuildCache.MaxUploadSize = "0" },
wantErr: true,
},
{
name: "invalid gradle max age",
modify: func(c *Config) { c.Gradle.BuildCache.MaxAge = testInvalid },
wantErr: true,
},
{
name: "valid gradle max age",
modify: func(c *Config) { c.Gradle.BuildCache.MaxAge = "24h" },
wantErr: false,
},
{
name: "invalid gradle max size",
modify: func(c *Config) { c.Gradle.BuildCache.MaxSize = testInvalid },
wantErr: true,
},
{
name: "invalid gradle sweep interval",
modify: func(c *Config) { c.Gradle.BuildCache.SweepInterval = "0" },
wantErr: true,
},
{
name: "valid gradle sweep interval",
modify: func(c *Config) { c.Gradle.BuildCache.SweepInterval = "30m" },
wantErr: false,
},
} }
for _, tt := range tests { for _, tt := range tests {
@ -215,8 +154,6 @@ database:
log: log:
level: "debug" level: "debug"
format: "json" format: "json"
access_log:
path: "/var/log/proxy/access.jsonl"
` `
if err := os.WriteFile(path, []byte(content), 0644); err != nil { if err := os.WriteFile(path, []byte(content), 0644); err != nil {
t.Fatalf("writing config file: %v", err) t.Fatalf("writing config file: %v", err)
@ -239,15 +176,12 @@ access_log:
if cfg.Storage.MaxSize != "5GB" { if cfg.Storage.MaxSize != "5GB" {
t.Errorf("Storage.MaxSize = %q, want %q", cfg.Storage.MaxSize, "5GB") t.Errorf("Storage.MaxSize = %q, want %q", cfg.Storage.MaxSize, "5GB")
} }
if cfg.Log.Level != testLevelDebug { if cfg.Log.Level != "debug" {
t.Errorf("Log.Level = %q, want %q", cfg.Log.Level, testLevelDebug) t.Errorf("Log.Level = %q, want %q", cfg.Log.Level, "debug")
} }
if cfg.Log.Format != "json" { if cfg.Log.Format != "json" {
t.Errorf("Log.Format = %q, want %q", cfg.Log.Format, "json") t.Errorf("Log.Format = %q, want %q", cfg.Log.Format, "json")
} }
if cfg.AccessLog.Path != "/var/log/proxy/access.jsonl" {
t.Errorf("AccessLog.Path = %q, want %q", cfg.AccessLog.Path, "/var/log/proxy/access.jsonl")
}
} }
func TestLoadJSON(t *testing.T) { func TestLoadJSON(t *testing.T) {
@ -280,18 +214,8 @@ func TestLoadFromEnv(t *testing.T) {
t.Setenv("PROXY_LISTEN", ":9000") t.Setenv("PROXY_LISTEN", ":9000")
t.Setenv("PROXY_BASE_URL", "https://env.example.com") t.Setenv("PROXY_BASE_URL", "https://env.example.com")
t.Setenv("PROXY_UI_URL", "https://ui.env.example.com/ui")
t.Setenv("PROXY_STORAGE_PATH", "/env/cache") t.Setenv("PROXY_STORAGE_PATH", "/env/cache")
t.Setenv("PROXY_LOG_LEVEL", testLevelDebug) t.Setenv("PROXY_LOG_LEVEL", "debug")
t.Setenv("PROXY_ACCESS_LOG_PATH", "/tmp/proxy-access.jsonl")
t.Setenv("PROXY_UPSTREAM_MAVEN", "https://maven.example.com/repository/maven-public")
t.Setenv("PROXY_UPSTREAM_GRADLE_PLUGIN_PORTAL", "https://plugins.example.com/m2")
t.Setenv("PROXY_UPSTREAM_DEBIAN", "http://archive.ubuntu.com/ubuntu")
t.Setenv("PROXY_GRADLE_BUILD_CACHE_READ_ONLY", "true")
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")
t.Setenv("PROXY_GRADLE_BUILD_CACHE_SWEEP_INTERVAL", "15m")
cfg.LoadFromEnv() cfg.LoadFromEnv()
@ -301,125 +225,11 @@ func TestLoadFromEnv(t *testing.T) {
if cfg.BaseURL != "https://env.example.com" { if cfg.BaseURL != "https://env.example.com" {
t.Errorf("BaseURL = %q, want %q", cfg.BaseURL, "https://env.example.com") t.Errorf("BaseURL = %q, want %q", cfg.BaseURL, "https://env.example.com")
} }
if cfg.UIBaseURL != "https://ui.env.example.com/ui" {
t.Errorf("UIBaseURL = %q, want %q", cfg.UIBaseURL, "https://ui.env.example.com/ui")
}
if cfg.Storage.Path != "/env/cache" { if cfg.Storage.Path != "/env/cache" {
t.Errorf("Storage.Path = %q, want %q", cfg.Storage.Path, "/env/cache") t.Errorf("Storage.Path = %q, want %q", cfg.Storage.Path, "/env/cache")
} }
if cfg.Log.Level != testLevelDebug { if cfg.Log.Level != "debug" {
t.Errorf("Log.Level = %q, want %q", cfg.Log.Level, testLevelDebug) t.Errorf("Log.Level = %q, want %q", cfg.Log.Level, "debug")
}
if cfg.AccessLog.Path != "/tmp/proxy-access.jsonl" {
t.Errorf("AccessLog.Path = %q, want %q", cfg.AccessLog.Path, "/tmp/proxy-access.jsonl")
}
if cfg.Upstream.Maven != "https://maven.example.com/repository/maven-public" {
t.Errorf("Upstream.Maven = %q, want %q", cfg.Upstream.Maven, "https://maven.example.com/repository/maven-public")
}
if cfg.Upstream.GradlePluginPortal != "https://plugins.example.com/m2" {
t.Errorf("Upstream.GradlePluginPortal = %q, want %q", cfg.Upstream.GradlePluginPortal, "https://plugins.example.com/m2")
}
if cfg.Upstream.Debian != "http://archive.ubuntu.com/ubuntu" {
t.Errorf("Upstream.Debian = %q, want %q", cfg.Upstream.Debian, "http://archive.ubuntu.com/ubuntu")
}
if !cfg.Gradle.BuildCache.ReadOnly {
t.Error("Gradle.BuildCache.ReadOnly = false, want true")
}
if cfg.Gradle.BuildCache.MaxUploadSize != "32MB" {
t.Errorf("Gradle.BuildCache.MaxUploadSize = %q, want %q", cfg.Gradle.BuildCache.MaxUploadSize, "32MB")
}
if cfg.Gradle.BuildCache.MaxAge != "12h" {
t.Errorf("Gradle.BuildCache.MaxAge = %q, want %q", cfg.Gradle.BuildCache.MaxAge, "12h")
}
if cfg.Gradle.BuildCache.MaxSize != "10GB" {
t.Errorf("Gradle.BuildCache.MaxSize = %q, want %q", cfg.Gradle.BuildCache.MaxSize, "10GB")
}
if cfg.Gradle.BuildCache.SweepInterval != "15m" {
t.Errorf("Gradle.BuildCache.SweepInterval = %q, want %q", cfg.Gradle.BuildCache.SweepInterval, "15m")
}
}
func TestLoadCooldownConfig(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "config.yaml")
content := `
listen: ":8080"
base_url: "http://localhost:8080"
storage:
path: "/data/cache"
database:
path: "/data/proxy.db"
cooldown:
default: "3d"
ecosystems:
npm: "7d"
cargo: "0"
packages:
"pkg:npm/lodash": "0"
"pkg:npm/@babel/core": "14d"
`
if err := os.WriteFile(path, []byte(content), 0644); err != nil {
t.Fatalf("writing config file: %v", err)
}
cfg, err := Load(path)
if err != nil {
t.Fatalf("Load failed: %v", err)
}
if cfg.Cooldown.Default != "3d" {
t.Errorf("Cooldown.Default = %q, want %q", cfg.Cooldown.Default, "3d")
}
if cfg.Cooldown.Ecosystems["npm"] != "7d" {
t.Errorf("Cooldown.Ecosystems[npm] = %q, want %q", cfg.Cooldown.Ecosystems["npm"], "7d")
}
if cfg.Cooldown.Ecosystems["cargo"] != "0" {
t.Errorf("Cooldown.Ecosystems[cargo] = %q, want %q", cfg.Cooldown.Ecosystems["cargo"], "0")
}
if cfg.Cooldown.Packages["pkg:npm/lodash"] != "0" {
t.Errorf("Cooldown.Packages[lodash] = %q, want %q", cfg.Cooldown.Packages["pkg:npm/lodash"], "0")
}
if cfg.Cooldown.Packages["pkg:npm/@babel/core"] != "14d" {
t.Errorf("Cooldown.Packages[@babel/core] = %q, want %q", cfg.Cooldown.Packages["pkg:npm/@babel/core"], "14d")
}
if got := cfg.Cooldown.NormalizedPackages()["pkg:npm/%40babel/core"]; got != "14d" {
t.Errorf("normalized Cooldown.Packages[@babel/core] = %q, want %q", got, "14d")
}
}
func TestCooldownConfigNormalizedPackages(t *testing.T) {
rawScoped := "pkg:npm/@typescript/typescript-darwin-arm64"
canonicalScoped := "pkg:npm/%40typescript/typescript-darwin-arm64"
cfg := CooldownConfig{Packages: map[string]string{
rawScoped: "2d",
canonicalScoped: "3d",
"not-a-purl": "4d",
}}
got := cfg.NormalizedPackages()
if got[canonicalScoped] != "3d" {
t.Errorf("canonical scoped package duration = %q, want %q", got[canonicalScoped], "3d")
}
if _, exists := got[rawScoped]; exists {
t.Errorf("raw scoped package key %q was not canonicalized", rawScoped)
}
if got["not-a-purl"] != "4d" {
t.Errorf("invalid PURL duration = %q, want preserved value %q", got["not-a-purl"], "4d")
}
if cfg.Packages[rawScoped] != "2d" {
t.Error("NormalizedPackages mutated the source map")
}
}
func TestLoadCooldownFromEnv(t *testing.T) {
cfg := Default()
t.Setenv("PROXY_COOLDOWN_DEFAULT", "5d")
cfg.LoadFromEnv()
if cfg.Cooldown.Default != "5d" {
t.Errorf("Cooldown.Default = %q, want %q", cfg.Cooldown.Default, "5d")
} }
} }
@ -429,493 +239,3 @@ func TestLoadFileNotFound(t *testing.T) {
t.Error("expected error for nonexistent file") t.Error("expected error for nonexistent file")
} }
} }
func TestParseMaxSize(t *testing.T) {
tests := []struct {
name string
maxSize string
want int64
}{
{"empty means unlimited", "", 0},
{"zero means unlimited", "0", 0},
{"10GB", "10GB", 10 * 1024 * 1024 * 1024},
{"500MB", "500MB", 500 * 1024 * 1024},
{"invalid returns 0", "invalid", 0},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
cfg := Default()
cfg.Storage.MaxSize = tt.maxSize
got := cfg.ParseMaxSize()
if got != tt.want {
t.Errorf("ParseMaxSize() = %d, want %d", got, tt.want)
}
})
}
}
func TestParseMetadataTTL(t *testing.T) {
tests := []struct {
name string
ttl string
want time.Duration
}{
{"empty defaults to 5m", "", 5 * time.Minute},
{"explicit zero", "0", 0},
{"10 minutes", "10m", 10 * time.Minute},
{"1 hour", "1h", 1 * time.Hour},
{"invalid defaults to 5m", "not-a-duration", 5 * time.Minute},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
cfg := Default()
cfg.MetadataTTL = tt.ttl
got := cfg.ParseMetadataTTL()
if got != tt.want {
t.Errorf("ParseMetadataTTL() = %v, want %v", got, tt.want)
}
})
}
}
func TestParseMetadataMaxSize(t *testing.T) {
tests := []struct {
name string
size string
want int64
}{
{"unset uses default", "", defaultMetadataMaxSize},
{"explicit value", "250MB", 250 << 20},
{"bytes", "1024", 1024},
{"invalid uses default", "lots", defaultMetadataMaxSize},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
cfg := Default()
cfg.MetadataMaxSize = tt.size
got := cfg.ParseMetadataMaxSize()
if got != tt.want {
t.Errorf("ParseMetadataMaxSize() = %d, want %d", got, tt.want)
}
})
}
}
func TestValidateMetadataMaxSize(t *testing.T) {
cfg := Default()
cfg.MetadataMaxSize = "not-a-size"
if err := cfg.Validate(); err == nil {
t.Error("expected validation error for invalid metadata_max_size")
}
cfg.MetadataMaxSize = "0"
if err := cfg.Validate(); err == nil {
t.Error("expected validation error for zero metadata_max_size")
}
cfg.MetadataMaxSize = "250MB"
if err := cfg.Validate(); err != nil {
t.Errorf("unexpected error for valid metadata_max_size: %v", err)
}
cfg.MetadataMaxSize = ""
if err := cfg.Validate(); err != nil {
t.Errorf("unexpected error for unset metadata_max_size: %v", err)
}
}
func TestValidateMetadataTTL(t *testing.T) {
cfg := Default()
cfg.MetadataTTL = "invalid"
if err := cfg.Validate(); err == nil {
t.Error("expected validation error for invalid metadata_ttl")
}
cfg.MetadataTTL = "5m"
if err := cfg.Validate(); err != nil {
t.Errorf("unexpected error for valid metadata_ttl: %v", err)
}
cfg.MetadataTTL = "0"
if err := cfg.Validate(); err != nil {
t.Errorf("unexpected error for zero metadata_ttl: %v", err)
}
}
func TestValidateHealthStorageProbeInterval(t *testing.T) {
cfg := Default()
cfg.Health.StorageProbeInterval = "not-a-duration"
if err := cfg.Validate(); err == nil {
t.Error("expected validation error for invalid health.storage_probe_interval")
}
cfg.Health.StorageProbeInterval = "30s"
if err := cfg.Validate(); err != nil {
t.Errorf("unexpected error for valid health.storage_probe_interval: %v", err)
}
cfg.Health.StorageProbeInterval = "0"
if err := cfg.Validate(); err != nil {
t.Errorf("unexpected error for zero health.storage_probe_interval: %v", err)
}
cfg.Health.StorageProbeInterval = ""
if err := cfg.Validate(); err != nil {
t.Errorf("unexpected error for empty health.storage_probe_interval: %v", err)
}
cfg.Health.StorageProbeInterval = "-5s"
if err := cfg.Validate(); err == nil {
t.Error("expected validation error for negative health.storage_probe_interval")
}
}
func TestParseHTTPTimeout(t *testing.T) {
tests := []struct {
name string
timeout string
want time.Duration
}{
{"empty defaults to 30s", "", 30 * time.Second},
{"explicit zero disables", "0", 0},
{"2 minutes", "2m", 2 * time.Minute},
{"90 seconds", "90s", 90 * time.Second},
{"invalid defaults to 30s", "not-a-duration", 30 * time.Second},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
cfg := Default()
cfg.HTTPTimeout = tt.timeout
got := cfg.ParseHTTPTimeout()
if got != tt.want {
t.Errorf("ParseHTTPTimeout() = %v, want %v", got, tt.want)
}
})
}
}
func TestValidateHTTPTimeout(t *testing.T) {
cfg := Default()
cfg.HTTPTimeout = "not-a-duration"
if err := cfg.Validate(); err == nil {
t.Error("expected validation error for invalid http_timeout")
}
cfg.HTTPTimeout = "-5s"
if err := cfg.Validate(); err == nil {
t.Error("expected validation error for negative http_timeout")
}
cfg.HTTPTimeout = "2m"
if err := cfg.Validate(); err != nil {
t.Errorf("unexpected error for valid http_timeout: %v", err)
}
cfg.HTTPTimeout = "0"
if err := cfg.Validate(); err != nil {
t.Errorf("unexpected error for zero http_timeout: %v", err)
}
cfg.HTTPTimeout = ""
if err := cfg.Validate(); err != nil {
t.Errorf("unexpected error for empty http_timeout: %v", err)
}
}
func TestLoadHTTPTimeoutFromEnv(t *testing.T) {
cfg := Default()
t.Setenv("PROXY_HTTP_TIMEOUT", "90s")
cfg.LoadFromEnv()
if cfg.HTTPTimeout != "90s" {
t.Errorf("HTTPTimeout = %q, want %q", cfg.HTTPTimeout, "90s")
}
}
func TestLoadMetadataTTLFromEnv(t *testing.T) {
cfg := Default()
t.Setenv("PROXY_METADATA_TTL", "10m")
cfg.LoadFromEnv()
if cfg.MetadataTTL != "10m" {
t.Errorf("MetadataTTL = %q, want %q", cfg.MetadataTTL, "10m")
}
}
func TestParseGradleBuildCacheConfig(t *testing.T) {
cfg := Default()
if got := cfg.ParseGradleBuildCacheMaxUploadSize(); got != 100*1024*1024 {
t.Errorf("ParseGradleBuildCacheMaxUploadSize() = %d, want %d", got, 100*1024*1024)
}
if got := cfg.ParseGradleBuildCacheMaxAge(); got != 168*time.Hour {
t.Errorf("ParseGradleBuildCacheMaxAge() = %v, want %v", got, 168*time.Hour)
}
if got := cfg.ParseGradleBuildCacheMaxSize(); got != 0 {
t.Errorf("ParseGradleBuildCacheMaxSize() = %d, want 0", got)
}
if got := cfg.ParseGradleBuildCacheSweepInterval(); got != 10*time.Minute {
t.Errorf("ParseGradleBuildCacheSweepInterval() = %v, want %v", got, 10*time.Minute)
}
cfg.Gradle.BuildCache.MaxUploadSize = "64MB"
cfg.Gradle.BuildCache.MaxAge = "48h"
cfg.Gradle.BuildCache.MaxSize = "2GB"
cfg.Gradle.BuildCache.SweepInterval = "20m"
if got := cfg.ParseGradleBuildCacheMaxUploadSize(); got != 64*1024*1024 {
t.Errorf("ParseGradleBuildCacheMaxUploadSize() = %d, want %d", got, 64*1024*1024)
}
if got := cfg.ParseGradleBuildCacheMaxAge(); got != 48*time.Hour {
t.Errorf("ParseGradleBuildCacheMaxAge() = %v, want %v", got, 48*time.Hour)
}
if got := cfg.ParseGradleBuildCacheMaxSize(); got != 2*1024*1024*1024 {
t.Errorf("ParseGradleBuildCacheMaxSize() = %d, want %d", got, 2*1024*1024*1024)
}
if got := cfg.ParseGradleBuildCacheSweepInterval(); got != 20*time.Minute {
t.Errorf("ParseGradleBuildCacheSweepInterval() = %v, want %v", got, 20*time.Minute)
}
}
func TestParseDirectServeTTL(t *testing.T) {
tests := []struct {
name string
ttl string
want time.Duration
}{
{"empty defaults to 15m", "", 15 * time.Minute},
{"5 minutes", "5m", 5 * time.Minute},
{"1 hour", "1h", 1 * time.Hour},
{"invalid defaults to 15m", "not-a-duration", 15 * time.Minute},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
cfg := Default()
cfg.Storage.DirectServeTTL = tt.ttl
got := cfg.ParseDirectServeTTL()
if got != tt.want {
t.Errorf("ParseDirectServeTTL() = %v, want %v", got, tt.want)
}
})
}
}
func TestValidateDirectServeTTL(t *testing.T) {
cfg := Default()
cfg.Storage.DirectServeTTL = "invalid"
if err := cfg.Validate(); err == nil {
t.Error("expected validation error for invalid storage.direct_serve_ttl")
}
cfg.Storage.DirectServeTTL = "5m"
if err := cfg.Validate(); err != nil {
t.Errorf("unexpected error for valid storage.direct_serve_ttl: %v", err)
}
}
func TestLoadDirectServeFromEnv(t *testing.T) {
cfg := Default()
t.Setenv("PROXY_STORAGE_DIRECT_SERVE", "true")
t.Setenv("PROXY_STORAGE_DIRECT_SERVE_TTL", "30m")
t.Setenv("PROXY_STORAGE_DIRECT_SERVE_BASE_URL", "https://cdn.example.com")
cfg.LoadFromEnv()
if !cfg.Storage.DirectServe {
t.Error("Storage.DirectServe should be true")
}
if cfg.Storage.DirectServeTTL != "30m" {
t.Errorf("Storage.DirectServeTTL = %q, want %q", cfg.Storage.DirectServeTTL, "30m")
}
if cfg.Storage.DirectServeBaseURL != "https://cdn.example.com" {
t.Errorf("Storage.DirectServeBaseURL = %q, want %q", cfg.Storage.DirectServeBaseURL, "https://cdn.example.com")
}
}
func TestValidateUIBaseURLDefaultsToBaseURL(t *testing.T) {
cfg := Default()
cfg.BaseURL = "https://proxy.example.com"
cfg.UIBaseURL = ""
if err := cfg.Validate(); err != nil {
t.Fatalf("unexpected validation error: %v", err)
}
if cfg.UIBaseURL != "https://proxy.example.com" {
t.Errorf("UIBaseURL = %q, want it to default to BaseURL %q", cfg.UIBaseURL, "https://proxy.example.com")
}
}
func TestValidateUIBaseURL(t *testing.T) {
cfg := Default()
cfg.UIBaseURL = "not a url"
if err := cfg.Validate(); err == nil {
t.Error("expected validation error for relative ui_base_url")
}
cfg = Default()
cfg.UIBaseURL = "://bad"
if err := cfg.Validate(); err == nil {
t.Error("expected validation error for unparseable ui_base_url")
}
cfg = Default()
cfg.UIBaseURL = "https://ui.example.com/ui"
if err := cfg.Validate(); err != nil {
t.Errorf("unexpected error for valid ui_base_url: %v", err)
}
}
func TestValidateDirectServeBaseURL(t *testing.T) {
cfg := Default()
cfg.Storage.DirectServeBaseURL = "not a url"
if err := cfg.Validate(); err == nil {
t.Error("expected validation error for relative direct_serve_base_url")
}
cfg.Storage.DirectServeBaseURL = "://bad"
if err := cfg.Validate(); err == nil {
t.Error("expected validation error for unparseable direct_serve_base_url")
}
cfg.Storage.DirectServeBaseURL = "https://cdn.example.com"
if err := cfg.Validate(); err != nil {
t.Errorf("unexpected error for valid direct_serve_base_url: %v", err)
}
}
func TestDatabaseConfigString(t *testing.T) {
tests := []struct {
name string
cfg DatabaseConfig
want string
}{
{"sqlite", DatabaseConfig{Driver: "sqlite", Path: "./cache/proxy.db"}, "./cache/proxy.db"},
{"default driver", DatabaseConfig{Path: "/var/lib/proxy.db"}, "/var/lib/proxy.db"},
{"postgres no password", DatabaseConfig{Driver: "postgres", URL: "postgres://user@localhost:5432/proxy"}, "postgres://user@localhost:5432/proxy"},
{"postgres redacts password", DatabaseConfig{Driver: "postgres", URL: "postgres://user:secret@localhost:5432/proxy?sslmode=disable"}, "postgres://user:xxxxx@localhost:5432/proxy?sslmode=disable"},
{"postgres unparseable url", DatabaseConfig{Driver: "postgres", URL: "host=localhost user=foo password=bar"}, "postgres"},
{"postgres ignores sqlite path", DatabaseConfig{Driver: "postgres", URL: "postgres://localhost/db", Path: "./cache/proxy.db"}, "postgres://localhost/db"},
}
for _, tt := range tests {
if got := tt.cfg.String(); got != tt.want {
t.Errorf("%s: String() = %q, want %q", tt.name, got, tt.want)
}
}
}
func TestUpstreamAuthForURLMatchesURLComponents(t *testing.T) {
registryAuth := AuthConfig{Type: "bearer", Token: "registry-token"}
privateAuth := AuthConfig{Type: "bearer", Token: "private-token"}
config := UpstreamConfig{Auth: map[string]AuthConfig{
"https://registry.example.com": registryAuth,
"https://registry.example.com/private": privateAuth,
}}
tests := []struct {
name string
url string
wantToken string
}{
{name: "registry root", url: "https://registry.example.com/package", wantToken: "registry-token"},
{name: "host is case insensitive", url: "https://REGISTRY.EXAMPLE.COM/package", wantToken: "registry-token"},
{name: "longest path match", url: "https://registry.example.com/private/package", wantToken: "private-token"},
{name: "exact path match", url: "https://registry.example.com/private", wantToken: "private-token"},
{name: "path segment boundary", url: "https://registry.example.com/private-other/package", wantToken: "registry-token"},
{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"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
auth := config.AuthForURL(tt.url)
if tt.wantToken == "" {
if auth != nil {
t.Fatalf("AuthForURL() = %+v, want nil", auth)
}
return
}
if auth == nil {
t.Fatal("AuthForURL() = nil, want authentication")
}
if auth.Token != tt.wantToken {
t.Errorf("token = %q, want %q", auth.Token, tt.wantToken)
}
})
}
}
func TestValidateUpstreamAuthURLs(t *testing.T) {
t.Run("valid absolute URL", func(t *testing.T) {
cfg := Default()
cfg.Upstream.Auth = map[string]AuthConfig{
"https://registry.example.com/private": {Type: "bearer", Token: "token"},
}
if err := cfg.Validate(); err != nil {
t.Fatalf("Validate() error = %v", err)
}
})
t.Run("invalid URL", func(t *testing.T) {
cfg := Default()
cfg.Upstream.Auth = map[string]AuthConfig{
"registry.example.com": {Type: "bearer", Token: "token"},
}
err := cfg.Validate()
if err == nil {
t.Fatal("Validate() error = nil, want invalid upstream.auth URL error")
}
if !strings.Contains(err.Error(), "upstream.auth") || !strings.Contains(err.Error(), "registry.example.com") {
t.Errorf("Validate() error = %q, want field and URL", err)
}
})
}
func TestValidateNamedUpstreams(t *testing.T) {
tests := []struct {
name string
modify func(*Config)
wantErr bool
}{
{
name: "valid Helm and OCI upstreams",
modify: func(cfg *Config) {
cfg.Upstream.Helm = map[string]string{"bitnami": "https://charts.bitnami.com/bitnami"}
cfg.Upstream.OCI = map[string]string{"ghcr": "https://ghcr.io"}
},
},
{
name: "Helm upstream name contains path separator",
modify: func(cfg *Config) {
cfg.Upstream.Helm = map[string]string{"team/charts": "https://charts.example.com"}
},
wantErr: true,
},
{
name: "OCI upstream URL is not absolute",
modify: func(cfg *Config) {
cfg.Upstream.OCI = map[string]string{"private": "registry.example.com"}
},
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
cfg := Default()
tt.modify(cfg)
err := cfg.Validate()
if (err != nil) != tt.wantErr {
t.Errorf("Validate() error = %v, wantErr %t", err, tt.wantErr)
}
})
}
}

View file

@ -5,6 +5,7 @@ import (
"os" "os"
"path/filepath" "path/filepath"
gitpkgsdb "github.com/git-pkgs/git-pkgs/database"
"github.com/jmoiron/sqlx" "github.com/jmoiron/sqlx"
_ "github.com/lib/pq" _ "github.com/lib/pq"
_ "modernc.org/sqlite" _ "modernc.org/sqlite"
@ -12,8 +13,6 @@ import (
const SchemaVersion = 1 const SchemaVersion = 1
const dirPermissions = 0755
type Dialect string type Dialect string
const ( const (
@ -31,10 +30,8 @@ func (db *DB) Dialect() Dialect {
return db.dialect return db.dialect
} }
func Exists(path string) bool { // Exists checks if a database file exists at the given path.
_, err := os.Stat(path) var Exists = gitpkgsdb.Exists
return err == nil
}
func Create(path string) (*DB, error) { func Create(path string) (*DB, error) {
if Exists(path) { if Exists(path) {
@ -56,29 +53,21 @@ func Create(path string) (*DB, error) {
return db, nil return db, nil
} }
// Open opens a SQLite database using the shared git-pkgs connection
// settings (WAL mode, busy timeout, single connection).
func Open(path string) (*DB, error) { func Open(path string) (*DB, error) {
if dir := filepath.Dir(path); dir != "." && dir != "/" { if dir := filepath.Dir(path); dir != "." && dir != "/" {
if err := os.MkdirAll(dir, dirPermissions); err != nil { if err := os.MkdirAll(dir, 0755); err != nil {
return nil, fmt.Errorf("creating database directory: %w", err) return nil, fmt.Errorf("creating database directory: %w", err)
} }
} }
// Add busy_timeout to handle concurrent writes sharedDB, err := gitpkgsdb.Open(path)
sqlDB, err := sqlx.Open("sqlite", path+"?_busy_timeout=5000")
if err != nil { if err != nil {
return nil, fmt.Errorf("opening database: %w", err) return nil, err
} }
// Limit connections to 1 for SQLite to serialize writes return &DB{DB: sharedDB.SQLX(), dialect: DialectSQLite, path: path}, nil
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)
}
return db, nil
} }
func OpenOrCreate(path string) (*DB, error) { func OpenOrCreate(path string) (*DB, error) {

View file

@ -8,11 +8,6 @@ import (
"time" "time"
) )
const (
testContentHash = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
testIntegrity = "sha512-z4PhNX7vuL3xVChQ1m2AB9Yg5AULVxXcg/SpIdNs6c5H0NE8XYXysP+DGNKHfuwvY7kxvUdBeoGlODJ6+SfaPg=="
)
func TestCreateAndOpen(t *testing.T) { func TestCreateAndOpen(t *testing.T) {
dir := t.TempDir() dir := t.TempDir()
dbPath := filepath.Join(dir, "test.db") dbPath := filepath.Join(dir, "test.db")
@ -137,7 +132,7 @@ func TestVersionCRUD(t *testing.T) {
v := &Version{ v := &Version{
PURL: "pkg:npm/lodash@4.17.21", PURL: "pkg:npm/lodash@4.17.21",
PackagePURL: "pkg:npm/lodash", PackagePURL: "pkg:npm/lodash",
Integrity: sql.NullString{String: testIntegrity, Valid: true}, Integrity: sql.NullString{String: "sha512-abc123", Valid: true},
} }
err = db.UpsertVersion(v) err = db.UpsertVersion(v)
@ -152,8 +147,8 @@ func TestVersionCRUD(t *testing.T) {
if got == nil { if got == nil {
t.Fatal("expected version, got nil") t.Fatal("expected version, got nil")
} }
if got.Version() != "4.17.21" { if got.VersionString() != "4.17.21" {
t.Errorf("expected version 4.17.21, got %s", got.Version()) t.Errorf("expected version 4.17.21, got %s", got.VersionString())
} }
versions, err := db.GetVersionsByPackagePURL("pkg:npm/lodash") versions, err := db.GetVersionsByPackagePURL("pkg:npm/lodash")
@ -205,7 +200,7 @@ func TestArtifactCRUD(t *testing.T) {
t.Error("expected artifact to not be cached yet") t.Error("expected artifact to not be cached yet")
} }
err = db.MarkArtifactCached(versionPURL, "lodash-4.17.21.tgz", "/cache/npm/lodash-4.17.21.tgz", testContentHash, 12345, "application/gzip") err = db.MarkArtifactCached(versionPURL, "lodash-4.17.21.tgz", "/cache/npm/lodash-4.17.21.tgz", "sha256-abc", 12345, "application/gzip")
if err != nil { if err != nil {
t.Fatalf("MarkArtifactCached failed: %v", err) t.Fatalf("MarkArtifactCached failed: %v", err)
} }
@ -244,86 +239,6 @@ func TestArtifactCRUD(t *testing.T) {
}) })
} }
func TestGetCachedArtifact(t *testing.T) {
runWithBothDatabases(t, func(t *testing.T, db *DB) {
const (
packagePURL = "pkg:npm/lodash"
versionPURL = "pkg:npm/lodash@4.17.21"
filename = "lodash-4.17.21.tgz"
)
seedCachedArtifactTestData(t, db, packagePURL, versionPURL, filename)
cached, err := db.GetCachedArtifact(packagePURL, versionPURL, filename)
if err != nil {
t.Fatalf("GetCachedArtifact before cache failed: %v", err)
}
if cached != nil {
t.Fatalf("expected no cached artifact, got %+v", cached)
}
if err := db.MarkArtifactCached(versionPURL, filename, "/cache/npm/"+filename,
testContentHash, 12345, "application/gzip"); err != nil {
t.Fatalf("MarkArtifactCached failed: %v", err)
}
cached, err = db.GetCachedArtifact(packagePURL, versionPURL, filename)
if err != nil {
t.Fatalf("GetCachedArtifact failed: %v", err)
}
if cached == nil {
t.Fatal("expected cached artifact, got nil")
}
if cached.Ecosystem != "npm" {
t.Errorf("expected npm ecosystem, got %q", cached.Ecosystem)
}
if cached.StoragePath != "/cache/npm/"+filename {
t.Errorf("expected cached storage path, got %q", cached.StoragePath)
}
if cached.ContentHash.String != testContentHash {
t.Errorf("expected cached content hash, got %q", cached.ContentHash.String)
}
if cached.Size.Int64 != 12345 {
t.Errorf("expected cached size 12345, got %d", cached.Size.Int64)
}
if cached.ContentType.String != "application/gzip" {
t.Errorf("expected cached content type, got %q", cached.ContentType.String)
}
if cached.Integrity.String != testIntegrity {
t.Errorf("expected cached integrity, got %q", cached.Integrity.String)
}
cached, err = db.GetCachedArtifact("pkg:npm/other", versionPURL, filename)
if err != nil {
t.Fatalf("GetCachedArtifact with wrong package failed: %v", err)
}
if cached != nil {
t.Fatalf("expected package mismatch to miss cache, got %+v", cached)
}
})
}
func seedCachedArtifactTestData(t *testing.T, db *DB, packagePURL, versionPURL, filename string) {
t.Helper()
if err := db.UpsertPackage(&Package{PURL: packagePURL, Ecosystem: "npm", Name: "lodash"}); err != nil {
t.Fatalf("UpsertPackage failed: %v", err)
}
if err := db.UpsertVersion(&Version{
PURL: versionPURL,
PackagePURL: packagePURL,
Integrity: sql.NullString{String: testIntegrity, Valid: true},
}); err != nil {
t.Fatalf("UpsertVersion failed: %v", err)
}
if err := db.UpsertArtifact(&Artifact{
VersionPURL: versionPURL,
Filename: filename,
UpstreamURL: "https://registry.npmjs.org/lodash/-/" + filename,
}); err != nil {
t.Fatalf("UpsertArtifact failed: %v", err)
}
}
func TestCacheManagement(t *testing.T) { func TestCacheManagement(t *testing.T) {
runWithBothDatabases(t, func(t *testing.T, db *DB) { runWithBothDatabases(t, func(t *testing.T, db *DB) {
pkg := &Package{ pkg := &Package{
@ -736,159 +651,58 @@ func TestMigrationFromOldSchema(t *testing.T) {
} }
defer func() { _ = db.Close() }() defer func() { _ = db.Close() }()
// Queries that require new columns should fail without migration // Try to run queries that require new columns - these should fail without migration
if _, err := db.GetEnrichmentStats(); err == nil { t.Run("queries should fail without migration", func(t *testing.T) {
t.Error("GetEnrichmentStats: expected error querying enriched_at column, got nil") _, err := db.GetEnrichmentStats()
} if err == nil {
if _, err := db.GetPackageByEcosystemName("npm", "test-package"); err == nil { t.Error("GetEnrichmentStats: expected error querying enriched_at column, got nil")
t.Error("GetPackageByEcosystemName: expected error querying registry_url column, got nil") }
}
// SearchPackages should work even with old schema because it uses sql.NullString _, err = db.GetPackageByEcosystemName("npm", "test-package")
if _, err := db.SearchPackages("test", "", 10, 0); err != nil { if err == nil {
t.Errorf("SearchPackages: unexpected error with old schema: %v", err) t.Error("GetPackageByEcosystemName: expected error querying registry_url column, got nil")
} }
// SearchPackages should work even with old schema because it uses sql.NullString
// for nullable columns, which can handle NULL values properly
_, err = db.SearchPackages("test", "", 10, 0)
if err != nil {
t.Errorf("SearchPackages: unexpected error with old schema: %v", err)
}
})
// Run migration // Run migration
if err := db.MigrateSchema(); err != nil { t.Run("migrate schema", func(t *testing.T) {
t.Fatalf("MigrateSchema failed: %v", err) if err := db.MigrateSchema(); err != nil {
} t.Fatalf("MigrateSchema failed: %v", err)
}
})
// Verify queries work after migration // Verify queries work after migration
stats, err := db.GetEnrichmentStats() t.Run("queries should work after migration", func(t *testing.T) {
if err != nil { stats, err := db.GetEnrichmentStats()
t.Errorf("GetEnrichmentStats failed after migration: %v", err) if err != nil {
} t.Errorf("GetEnrichmentStats failed after migration: %v", err)
if stats == nil {
t.Error("GetEnrichmentStats returned nil after migration")
}
pkg, err := db.GetPackageByEcosystemName("npm", "test-package")
if err != nil {
t.Errorf("GetPackageByEcosystemName failed after migration: %v", err)
}
if pkg == nil {
t.Fatal("GetPackageByEcosystemName returned nil after migration")
}
if pkg.Name != "test-package" {
t.Errorf("expected package name test-package, got %s", pkg.Name)
}
// Verify migrations were recorded
applied, err := db.appliedMigrations()
if err != nil {
t.Fatalf("appliedMigrations failed: %v", err)
}
for _, m := range migrations {
if !applied[m.name] {
t.Errorf("migration %s not recorded as applied", m.name)
} }
} if stats == nil {
t.Error("GetEnrichmentStats returned nil after migration")
// Running again should be a no-op
if err := db.MigrateSchema(); err != nil {
t.Fatalf("second MigrateSchema failed: %v", err)
}
}
func TestFreshDatabaseRecordsMigrations(t *testing.T) {
dir := t.TempDir()
dbPath := filepath.Join(dir, "fresh.db")
db, err := Create(dbPath)
if err != nil {
t.Fatalf("Create failed: %v", err)
}
defer func() { _ = db.Close() }()
applied, err := db.appliedMigrations()
if err != nil {
t.Fatalf("appliedMigrations failed: %v", err)
}
for _, m := range migrations {
if !applied[m.name] {
t.Errorf("migration %s not recorded in fresh database", m.name)
} }
}
}
func TestMigrateSchemaSkipsApplied(t *testing.T) { pkg, err := db.GetPackageByEcosystemName("npm", "test-package")
dir := t.TempDir() if err != nil {
dbPath := filepath.Join(dir, "test.db") t.Errorf("GetPackageByEcosystemName failed after migration: %v", err)
}
db, err := Create(dbPath) if pkg == nil {
if err != nil { t.Fatal("GetPackageByEcosystemName returned nil after migration")
t.Fatalf("Create failed: %v", err) }
} if pkg.Name != "test-package" {
defer func() { _ = db.Close() }() t.Errorf("expected package name test-package, got %s", pkg.Name)
// All migrations are already recorded from Create. Running MigrateSchema
// should return without running any migration functions.
if err := db.MigrateSchema(); err != nil {
t.Fatalf("MigrateSchema failed: %v", err)
}
// Verify count hasn't changed (no duplicate inserts)
var count int
if err := db.Get(&count, "SELECT COUNT(*) FROM migrations"); err != nil {
t.Fatalf("counting migrations failed: %v", err)
}
if count != len(migrations) {
t.Errorf("expected %d migrations, got %d", len(migrations), count)
}
}
func TestMigrateSchemaUpgradeFromFullyMigrated(t *testing.T) {
dir := t.TempDir()
dbPath := filepath.Join(dir, "existing.db")
// Simulate an existing proxy database that has the full current schema
// but no migrations table (i.e. it was running the previous version).
sqlDB, err := sql.Open("sqlite", dbPath)
if err != nil {
t.Fatalf("failed to open database: %v", err)
}
if _, err := sqlDB.Exec(schemaSQLite); err != nil {
t.Fatalf("failed to create schema: %v", err)
}
// Drop the migrations table that schemaSQLite now includes
if _, err := sqlDB.Exec("DROP TABLE migrations"); err != nil {
t.Fatalf("failed to drop migrations table: %v", err)
}
if _, err := sqlDB.Exec("INSERT INTO schema_info (version) VALUES (1)"); err != nil {
t.Fatalf("failed to set schema version: %v", err)
}
if err := sqlDB.Close(); err != nil {
t.Fatalf("failed to close database: %v", err)
}
db, err := Open(dbPath)
if err != nil {
t.Fatalf("Open failed: %v", err)
}
defer func() { _ = db.Close() }()
// This should create the migrations table and record all migrations
// without altering any tables (everything already exists).
if err := db.MigrateSchema(); err != nil {
t.Fatalf("MigrateSchema failed: %v", err)
}
applied, err := db.appliedMigrations()
if err != nil {
t.Fatalf("appliedMigrations failed: %v", err)
}
for _, m := range migrations {
if !applied[m.name] {
t.Errorf("migration %s not recorded after upgrade", m.name)
} }
}
// Second run should be the fast path (single SELECT) // Note: SearchPackages not tested here because old timestamp data
if err := db.MigrateSchema(); err != nil { // stored as strings can't be scanned into time.Time. This is a data
t.Fatalf("second MigrateSchema failed: %v", err) // migration issue, not a schema migration issue.
} })
} }
func TestConcurrentWrites(t *testing.T) { func TestConcurrentWrites(t *testing.T) {
@ -1076,26 +890,3 @@ func TestSearchPackagesWithValues(t *testing.T) {
t.Errorf("expected 10 hits, got %d", result.Hits) t.Errorf("expected 10 hits, got %d", result.Hits)
} }
} }
func BenchmarkMigrateSchemaFullyMigrated(b *testing.B) {
dir := b.TempDir()
dbPath := filepath.Join(dir, "bench.db")
db, err := Create(dbPath)
if err != nil {
b.Fatalf("Create failed: %v", err)
}
defer func() { _ = db.Close() }()
// First call to ensure everything is migrated
if err := db.MigrateSchema(); err != nil {
b.Fatalf("initial MigrateSchema failed: %v", err)
}
b.ResetTimer()
for b.Loop() {
if err := db.MigrateSchema(); err != nil {
b.Fatalf("MigrateSchema failed: %v", err)
}
}
}

View file

@ -1,231 +0,0 @@
package database
import (
"database/sql"
"path/filepath"
"testing"
"time"
)
func setupMetadataCacheDB(t *testing.T) *DB {
t.Helper()
dbPath := filepath.Join(t.TempDir(), "test.db")
db, err := Create(dbPath)
if err != nil {
t.Fatalf("Create failed: %v", err)
}
if err := db.MigrateSchema(); err != nil {
t.Fatalf("MigrateSchema failed: %v", err)
}
t.Cleanup(func() { _ = db.Close() })
return db
}
func TestUpsertAndGetMetadataCache(t *testing.T) {
db := setupMetadataCacheDB(t)
entry := &MetadataCacheEntry{
Ecosystem: testEcosystemNPM,
Name: "lodash",
StoragePath: "_metadata/npm/lodash/metadata",
ETag: sql.NullString{String: `"abc123"`, Valid: true},
ContentType: sql.NullString{String: "application/json", Valid: true},
ContentDigest: sql.NullString{
String: "sha256:0123456789abcdef",
Valid: true,
},
Size: sql.NullInt64{Int64: 1024, Valid: true},
FetchedAt: sql.NullTime{Time: time.Now(), Valid: true},
}
err := db.UpsertMetadataCache(entry)
if err != nil {
t.Fatalf("UpsertMetadataCache() error = %v", err)
}
got, err := db.GetMetadataCache(testEcosystemNPM, "lodash")
if err != nil {
t.Fatalf("GetMetadataCache() error = %v", err)
}
if got == nil {
t.Fatal("GetMetadataCache() returned nil")
}
if got.Ecosystem != testEcosystemNPM {
t.Errorf("ecosystem = %q, want %q", got.Ecosystem, testEcosystemNPM)
}
if got.Name != "lodash" {
t.Errorf("name = %q, want %q", got.Name, "lodash")
}
if got.StoragePath != "_metadata/npm/lodash/metadata" {
t.Errorf("storage_path = %q, want %q", got.StoragePath, "_metadata/npm/lodash/metadata")
}
if !got.ETag.Valid || got.ETag.String != `"abc123"` {
t.Errorf("etag = %v, want %q", got.ETag, `"abc123"`)
}
if !got.ContentType.Valid || got.ContentType.String != "application/json" {
t.Errorf("content_type = %v, want %q", got.ContentType, "application/json")
}
if !got.ContentDigest.Valid || got.ContentDigest.String != "sha256:0123456789abcdef" {
t.Errorf("content_digest = %v, want %q", got.ContentDigest, "sha256:0123456789abcdef")
}
if !got.Size.Valid || got.Size.Int64 != 1024 {
t.Errorf("size = %v, want 1024", got.Size)
}
}
func TestGetMetadataCacheMiss(t *testing.T) {
db := setupMetadataCacheDB(t)
got, err := db.GetMetadataCache(testEcosystemNPM, "nonexistent")
if err != nil {
t.Fatalf("GetMetadataCache() error = %v", err)
}
if got != nil {
t.Errorf("expected nil for cache miss, got %v", got)
}
}
func TestUpsertMetadataCacheOverwrite(t *testing.T) {
db := setupMetadataCacheDB(t)
// First insert
entry1 := &MetadataCacheEntry{
Ecosystem: testEcosystemNPM,
Name: "lodash",
StoragePath: "_metadata/npm/lodash/metadata",
ETag: sql.NullString{String: `"v1"`, Valid: true},
ContentType: sql.NullString{String: "application/json", Valid: true},
Size: sql.NullInt64{Int64: 100, Valid: true},
FetchedAt: sql.NullTime{Time: time.Now(), Valid: true},
}
if err := db.UpsertMetadataCache(entry1); err != nil {
t.Fatalf("first UpsertMetadataCache() error = %v", err)
}
// Second insert (same ecosystem+name, different etag and size)
entry2 := &MetadataCacheEntry{
Ecosystem: testEcosystemNPM,
Name: "lodash",
StoragePath: "_metadata/npm/lodash/metadata",
ETag: sql.NullString{String: `"v2"`, Valid: true},
ContentType: sql.NullString{String: "application/json", Valid: true},
Size: sql.NullInt64{Int64: 200, Valid: true},
FetchedAt: sql.NullTime{Time: time.Now(), Valid: true},
}
if err := db.UpsertMetadataCache(entry2); err != nil {
t.Fatalf("second UpsertMetadataCache() error = %v", err)
}
got, err := db.GetMetadataCache(testEcosystemNPM, "lodash")
if err != nil {
t.Fatalf("GetMetadataCache() error = %v", err)
}
if got == nil {
t.Fatal("expected entry after overwrite")
}
if got.ETag.String != `"v2"` {
t.Errorf("etag = %q, want %q", got.ETag.String, `"v2"`)
}
if got.Size.Int64 != 200 {
t.Errorf("size = %d, want 200", got.Size.Int64)
}
}
func TestUpsertMetadataCacheNullableFields(t *testing.T) {
db := setupMetadataCacheDB(t)
entry := &MetadataCacheEntry{
Ecosystem: "pypi",
Name: "requests",
StoragePath: "_metadata/pypi/requests/metadata",
}
if err := db.UpsertMetadataCache(entry); err != nil {
t.Fatalf("UpsertMetadataCache() error = %v", err)
}
got, err := db.GetMetadataCache("pypi", "requests")
if err != nil {
t.Fatalf("GetMetadataCache() error = %v", err)
}
if got == nil {
t.Fatal("expected entry")
}
if got.ETag.Valid {
t.Error("expected null etag")
}
if got.ContentType.Valid {
t.Error("expected null content_type")
}
if got.Size.Valid {
t.Error("expected null size")
}
}
func TestMetadataCacheTableCreatedByMigration(t *testing.T) {
// Create a DB without the metadata_cache table, then migrate
dbPath := filepath.Join(t.TempDir(), "test.db")
db, err := Create(dbPath)
if err != nil {
t.Fatalf("Create failed: %v", err)
}
defer func() { _ = db.Close() }()
// MigrateSchema should create the metadata_cache table
if err := db.MigrateSchema(); err != nil {
t.Fatalf("MigrateSchema() error = %v", err)
}
has, err := db.HasTable("metadata_cache")
if err != nil {
t.Fatalf("HasTable() error = %v", err)
}
if !has {
t.Error("metadata_cache table should exist after migration")
}
}
func TestMetadataCacheContentDigestMigrationPreservesExistingRows(t *testing.T) {
dbPath := filepath.Join(t.TempDir(), "test.db")
db, err := Create(dbPath)
if err != nil {
t.Fatalf("Create failed: %v", err)
}
defer func() { _ = db.Close() }()
if _, err := db.Exec("ALTER TABLE metadata_cache DROP COLUMN content_digest"); err != nil {
t.Fatalf("dropping content_digest: %v", err)
}
if _, err := db.Exec("DELETE FROM migrations WHERE name = ?", "006_add_metadata_content_digest"); err != nil {
t.Fatalf("resetting digest migration: %v", err)
}
if _, err := db.Exec(`
INSERT INTO metadata_cache (ecosystem, name, storage_path, content_type, size, fetched_at, created_at, updated_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
`, "oci-manifest", "cache-key", "_metadata/oci-manifest/cache-key/metadata", "application/json", 2, time.Now(), time.Now(), time.Now()); err != nil {
t.Fatalf("inserting legacy cache row: %v", err)
}
if err := db.MigrateSchema(); err != nil {
t.Fatalf("MigrateSchema() error = %v", err)
}
hasDigest, err := db.HasColumn("metadata_cache", "content_digest")
if err != nil {
t.Fatalf("HasColumn() error = %v", err)
}
if !hasDigest {
t.Fatal("metadata_cache.content_digest was not added")
}
entry, err := db.GetMetadataCache("oci-manifest", "cache-key")
if err != nil {
t.Fatalf("GetMetadataCache() error = %v", err)
}
if entry == nil || entry.StoragePath != "_metadata/oci-manifest/cache-key/metadata" {
t.Fatalf("existing metadata cache row was not preserved: %#v", entry)
}
if entry.ContentDigest.Valid {
t.Errorf("legacy content digest = %q, want NULL", entry.ContentDigest.String)
}
}

View file

@ -191,28 +191,6 @@ func (db *DB) GetArtifact(versionPURL, filename string) (*Artifact, error) {
return &a, nil return &a, nil
} }
// GetCachedArtifact returns the fields needed to serve a cached artifact.
func (db *DB) GetCachedArtifact(packagePURL, versionPURL, filename string) (*CachedArtifact, error) {
var artifact CachedArtifact
query := db.Rebind(`
SELECT packages.ecosystem, artifacts.storage_path, artifacts.content_hash, artifacts.size,
artifacts.content_type, versions.integrity
FROM artifacts
JOIN versions ON versions.purl = artifacts.version_purl
JOIN packages ON packages.purl = versions.package_purl
WHERE packages.purl = ? AND artifacts.version_purl = ? AND artifacts.filename = ?
AND artifacts.storage_path IS NOT NULL AND artifacts.fetched_at IS NOT NULL
`)
err := db.Get(&artifact, query, packagePURL, versionPURL, filename)
if err == sql.ErrNoRows {
return nil, nil
}
if err != nil {
return nil, err
}
return &artifact, nil
}
func (db *DB) GetArtifactByPath(storagePath string) (*Artifact, error) { func (db *DB) GetArtifactByPath(storagePath string) (*Artifact, error) {
var a Artifact var a Artifact
query := db.Rebind(` query := db.Rebind(`
@ -465,14 +443,11 @@ func (db *DB) GetMostPopularPackages(limit int) ([]PopularPackage, error) {
} }
type RecentPackage struct { type RecentPackage struct {
Ecosystem string `db:"ecosystem"` Ecosystem string `db:"ecosystem"`
Name string `db:"name"` Name string `db:"name"`
VersionPURL string `db:"version_purl"` Version string `db:"version"`
CachedAt time.Time `db:"fetched_at"` CachedAt time.Time `db:"fetched_at"`
Size int64 `db:"size"` Size int64 `db:"size"`
// Version is derived from VersionPURL rather than selected, so that the
// PURL percent-encoding is decoded (e.g. "%2B" back to "+").
Version string `db:"-"`
} }
func (db *DB) GetRecentlyCachedPackages(limit int) ([]RecentPackage, error) { func (db *DB) GetRecentlyCachedPackages(limit int) ([]RecentPackage, error) {
@ -486,10 +461,10 @@ func (db *DB) GetRecentlyCachedPackages(limit int) ([]RecentPackage, error) {
} }
var packages []RecentPackage var packages []RecentPackage
// There is no separate version column, so the full version PURL is selected // We need to extract version from the purl since there's no separate version column
// and the version is decoded from it in Go.
query := db.Rebind(` query := db.Rebind(`
SELECT p.ecosystem, p.name, v.purl as version_purl, SELECT p.ecosystem, p.name,
SUBSTR(v.purl, INSTR(v.purl, '@') + 1) as version,
a.fetched_at, COALESCE(a.size, 0) as size a.fetched_at, COALESCE(a.size, 0) as size
FROM artifacts a FROM artifacts a
JOIN versions v ON v.purl = a.version_purl JOIN versions v ON v.purl = a.version_purl
@ -499,13 +474,25 @@ func (db *DB) GetRecentlyCachedPackages(limit int) ([]RecentPackage, error) {
LIMIT ? LIMIT ?
`) `)
// For postgres, use different string function
if db.dialect == DialectPostgres {
query = db.Rebind(`
SELECT p.ecosystem, p.name,
SUBSTRING(v.purl FROM POSITION('@' IN v.purl) + 1) as version,
a.fetched_at, COALESCE(a.size, 0) as size
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.fetched_at IS NOT NULL
ORDER BY a.fetched_at DESC
LIMIT ?
`)
}
err = db.Select(&packages, query, limit) err = db.Select(&packages, query, limit)
if err != nil { if err != nil {
return nil, err return nil, err
} }
for i := range packages {
packages[i].Version = VersionFromPURL(packages[i].VersionPURL)
}
return packages, nil return packages, nil
} }
@ -900,68 +887,3 @@ func (db *DB) CountCachedPackages(ecosystem string) (int64, error) {
err = db.Get(&count, query, args...) err = db.Get(&count, query, args...)
return count, err return count, err
} }
// Metadata cache queries
func (db *DB) GetMetadataCache(ecosystem, name string) (*MetadataCacheEntry, error) {
var entry MetadataCacheEntry
query := db.Rebind(`
SELECT id, ecosystem, name, storage_path, etag, content_type,
content_digest, size, last_modified, fetched_at, created_at, updated_at
FROM metadata_cache WHERE ecosystem = ? AND name = ?
`)
err := db.Get(&entry, query, ecosystem, name)
if err == sql.ErrNoRows {
return nil, nil
}
if err != nil {
return nil, err
}
return &entry, nil
}
func (db *DB) UpsertMetadataCache(entry *MetadataCacheEntry) error {
now := time.Now()
var query string
if db.dialect == DialectPostgres {
query = `
INSERT INTO metadata_cache (ecosystem, name, storage_path, etag, content_type,
content_digest, size, last_modified, fetched_at, created_at, updated_at)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)
ON CONFLICT(ecosystem, name) DO UPDATE SET
storage_path = EXCLUDED.storage_path,
etag = EXCLUDED.etag,
content_type = EXCLUDED.content_type,
content_digest = EXCLUDED.content_digest,
size = EXCLUDED.size,
last_modified = EXCLUDED.last_modified,
fetched_at = EXCLUDED.fetched_at,
updated_at = EXCLUDED.updated_at
`
} else {
query = `
INSERT INTO metadata_cache (ecosystem, name, storage_path, etag, content_type,
content_digest, size, last_modified, fetched_at, created_at, updated_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(ecosystem, name) DO UPDATE SET
storage_path = excluded.storage_path,
etag = excluded.etag,
content_type = excluded.content_type,
content_digest = excluded.content_digest,
size = excluded.size,
last_modified = excluded.last_modified,
fetched_at = excluded.fetched_at,
updated_at = excluded.updated_at
`
}
_, err := db.Exec(query,
entry.Ecosystem, entry.Name, entry.StoragePath, entry.ETag,
entry.ContentType, entry.ContentDigest, entry.Size, entry.LastModified, entry.FetchedAt, now, now,
)
if err != nil {
return fmt.Errorf("upserting metadata cache: %w", err)
}
return nil
}

View file

@ -6,121 +6,118 @@ import (
"time" "time"
) )
const testEcosystemNPM = "npm" func TestListCachedPackages(t *testing.T) {
func setupListCachedPackagesDB(t *testing.T) *DB {
t.Helper()
db, err := Create(t.TempDir() + "/test.db") db, err := Create(t.TempDir() + "/test.db")
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
seedListCachedPackagesData(t, db)
return db
}
func seedListCachedPackagesData(t *testing.T, db *DB) {
t.Helper()
packages := []*Package{
{
PURL: "pkg:npm/lodash",
Ecosystem: testEcosystemNPM,
Name: "lodash",
LatestVersion: sql.NullString{String: "4.17.21", Valid: true},
License: sql.NullString{String: "MIT", Valid: true},
},
{
PURL: "pkg:cargo/serde",
Ecosystem: "cargo",
Name: "serde",
LatestVersion: sql.NullString{String: "1.0.0", Valid: true},
License: sql.NullString{String: "MIT OR Apache-2.0", Valid: true},
},
{
PURL: "pkg:npm/react",
Ecosystem: testEcosystemNPM,
Name: "react",
LatestVersion: sql.NullString{String: "18.0.0", Valid: true},
License: sql.NullString{String: "MIT", Valid: true},
},
}
for _, pkg := range packages {
if err := db.UpsertPackage(pkg); err != nil {
t.Fatal(err)
}
}
versions := []*Version{
{PURL: "pkg:npm/lodash@4.17.21", PackagePURL: packages[0].PURL},
{PURL: "pkg:cargo/serde@1.0.0", PackagePURL: packages[1].PURL},
{PURL: "pkg:npm/react@18.0.0", PackagePURL: packages[2].PURL},
}
for _, ver := range versions {
if err := db.UpsertVersion(ver); err != nil {
t.Fatal(err)
}
}
artifacts := []*Artifact{
{
VersionPURL: versions[0].PURL,
Filename: "lodash.tgz",
UpstreamURL: "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz",
StoragePath: sql.NullString{String: "npm/lodash/4.17.21/lodash.tgz", Valid: true},
Size: sql.NullInt64{Int64: 1024, Valid: true},
HitCount: 100,
FetchedAt: sql.NullTime{Time: time.Now(), Valid: true},
},
{
VersionPURL: versions[1].PURL,
Filename: "serde.crate",
UpstreamURL: "https://crates.io/api/v1/crates/serde/1.0.0/download",
StoragePath: sql.NullString{String: "cargo/serde/1.0.0/serde.crate", Valid: true},
Size: sql.NullInt64{Int64: 2048, Valid: true},
HitCount: 50,
FetchedAt: sql.NullTime{Time: time.Now().Add(-1 * time.Hour), Valid: true},
},
{
VersionPURL: versions[2].PURL,
Filename: "react.tgz",
UpstreamURL: "https://registry.npmjs.org/react/-/react-18.0.0.tgz",
StoragePath: sql.NullString{String: "npm/react/18.0.0/react.tgz", Valid: true},
Size: sql.NullInt64{Int64: 512, Valid: true},
HitCount: 200,
FetchedAt: sql.NullTime{Time: time.Now().Add(-2 * time.Hour), Valid: true},
},
}
for _, art := range artifacts {
if err := db.UpsertArtifact(art); err != nil {
t.Fatal(err)
}
}
}
func TestListCachedPackages(t *testing.T) {
db := setupListCachedPackagesDB(t)
defer func() { _ = db.Close() }() defer func() { _ = db.Close() }()
listAll := func(ecosystem, sortBy string) []PackageListItem { // Create test packages
t.Helper() pkg1 := &Package{
packages, err := db.ListCachedPackages(ecosystem, sortBy, 10, 0) PURL: "pkg:npm/lodash",
if err != nil { Ecosystem: "npm",
t.Fatal(err) Name: "lodash",
} LatestVersion: sql.NullString{String: "4.17.21", Valid: true},
return packages License: sql.NullString{String: "MIT", Valid: true},
}
pkg2 := &Package{
PURL: "pkg:cargo/serde",
Ecosystem: "cargo",
Name: "serde",
LatestVersion: sql.NullString{String: "1.0.0", Valid: true},
License: sql.NullString{String: "MIT OR Apache-2.0", Valid: true},
}
pkg3 := &Package{
PURL: "pkg:npm/react",
Ecosystem: "npm",
Name: "react",
LatestVersion: sql.NullString{String: "18.0.0", Valid: true},
License: sql.NullString{String: "MIT", Valid: true},
}
if err := db.UpsertPackage(pkg1); err != nil {
t.Fatal(err)
}
if err := db.UpsertPackage(pkg2); err != nil {
t.Fatal(err)
}
if err := db.UpsertPackage(pkg3); err != nil {
t.Fatal(err)
}
// Create versions
ver1 := &Version{
PURL: "pkg:npm/lodash@4.17.21",
PackagePURL: pkg1.PURL,
}
ver2 := &Version{
PURL: "pkg:cargo/serde@1.0.0",
PackagePURL: pkg2.PURL,
}
ver3 := &Version{
PURL: "pkg:npm/react@18.0.0",
PackagePURL: pkg3.PURL,
}
if err := db.UpsertVersion(ver1); err != nil {
t.Fatal(err)
}
if err := db.UpsertVersion(ver2); err != nil {
t.Fatal(err)
}
if err := db.UpsertVersion(ver3); err != nil {
t.Fatal(err)
}
// Create artifacts
art1 := &Artifact{
VersionPURL: ver1.PURL,
Filename: "lodash.tgz",
UpstreamURL: "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz",
StoragePath: sql.NullString{String: "npm/lodash/4.17.21/lodash.tgz", Valid: true},
Size: sql.NullInt64{Int64: 1024, Valid: true},
HitCount: 100,
FetchedAt: sql.NullTime{Time: time.Now(), Valid: true},
}
art2 := &Artifact{
VersionPURL: ver2.PURL,
Filename: "serde.crate",
UpstreamURL: "https://crates.io/api/v1/crates/serde/1.0.0/download",
StoragePath: sql.NullString{String: "cargo/serde/1.0.0/serde.crate", Valid: true},
Size: sql.NullInt64{Int64: 2048, Valid: true},
HitCount: 50,
FetchedAt: sql.NullTime{Time: time.Now().Add(-1 * time.Hour), Valid: true},
}
art3 := &Artifact{
VersionPURL: ver3.PURL,
Filename: "react.tgz",
UpstreamURL: "https://registry.npmjs.org/react/-/react-18.0.0.tgz",
StoragePath: sql.NullString{String: "npm/react/18.0.0/react.tgz", Valid: true},
Size: sql.NullInt64{Int64: 512, Valid: true},
HitCount: 200,
FetchedAt: sql.NullTime{Time: time.Now().Add(-2 * time.Hour), Valid: true},
}
if err := db.UpsertArtifact(art1); err != nil {
t.Fatal(err)
}
if err := db.UpsertArtifact(art2); err != nil {
t.Fatal(err)
}
if err := db.UpsertArtifact(art3); err != nil {
t.Fatal(err)
} }
t.Run("list all packages", func(t *testing.T) { t.Run("list all packages", func(t *testing.T) {
packages := listAll("", "hits") packages, err := db.ListCachedPackages("", "hits", 10, 0)
if err != nil {
t.Fatal(err)
}
if len(packages) != 3 { if len(packages) != 3 {
t.Errorf("expected 3 packages, got %d", len(packages)) t.Errorf("expected 3 packages, got %d", len(packages))
} }
// Should be sorted by hits DESC
if packages[0].Name != "react" { if packages[0].Name != "react" {
t.Errorf("expected first package to be react, got %s", packages[0].Name) t.Errorf("expected first package to be react, got %s", packages[0].Name)
} }
@ -130,26 +127,35 @@ func TestListCachedPackages(t *testing.T) {
}) })
t.Run("filter by ecosystem", func(t *testing.T) { t.Run("filter by ecosystem", func(t *testing.T) {
packages := listAll(testEcosystemNPM, "hits") packages, err := db.ListCachedPackages("npm", "hits", 10, 0)
if err != nil {
t.Fatal(err)
}
if len(packages) != 2 { if len(packages) != 2 {
t.Errorf("expected 2 npm packages, got %d", len(packages)) t.Errorf("expected 2 npm packages, got %d", len(packages))
} }
for _, pkg := range packages { for _, pkg := range packages {
if pkg.Ecosystem != testEcosystemNPM { if pkg.Ecosystem != "npm" {
t.Errorf("expected npm ecosystem, got %s", pkg.Ecosystem) t.Errorf("expected npm ecosystem, got %s", pkg.Ecosystem)
} }
} }
}) })
t.Run("sort by name", func(t *testing.T) { t.Run("sort by name", func(t *testing.T) {
packages := listAll("", "name") packages, err := db.ListCachedPackages("", "name", 10, 0)
if err != nil {
t.Fatal(err)
}
if packages[0].Name != "lodash" { if packages[0].Name != "lodash" {
t.Errorf("expected first package to be lodash, got %s", packages[0].Name) t.Errorf("expected first package to be lodash, got %s", packages[0].Name)
} }
}) })
t.Run("sort by size", func(t *testing.T) { t.Run("sort by size", func(t *testing.T) {
packages := listAll("", "size") packages, err := db.ListCachedPackages("", "size", 10, 0)
if err != nil {
t.Fatal(err)
}
if packages[0].Name != "serde" { if packages[0].Name != "serde" {
t.Errorf("expected first package to be serde (largest), got %s", packages[0].Name) t.Errorf("expected first package to be serde (largest), got %s", packages[0].Name)
} }
@ -164,7 +170,7 @@ func TestListCachedPackages(t *testing.T) {
t.Errorf("expected count 3, got %d", count) t.Errorf("expected count 3, got %d", count)
} }
count, err = db.CountCachedPackages(testEcosystemNPM) count, err = db.CountCachedPackages("npm")
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }

View file

@ -1,16 +1,6 @@
package database package database
import ( import "fmt"
"fmt"
"strings"
"time"
)
const (
postgresTimestamp = "TIMESTAMP"
sqliteDatetime = "DATETIME"
colTypeText = "TEXT"
)
// Schema for proxy-specific tables. The packages and versions tables // Schema for proxy-specific tables. The packages and versions tables
// are compatible with git-pkgs, allowing the proxy to use an existing // are compatible with git-pkgs, allowing the proxy to use an existing
@ -94,27 +84,6 @@ CREATE TABLE IF NOT EXISTS vulnerabilities (
); );
CREATE UNIQUE INDEX IF NOT EXISTS idx_vulns_id_pkg ON vulnerabilities(vuln_id, ecosystem, package_name); CREATE UNIQUE INDEX IF NOT EXISTS idx_vulns_id_pkg ON vulnerabilities(vuln_id, ecosystem, package_name);
CREATE INDEX IF NOT EXISTS idx_vulns_ecosystem_pkg ON vulnerabilities(ecosystem, package_name); CREATE INDEX IF NOT EXISTS idx_vulns_ecosystem_pkg ON vulnerabilities(ecosystem, package_name);
CREATE TABLE IF NOT EXISTS metadata_cache (
id INTEGER PRIMARY KEY,
ecosystem TEXT NOT NULL,
name TEXT NOT NULL,
storage_path TEXT NOT NULL,
etag TEXT,
content_type TEXT,
content_digest TEXT,
size INTEGER,
last_modified DATETIME,
fetched_at DATETIME,
created_at DATETIME,
updated_at DATETIME
);
CREATE UNIQUE INDEX IF NOT EXISTS idx_metadata_eco_name ON metadata_cache(ecosystem, name);
CREATE TABLE IF NOT EXISTS migrations (
name TEXT NOT NULL PRIMARY KEY,
applied_at DATETIME NOT NULL
);
` `
var schemaPostgres = ` var schemaPostgres = `
@ -195,27 +164,6 @@ CREATE TABLE IF NOT EXISTS vulnerabilities (
); );
CREATE UNIQUE INDEX IF NOT EXISTS idx_vulns_id_pkg ON vulnerabilities(vuln_id, ecosystem, package_name); CREATE UNIQUE INDEX IF NOT EXISTS idx_vulns_id_pkg ON vulnerabilities(vuln_id, ecosystem, package_name);
CREATE INDEX IF NOT EXISTS idx_vulns_ecosystem_pkg ON vulnerabilities(ecosystem, package_name); CREATE INDEX IF NOT EXISTS idx_vulns_ecosystem_pkg ON vulnerabilities(ecosystem, package_name);
CREATE TABLE IF NOT EXISTS metadata_cache (
id SERIAL PRIMARY KEY,
ecosystem TEXT NOT NULL,
name TEXT NOT NULL,
storage_path TEXT NOT NULL,
etag TEXT,
content_type TEXT,
content_digest TEXT,
size BIGINT,
last_modified TIMESTAMP,
fetched_at TIMESTAMP,
created_at TIMESTAMP,
updated_at TIMESTAMP
);
CREATE UNIQUE INDEX IF NOT EXISTS idx_metadata_eco_name ON metadata_cache(ecosystem, name);
CREATE TABLE IF NOT EXISTS migrations (
name TEXT NOT NULL PRIMARY KEY,
applied_at TIMESTAMP NOT NULL
);
` `
// schemaArtifactsOnly contains just the artifacts table for adding to existing git-pkgs databases. // schemaArtifactsOnly contains just the artifacts table for adding to existing git-pkgs databases.
@ -282,11 +230,6 @@ func (db *DB) CreateSchema() error {
return fmt.Errorf("setting schema version: %w", err) return fmt.Errorf("setting schema version: %w", err)
} }
// Record all migrations as applied since the full schema is already current.
if err := db.recordAllMigrations(); err != nil {
return fmt.Errorf("recording migrations: %w", err)
}
return db.OptimizeForReads() return db.OptimizeForReads()
} }
@ -347,307 +290,127 @@ func (db *DB) HasColumn(table, column string) (bool, error) {
return exists, err return exists, err
} }
// migration represents a named schema migration. // MigrateSchema adds missing columns to existing tables for backward compatibility.
type migration struct {
name string
fn func(db *DB) error
}
// migrations is the ordered list of all schema migrations. See
// docs/migrations.md for how to add new ones.
var migrations = []migration{
{"001_add_packages_enrichment_columns", migrateAddPackagesEnrichmentColumns},
{"002_add_versions_enrichment_columns", migrateAddVersionsEnrichmentColumns},
{"003_ensure_artifacts_table", migrateEnsureArtifactsTable},
{"004_ensure_vulnerabilities_table", migrateEnsureVulnerabilitiesTable},
{"005_ensure_metadata_cache_table", migrateEnsureMetadataCacheTable},
{"006_add_metadata_content_digest", migrateAddMetadataContentDigest},
}
// isTableNotFound returns true if the error indicates a missing table.
// SQLite returns "no such table: X", Postgres returns "relation \"X\" does not exist".
func isTableNotFound(err error) bool {
msg := err.Error()
return strings.Contains(msg, "no such table") ||
strings.Contains(msg, "does not exist")
}
// createMigrationsTable creates the migrations table.
func (db *DB) createMigrationsTable() error {
var ts string
if db.dialect == DialectPostgres {
ts = postgresTimestamp
} else {
ts = sqliteDatetime
}
query := fmt.Sprintf(`CREATE TABLE IF NOT EXISTS migrations (
name TEXT NOT NULL PRIMARY KEY,
applied_at %s NOT NULL
)`, ts)
if _, err := db.Exec(query); err != nil {
return fmt.Errorf("creating migrations table: %w", err)
}
return nil
}
// appliedMigrations returns the set of migration names that have been recorded.
// Returns nil if the migrations table does not exist yet.
func (db *DB) appliedMigrations() (map[string]bool, error) {
var names []string
err := db.Select(&names, "SELECT name FROM migrations")
if err != nil {
// Table doesn't exist yet — this is a pre-migration database.
if isTableNotFound(err) {
return nil, nil
}
return nil, fmt.Errorf("loading applied migrations: %w", err)
}
applied := make(map[string]bool, len(names))
for _, name := range names {
applied[name] = true
}
return applied, nil
}
// recordMigration inserts a migration name into the migrations table.
func (db *DB) recordMigration(name string) error {
query := db.Rebind("INSERT INTO migrations (name, applied_at) VALUES (?, ?)")
if _, err := db.Exec(query, name, time.Now().UTC()); err != nil {
return fmt.Errorf("recording migration %s: %w", name, err)
}
return nil
}
// recordAllMigrations marks every known migration as applied.
func (db *DB) recordAllMigrations() error {
for _, m := range migrations {
if err := db.recordMigration(m.name); err != nil {
return err
}
}
return nil
}
// MigrateSchema applies any unapplied migrations in order.
// For a fully migrated database this executes a single SELECT query.
func (db *DB) MigrateSchema() error { func (db *DB) MigrateSchema() error {
applied, err := db.appliedMigrations() // Check and add missing columns to packages table
if err != nil { packagesColumns := map[string]string{
return err "registry_url": "TEXT",
} "supplier_name": "TEXT",
"supplier_type": "TEXT",
// If the migrations table didn't exist, create it now. "source": "TEXT",
if applied == nil { "enriched_at": "DATETIME",
if err := db.createMigrationsTable(); err != nil { "vulns_synced_at": "DATETIME",
return err
}
applied = make(map[string]bool)
}
for _, m := range migrations {
if applied[m.name] {
continue
}
if err := m.fn(db); err != nil {
return fmt.Errorf("migration %s: %w", m.name, err)
}
if err := db.recordMigration(m.name); err != nil {
return err
}
}
return nil
}
func migrateAddPackagesEnrichmentColumns(db *DB) error {
columns := map[string]string{
"registry_url": colTypeText,
"supplier_name": colTypeText,
"supplier_type": colTypeText,
"source": colTypeText,
"enriched_at": sqliteDatetime,
"vulns_synced_at": sqliteDatetime,
} }
if db.dialect == DialectPostgres { if db.dialect == DialectPostgres {
columns["enriched_at"] = postgresTimestamp packagesColumns["enriched_at"] = "TIMESTAMP"
columns["vulns_synced_at"] = postgresTimestamp packagesColumns["vulns_synced_at"] = "TIMESTAMP"
} }
for column, colType := range columns { for column, colType := range packagesColumns {
hasCol, err := db.HasColumn("packages", column) hasCol, err := db.HasColumn("packages", column)
if err != nil { if err != nil {
return fmt.Errorf("checking column %s: %w", column, err) return fmt.Errorf("checking column %s: %w", column, err)
} }
if !hasCol { if !hasCol {
alterQuery := fmt.Sprintf("ALTER TABLE packages ADD COLUMN %s %s", column, colType) var alterQuery string
if db.dialect == DialectPostgres {
alterQuery = fmt.Sprintf("ALTER TABLE packages ADD COLUMN %s %s", column, colType)
} else {
alterQuery = fmt.Sprintf("ALTER TABLE packages ADD COLUMN %s %s", column, colType)
}
if _, err := db.Exec(alterQuery); err != nil { if _, err := db.Exec(alterQuery); err != nil {
return fmt.Errorf("adding column %s to packages: %w", column, err) return fmt.Errorf("adding column %s to packages: %w", column, err)
} }
} }
} }
return nil
}
func migrateAddVersionsEnrichmentColumns(db *DB) error { // Check and add missing columns to versions table
columns := map[string]string{ versionsColumns := map[string]string{
"integrity": colTypeText, "integrity": "TEXT",
"yanked": "INTEGER DEFAULT 0", "yanked": "INTEGER DEFAULT 0",
"source": colTypeText, "source": "TEXT",
"enriched_at": sqliteDatetime, "enriched_at": "DATETIME",
} }
if db.dialect == DialectPostgres { if db.dialect == DialectPostgres {
columns["yanked"] = "BOOLEAN DEFAULT FALSE" versionsColumns["yanked"] = "BOOLEAN DEFAULT FALSE"
columns["enriched_at"] = postgresTimestamp versionsColumns["enriched_at"] = "TIMESTAMP"
} }
for column, colType := range columns { for column, colType := range versionsColumns {
hasCol, err := db.HasColumn("versions", column) hasCol, err := db.HasColumn("versions", column)
if err != nil { if err != nil {
return fmt.Errorf("checking column %s: %w", column, err) return fmt.Errorf("checking column %s: %w", column, err)
} }
if !hasCol { if !hasCol {
alterQuery := fmt.Sprintf("ALTER TABLE versions ADD COLUMN %s %s", column, colType) var alterQuery string
if db.dialect == DialectPostgres {
alterQuery = fmt.Sprintf("ALTER TABLE versions ADD COLUMN %s %s", column, colType)
} else {
alterQuery = fmt.Sprintf("ALTER TABLE versions ADD COLUMN %s %s", column, colType)
}
if _, err := db.Exec(alterQuery); err != nil { if _, err := db.Exec(alterQuery); err != nil {
return fmt.Errorf("adding column %s to versions: %w", column, err) return fmt.Errorf("adding column %s to versions: %w", column, err)
} }
} }
} }
return nil
}
func migrateEnsureArtifactsTable(db *DB) error { // Ensure artifacts table exists
return db.EnsureArtifactsTable() if err := db.EnsureArtifactsTable(); err != nil {
} return fmt.Errorf("ensuring artifacts table: %w", err)
}
func migrateEnsureVulnerabilitiesTable(db *DB) error { // Ensure vulnerabilities table exists
hasVulns, err := db.HasTable("vulnerabilities") hasVulns, err := db.HasTable("vulnerabilities")
if err != nil { if err != nil {
return fmt.Errorf("checking vulnerabilities table: %w", err) return fmt.Errorf("checking vulnerabilities table: %w", err)
} }
if hasVulns { if !hasVulns {
return nil var vulnSchema string
} if db.dialect == DialectPostgres {
vulnSchema = `
var vulnSchema string CREATE TABLE vulnerabilities (
if db.dialect == DialectPostgres { id SERIAL PRIMARY KEY,
vulnSchema = ` vuln_id TEXT NOT NULL,
CREATE TABLE vulnerabilities ( ecosystem TEXT NOT NULL,
id SERIAL PRIMARY KEY, package_name TEXT NOT NULL,
vuln_id TEXT NOT NULL, severity TEXT,
ecosystem TEXT NOT NULL, summary TEXT,
package_name TEXT NOT NULL, fixed_version TEXT,
severity TEXT, cvss_score REAL,
summary TEXT, "references" TEXT,
fixed_version TEXT, fetched_at TIMESTAMP,
cvss_score REAL, created_at TIMESTAMP,
"references" TEXT, updated_at TIMESTAMP
fetched_at TIMESTAMP, );
created_at TIMESTAMP, CREATE UNIQUE INDEX IF NOT EXISTS idx_vulns_id_pkg ON vulnerabilities(vuln_id, ecosystem, package_name);
updated_at TIMESTAMP CREATE INDEX IF NOT EXISTS idx_vulns_ecosystem_pkg ON vulnerabilities(ecosystem, package_name);
); `
CREATE UNIQUE INDEX IF NOT EXISTS idx_vulns_id_pkg ON vulnerabilities(vuln_id, ecosystem, package_name); } else {
CREATE INDEX IF NOT EXISTS idx_vulns_ecosystem_pkg ON vulnerabilities(ecosystem, package_name); vulnSchema = `
` CREATE TABLE vulnerabilities (
} else { id INTEGER PRIMARY KEY,
vulnSchema = ` vuln_id TEXT NOT NULL,
CREATE TABLE vulnerabilities ( ecosystem TEXT NOT NULL,
id INTEGER PRIMARY KEY, package_name TEXT NOT NULL,
vuln_id TEXT NOT NULL, severity TEXT,
ecosystem TEXT NOT NULL, summary TEXT,
package_name TEXT NOT NULL, fixed_version TEXT,
severity TEXT, cvss_score REAL,
summary TEXT, "references" TEXT,
fixed_version TEXT, fetched_at DATETIME,
cvss_score REAL, created_at DATETIME,
"references" TEXT, updated_at DATETIME
fetched_at DATETIME, );
created_at DATETIME, CREATE UNIQUE INDEX IF NOT EXISTS idx_vulns_id_pkg ON vulnerabilities(vuln_id, ecosystem, package_name);
updated_at DATETIME CREATE INDEX IF NOT EXISTS idx_vulns_ecosystem_pkg ON vulnerabilities(ecosystem, package_name);
); `
CREATE UNIQUE INDEX IF NOT EXISTS idx_vulns_id_pkg ON vulnerabilities(vuln_id, ecosystem, package_name); }
CREATE INDEX IF NOT EXISTS idx_vulns_ecosystem_pkg ON vulnerabilities(ecosystem, package_name); if _, err := db.Exec(vulnSchema); err != nil {
` return fmt.Errorf("creating vulnerabilities table: %w", err)
} }
if _, err := db.Exec(vulnSchema); err != nil {
return fmt.Errorf("creating vulnerabilities table: %w", err)
} }
return nil return nil
} }
func migrateEnsureMetadataCacheTable(db *DB) error {
return db.EnsureMetadataCacheTable()
}
func migrateAddMetadataContentDigest(db *DB) error {
hasColumn, err := db.HasColumn("metadata_cache", "content_digest")
if err != nil {
return fmt.Errorf("checking metadata_cache content_digest column: %w", err)
}
if hasColumn {
return nil
}
if _, err := db.Exec("ALTER TABLE metadata_cache ADD COLUMN content_digest TEXT"); err != nil {
return fmt.Errorf("adding metadata_cache content_digest column: %w", err)
}
return nil
}
// EnsureMetadataCacheTable creates the metadata_cache table if it doesn't exist.
func (db *DB) EnsureMetadataCacheTable() error {
has, err := db.HasTable("metadata_cache")
if err != nil {
return fmt.Errorf("checking metadata_cache table: %w", err)
}
if has {
return nil
}
var schema string
if db.dialect == DialectPostgres {
schema = `
CREATE TABLE metadata_cache (
id SERIAL PRIMARY KEY,
ecosystem TEXT NOT NULL,
name TEXT NOT NULL,
storage_path TEXT NOT NULL,
etag TEXT,
content_type TEXT,
content_digest TEXT,
size BIGINT,
last_modified TIMESTAMP,
fetched_at TIMESTAMP,
created_at TIMESTAMP,
updated_at TIMESTAMP
);
CREATE UNIQUE INDEX IF NOT EXISTS idx_metadata_eco_name ON metadata_cache(ecosystem, name);
`
} else {
schema = `
CREATE TABLE metadata_cache (
id INTEGER PRIMARY KEY,
ecosystem TEXT NOT NULL,
name TEXT NOT NULL,
storage_path TEXT NOT NULL,
etag TEXT,
content_type TEXT,
content_digest TEXT,
size INTEGER,
last_modified DATETIME,
fetched_at DATETIME,
created_at DATETIME,
updated_at DATETIME
);
CREATE UNIQUE INDEX IF NOT EXISTS idx_metadata_eco_name ON metadata_cache(ecosystem, name);
`
}
if _, err := db.Exec(schema); err != nil {
return fmt.Errorf("creating metadata_cache table: %w", err)
}
return nil
}

View file

@ -2,126 +2,16 @@ package database
import ( import (
"database/sql" "database/sql"
"net/url"
"strings"
"time" "time"
gitpkgsdb "github.com/git-pkgs/git-pkgs/database"
) )
// Package represents a package in the database. // Package and Version are shared with git-pkgs. The types and schema
// Schema is compatible with git-pkgs. // are defined in the git-pkgs database package, keeping both projects
type Package struct { // in sync automatically.
ID int64 `db:"id" json:"id"` type Package = gitpkgsdb.Package
PURL string `db:"purl" json:"purl"` type Version = gitpkgsdb.Version
Ecosystem string `db:"ecosystem" json:"ecosystem"`
Name string `db:"name" json:"name"`
LatestVersion sql.NullString `db:"latest_version" json:"latest_version,omitempty"`
License sql.NullString `db:"license" json:"license,omitempty"`
Description sql.NullString `db:"description" json:"description,omitempty"`
Homepage sql.NullString `db:"homepage" json:"homepage,omitempty"`
RepositoryURL sql.NullString `db:"repository_url" json:"repository_url,omitempty"`
RegistryURL sql.NullString `db:"registry_url" json:"registry_url,omitempty"`
SupplierName sql.NullString `db:"supplier_name" json:"supplier_name,omitempty"`
SupplierType sql.NullString `db:"supplier_type" json:"supplier_type,omitempty"`
Source sql.NullString `db:"source" json:"source,omitempty"`
EnrichedAt sql.NullTime `db:"enriched_at" json:"enriched_at,omitempty"`
VulnsSyncedAt sql.NullTime `db:"vulns_synced_at" json:"vulns_synced_at,omitempty"`
CreatedAt time.Time `db:"created_at" json:"created_at"`
UpdatedAt time.Time `db:"updated_at" json:"updated_at"`
}
// Version represents a package version in the database.
// Schema is compatible with git-pkgs.
type Version struct {
ID int64 `db:"id" json:"id"`
PURL string `db:"purl" json:"purl"`
PackagePURL string `db:"package_purl" json:"package_purl"`
License sql.NullString `db:"license" json:"license,omitempty"`
PublishedAt sql.NullTime `db:"published_at" json:"published_at,omitempty"`
Integrity sql.NullString `db:"integrity" json:"integrity,omitempty"`
Yanked bool `db:"yanked" json:"yanked"`
Source sql.NullString `db:"source" json:"source,omitempty"`
EnrichedAt sql.NullTime `db:"enriched_at" json:"enriched_at,omitempty"`
CreatedAt time.Time `db:"created_at" json:"created_at"`
UpdatedAt time.Time `db:"updated_at" json:"updated_at"`
}
// Version extracts the version string from the PURL.
// e.g., "pkg:npm/lodash@4.17.21" -> "4.17.21"
func (v *Version) Version() string {
return VersionFromPURL(v.PURL)
}
// EscapedVersion returns the version escaped for use as a single URL path
// segment.
//
// Version returns decoded text, which is what should be shown to a user but is
// not safe to drop into a link: html/template preserves reserved characters and
// existing escapes in a URL, so "release/1" would split into two path segments,
// "v1?build" would start a query string, and a literal "%2B" would be read back
// as "+". Escaping here and decoding in splitWildcardPath round-trips the value,
// so the link resolves to the version that was stored.
func (v *Version) EscapedVersion() string {
return url.PathEscape(v.Version())
}
// DisplayPURL returns the PURL with its path components percent-decoded, for
// showing in the UI. The stored PURL keeps the canonical encoding (which is
// what the API and all lookups use); this is only a readable rendering, so that
// a version like "7.91+dfsg1-2ubuntu0.1" is not shown as "7.91%2Bdfsg1-2ubuntu0.1"
// and an npm scope is shown as "@babel" rather than "%40babel". Qualifiers and
// subpath keep their encoding, since decoding those would be ambiguous.
func (v *Version) DisplayPURL() string {
base, suffix := v.PURL, ""
if i := strings.IndexAny(base, "?#"); i >= 0 {
base, suffix = base[:i], base[i:]
}
name, version := base, ""
if idx := strings.LastIndex(base, "@"); idx >= 0 {
name, version = base[:idx], "@"+decodePURLComponent(base[idx+1:])
}
parts := strings.Split(name, "/")
for i, part := range parts {
parts[i] = decodePURLComponent(part)
}
return strings.Join(parts, "/") + version + suffix
}
// VersionFromPURL extracts the decoded version string from a PURL.
//
// PURL percent-encodes characters that are not safe in a path component, so a
// Debian version like "7.91+dfsg1-2ubuntu0.1" is stored as
// "pkg:deb/nmap@7.91%2Bdfsg1-2ubuntu0.1". The raw substring after "@" is
// therefore not the version: it must be percent-decoded before being displayed
// or used to build a URL, otherwise "%2B" leaks into the UI and round-tripping
// the value back into a PURL double-encodes it.
//
// e.g., "pkg:npm/lodash@4.17.21" -> "4.17.21"
func VersionFromPURL(p string) string {
// Qualifiers ("?key=value") and subpath ("#path") follow the version.
if i := strings.IndexAny(p, "?#"); i >= 0 {
p = p[:i]
}
idx := strings.LastIndex(p, "@")
if idx < 0 {
return ""
}
return decodePURLComponent(p[idx+1:])
}
// decodePURLComponent percent-decodes a single PURL path component, returning
// the input unchanged if it is not valid percent-encoding.
func decodePURLComponent(s string) string {
if !strings.Contains(s, "%") {
return s
}
decoded, err := url.PathUnescape(s)
if err != nil {
return s
}
return decoded
}
// Artifact represents a cached artifact in the database. // Artifact represents a cached artifact in the database.
// This table is proxy-specific and not part of git-pkgs. // This table is proxy-specific and not part of git-pkgs.
@ -146,44 +36,18 @@ func (a *Artifact) IsCached() bool {
return a.StoragePath.Valid && a.FetchedAt.Valid return a.StoragePath.Valid && a.FetchedAt.Valid
} }
// CachedArtifact contains the fields needed to serve a cached artifact.
type CachedArtifact struct {
Ecosystem string `db:"ecosystem"`
StoragePath string `db:"storage_path"`
ContentHash sql.NullString `db:"content_hash"`
Size sql.NullInt64 `db:"size"`
ContentType sql.NullString `db:"content_type"`
Integrity sql.NullString `db:"integrity"`
}
// MetadataCacheEntry represents a cached metadata blob for offline serving.
type MetadataCacheEntry struct {
ID int64 `db:"id" json:"id"`
Ecosystem string `db:"ecosystem" json:"ecosystem"`
Name string `db:"name" json:"name"`
StoragePath string `db:"storage_path" json:"storage_path"`
ETag sql.NullString `db:"etag" json:"etag,omitempty"`
ContentType sql.NullString `db:"content_type" json:"content_type,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"`
}
// Vulnerability represents a cached vulnerability record. // Vulnerability represents a cached vulnerability record.
type Vulnerability struct { type Vulnerability struct {
ID int64 `db:"id" json:"id"` ID int64 `db:"id" json:"id"`
VulnID string `db:"vuln_id" json:"vuln_id"` VulnID string `db:"vuln_id" json:"vuln_id"`
Ecosystem string `db:"ecosystem" json:"ecosystem"` Ecosystem string `db:"ecosystem" json:"ecosystem"`
PackageName string `db:"package_name" json:"package_name"` PackageName string `db:"package_name" json:"package_name"`
Severity sql.NullString `db:"severity" json:"severity,omitempty"` Severity sql.NullString `db:"severity" json:"severity,omitempty"`
Summary sql.NullString `db:"summary" json:"summary,omitempty"` Summary sql.NullString `db:"summary" json:"summary,omitempty"`
FixedVersion sql.NullString `db:"fixed_version" json:"fixed_version,omitempty"` FixedVersion sql.NullString `db:"fixed_version" json:"fixed_version,omitempty"`
CVSSScore sql.NullFloat64 `db:"cvss_score" json:"cvss_score,omitempty"` CVSSScore sql.NullFloat64 `db:"cvss_score" json:"cvss_score,omitempty"`
References sql.NullString `db:"references" json:"references,omitempty"` References sql.NullString `db:"references" json:"references,omitempty"`
FetchedAt sql.NullTime `db:"fetched_at" json:"fetched_at,omitempty"` FetchedAt sql.NullTime `db:"fetched_at" json:"fetched_at,omitempty"`
CreatedAt time.Time `db:"created_at" json:"created_at"` CreatedAt time.Time `db:"created_at" json:"created_at"`
UpdatedAt time.Time `db:"updated_at" json:"updated_at"` UpdatedAt time.Time `db:"updated_at" json:"updated_at"`
} }

View file

@ -1,159 +0,0 @@
package database
import (
"database/sql"
"net/url"
"testing"
"time"
)
func TestVersionFromPURL(t *testing.T) {
tests := []struct {
name string
purl string
want string
}{
{"simple", "pkg:npm/lodash@4.17.21", "4.17.21"},
{"namespaced", "pkg:composer/symfony/console@6.0.0", "6.0.0"},
// Debian/Ubuntu versions routinely contain "+", which PURL encodes.
{"encoded plus", "pkg:deb/nmap@7.91%2Bdfsg1%2Breally7.80%2Bdfsg1-2ubuntu0.1", "7.91+dfsg1+really7.80+dfsg1-2ubuntu0.1"},
{"encoded epoch", "pkg:deb/curl@1%3A7.81.0-1", "1:7.81.0-1"},
{"encoded plus with qualifier", "pkg:deb/nmap@7.91%2Bdfsg1?repository_url=http%3A%2F%2Fexample.com", "7.91+dfsg1"},
{"tilde is not encoded", "pkg:deb/foo@1.0~rc1", "1.0~rc1"},
{"no version", "pkg:npm/lodash", ""},
{"invalid escape passed through", "pkg:npm/lodash@1.0%zz", "1.0%zz"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := VersionFromPURL(tt.purl); got != tt.want {
t.Errorf("VersionFromPURL(%q) = %q, want %q", tt.purl, got, tt.want)
}
v := &Version{PURL: tt.purl}
if got := v.Version(); got != tt.want {
t.Errorf("Version.Version() for %q = %q, want %q", tt.purl, got, tt.want)
}
})
}
}
// TestVersionEscapedVersion checks the value the templates put in a URL. It
// must survive the round trip back through the router: escaping here and
// decoding per path segment on the way in has to yield the original version.
func TestVersionEscapedVersion(t *testing.T) {
tests := []struct {
name string
purl string
want string
}{
{"simple", "pkg:npm/lodash@4.17.21", "4.17.21"},
// "+" is legal in a path segment, so it stays literal and the UI keeps
// showing the version the way Debian writes it.
{"plus stays literal", "pkg:deb/nmap@7.91%2Bdfsg1-2ubuntu0.1", "7.91+dfsg1-2ubuntu0.1"},
// A slash would otherwise split the version into two path segments.
{"slash", "pkg:golang/example@release%2F1", "release%2F1"},
// A question mark would otherwise start the query string.
{"question mark", "pkg:npm/example@v1%3Fbuild", "v1%3Fbuild"},
// A version containing a literal "%2B" is stored double-encoded; the
// link must re-encode it or it decodes back to "+" instead.
{"literal percent escape", "pkg:npm/example@1.0%252B", "1.0%252B"},
{"space", "pkg:npm/example@1.0%20beta", "1.0%20beta"},
{"no version", "pkg:npm/lodash", ""},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
v := &Version{PURL: tt.purl}
got := v.EscapedVersion()
if got != tt.want {
t.Errorf("EscapedVersion() for %q = %q, want %q", tt.purl, got, tt.want)
}
// The router decodes each path segment, which must give back the
// version the page displays.
decoded, err := url.PathUnescape(got)
if err != nil {
t.Fatalf("PathUnescape(%q) failed: %v", got, err)
}
if decoded != v.Version() {
t.Errorf("round trip for %q = %q, want %q", tt.purl, decoded, v.Version())
}
})
}
}
func TestVersionDisplayPURL(t *testing.T) {
tests := []struct {
name string
purl string
want string
}{
{"simple", "pkg:npm/lodash@4.17.21", "pkg:npm/lodash@4.17.21"},
{
"encoded plus",
"pkg:deb/nmap@7.91%2Bdfsg1%2Breally7.80%2Bdfsg1-2ubuntu0.1",
"pkg:deb/nmap@7.91+dfsg1+really7.80+dfsg1-2ubuntu0.1",
},
{
"qualifier preserved",
"pkg:deb/nmap@7.91%2Bdfsg1?repository_url=http%3A%2F%2Fexample.com",
"pkg:deb/nmap@7.91+dfsg1?repository_url=http%3A%2F%2Fexample.com",
},
// The namespace is encoded too: MakePURLString("npm", "@babel/core", …)
// produces "pkg:npm/%40babel/core@…".
{"encoded npm scope", "pkg:npm/%40babel/core@7.0.0", "pkg:npm/@babel/core@7.0.0"},
{"encoded scope without version", "pkg:npm/%40babel/core", "pkg:npm/@babel/core"},
{"no version", "pkg:npm/lodash", "pkg:npm/lodash"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
v := &Version{PURL: tt.purl}
if got := v.DisplayPURL(); got != tt.want {
t.Errorf("DisplayPURL() for %q = %q, want %q", tt.purl, got, tt.want)
}
})
}
}
// TestGetRecentlyCachedPackagesDecodesVersion guards the dashboard's "recently
// cached" list, which derives the version from the version PURL.
func TestGetRecentlyCachedPackagesDecodesVersion(t *testing.T) {
runWithBothDatabases(t, func(t *testing.T, db *DB) {
const versionPURL = "pkg:deb/nmap@7.91%2Bdfsg1%2Breally7.80%2Bdfsg1-2ubuntu0.1"
if err := db.UpsertPackage(&Package{
PURL: "pkg:deb/nmap", Ecosystem: "deb", Name: "nmap",
}); err != nil {
t.Fatalf("UpsertPackage failed: %v", err)
}
if err := db.UpsertVersion(&Version{
PURL: versionPURL, PackagePURL: "pkg:deb/nmap",
}); err != nil {
t.Fatalf("UpsertVersion failed: %v", err)
}
if err := db.UpsertArtifact(&Artifact{
VersionPURL: versionPURL,
Filename: "nmap_7.91+dfsg1+really7.80+dfsg1-2ubuntu0.1_amd64.deb",
UpstreamURL: "http://archive.ubuntu.com/ubuntu/pool/universe/n/nmap/nmap.deb",
StoragePath: sql.NullString{String: "/cache/nmap.deb", Valid: true},
FetchedAt: sql.NullTime{Time: time.Now(), Valid: true},
}); err != nil {
t.Fatalf("UpsertArtifact failed: %v", err)
}
recent, err := db.GetRecentlyCachedPackages(10)
if err != nil {
t.Fatalf("GetRecentlyCachedPackages failed: %v", err)
}
if len(recent) != 1 {
t.Fatalf("expected 1 recent package, got %d", len(recent))
}
const want = "7.91+dfsg1+really7.80+dfsg1-2ubuntu0.1"
if recent[0].Version != want {
t.Errorf("Version = %q, want %q", recent[0].Version, want)
}
if recent[0].VersionPURL != versionPURL {
t.Errorf("VersionPURL = %q, want %q", recent[0].VersionPURL, versionPURL)
}
})
}

View file

@ -201,6 +201,43 @@ func (s *Service) CheckVulnerabilities(ctx context.Context, ecosystem, name, ver
return results, nil return results, nil
} }
// BulkCheckVulnerabilities queries vulnerabilities for multiple package versions.
func (s *Service) BulkCheckVulnerabilities(ctx context.Context, packages []struct{ Ecosystem, Name, Version string }) (map[string][]VulnInfo, error) {
purls := make([]*purl.PURL, len(packages))
for i, pkg := range packages {
purls[i] = purl.MakePURL(pkg.Ecosystem, pkg.Name, pkg.Version)
}
vulnResults, err := s.vulnSource.QueryBatch(ctx, purls)
if err != nil {
return nil, err
}
result := make(map[string][]VulnInfo, len(packages))
for i, vulnList := range vulnResults {
pkg := packages[i]
key := purl.MakePURLString(pkg.Ecosystem, pkg.Name, pkg.Version)
var infos []VulnInfo
for _, v := range vulnList {
info := VulnInfo{
ID: v.ID,
Summary: v.Summary,
Severity: v.SeverityLevel(),
CVSSScore: v.CVSSScore(),
FixedVersion: v.FixedVersion(pkg.Ecosystem, pkg.Name),
}
for _, ref := range v.References {
info.References = append(info.References, ref.URL)
}
infos = append(infos, info)
}
result[key] = infos
}
return result, nil
}
// IsOutdated checks if a version is older than the latest version. // IsOutdated checks if a version is older than the latest version.
func (s *Service) IsOutdated(currentVersion, latestVersion string) bool { func (s *Service) IsOutdated(currentVersion, latestVersion string) bool {
if latestVersion == "" || currentVersion == "" { if latestVersion == "" || currentVersion == "" {
@ -251,6 +288,19 @@ func (s *Service) CategorizeLicense(license string) LicenseCategory {
return LicenseUnknown return LicenseUnknown
} }
// NormalizeLicense normalizes a license string to SPDX format.
func (s *Service) NormalizeLicense(license string) string {
if license == "" {
return ""
}
if normalized, err := spdx.NormalizeExpressionLax(license); err == nil {
return normalized
}
return license
}
// EnrichmentResult contains all enrichment data for a package version. // EnrichmentResult contains all enrichment data for a package version.
type EnrichmentResult struct { type EnrichmentResult struct {
Package *PackageInfo Package *PackageInfo

View file

@ -74,3 +74,25 @@ func TestCategorizeLicense(t *testing.T) {
} }
} }
} }
func TestNormalizeLicense(t *testing.T) {
logger := slog.New(slog.NewTextHandler(os.Stdout, nil))
svc := New(logger)
tests := []struct {
input string
expected string
}{
{"MIT", "MIT"},
{"Apache 2", "Apache-2.0"},
{"Apache-2.0", "Apache-2.0"},
{"", ""},
}
for _, tc := range tests {
result := svc.NormalizeLicense(tc.input)
if result != tc.expected {
t.Errorf("NormalizeLicense(%q) = %q, want %q", tc.input, result, tc.expected)
}
}
}

View file

@ -1,23 +1,16 @@
package handler package handler
import ( import (
"bufio"
"encoding/json" "encoding/json"
"errors"
"fmt" "fmt"
"io"
"net/http" "net/http"
"net/url"
"strings" "strings"
"time"
) )
const ( const (
cargoUpstream = "https://index.crates.io" cargoUpstream = "https://index.crates.io"
cargoDownloadBase = "https://static.crates.io/crates" cargoDownloadBase = "https://static.crates.io/crates"
cargoIndexLen1 = 1
cargoIndexLen2 = 2
cargoIndexLen3 = 3
) )
// CargoHandler handles cargo registry protocol requests. // CargoHandler handles cargo registry protocol requests.
@ -29,18 +22,11 @@ type CargoHandler struct {
} }
// NewCargoHandler creates a new cargo protocol handler. // NewCargoHandler creates a new cargo protocol handler.
func NewCargoHandler(proxy *Proxy, proxyURL, indexURL, downloadURL string) *CargoHandler { func NewCargoHandler(proxy *Proxy, proxyURL string) *CargoHandler {
if strings.TrimSpace(indexURL) == "" {
indexURL = cargoUpstream
}
if strings.TrimSpace(downloadURL) == "" {
downloadURL = cargoDownloadBase
}
return &CargoHandler{ return &CargoHandler{
proxy: proxy, proxy: proxy,
indexURL: strings.TrimSuffix(indexURL, "/"), indexURL: cargoUpstream,
downloadURL: strings.TrimSuffix(downloadURL, "/"), downloadURL: cargoDownloadBase,
proxyURL: strings.TrimSuffix(proxyURL, "/"), proxyURL: strings.TrimSuffix(proxyURL, "/"),
} }
} }
@ -70,7 +56,7 @@ func (h *CargoHandler) Routes() http.Handler {
// CargoConfig is the registry configuration returned by config.json. // CargoConfig is the registry configuration returned by config.json.
type CargoConfig struct { type CargoConfig struct {
DL string `json:"dl"` DL string `json:"dl"`
API string `json:"api,omitempty"` API string `json:"api,omitempty"`
} }
@ -94,76 +80,44 @@ func (h *CargoHandler) handleIndex(w http.ResponseWriter, r *http.Request) {
h.proxy.Logger.Info("cargo index request", "crate", name) h.proxy.Logger.Info("cargo index request", "crate", name)
// Build the index path
indexPath := h.buildIndexPath(name) indexPath := h.buildIndexPath(name)
upstreamURL := fmt.Sprintf("%s/%s", h.indexURL, indexPath) upstreamURL := fmt.Sprintf("%s/%s", h.indexURL, indexPath)
body, contentType, err := h.proxy.FetchOrCacheMetadata(r.Context(), "cargo", name, upstreamURL, "text/plain") req, err := http.NewRequestWithContext(r.Context(), http.MethodGet, upstreamURL, nil)
if err != nil {
http.Error(w, "internal error", http.StatusInternalServerError)
return
}
resp, err := http.DefaultClient.Do(req)
if err != nil { if err != nil {
if errors.Is(err, ErrUpstreamNotFound) {
http.Error(w, "not found", http.StatusNotFound)
return
}
h.proxy.Logger.Error("failed to fetch upstream index", "error", err) h.proxy.Logger.Error("failed to fetch upstream index", "error", err)
http.Error(w, "failed to fetch from upstream", http.StatusBadGateway) http.Error(w, "failed to fetch from upstream", http.StatusBadGateway)
return return
} }
defer func() { _ = resp.Body.Close() }()
if contentType == "" { if resp.StatusCode == http.StatusNotFound {
contentType = "text/plain; charset=utf-8" http.Error(w, "not found", http.StatusNotFound)
return
} }
if resp.StatusCode != http.StatusOK {
w.Header().Set("Content-Type", contentType) http.Error(w, fmt.Sprintf("upstream returned %d", resp.StatusCode), http.StatusBadGateway)
w.WriteHeader(http.StatusOK)
h.applyCooldownFiltering(w, body)
}
type crateIndexEntry struct {
Name string `json:"name"`
Version string `json:"vers"`
PublishTime string `json:"pubtime,omitempty"`
}
func (h *CargoHandler) applyCooldownFiltering(downstreamResponse http.ResponseWriter, body []byte) {
if h.proxy.Cooldown == nil || !h.proxy.Cooldown.Enabled() {
_, _ = downstreamResponse.Write(body)
return return
} }
scanner := bufio.NewScanner(strings.NewReader(string(body))) // Copy headers and body
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
for scanner.Scan() { if etag := resp.Header.Get("ETag"); etag != "" {
line := scanner.Text() w.Header().Set("ETag", etag)
}
var crate crateIndexEntry if lastMod := resp.Header.Get("Last-Modified"); lastMod != "" {
err := json.Unmarshal([]byte(line), &crate) w.Header().Set("Last-Modified", lastMod)
if err != nil {
h.proxy.Logger.Error("failed to parse json entry in index", "error", err)
continue
}
publishedAt, err := time.Parse(time.RFC3339, crate.PublishTime)
if crate.PublishTime == "" || err != nil {
_, _ = downstreamResponse.Write([]byte(line + "\n"))
continue
}
cratePURL := canonicalPackagePURL("cargo", crate.Name)
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)
continue
}
_, _ = downstreamResponse.Write([]byte(line + "\n"))
} }
if err := scanner.Err(); err != nil { w.WriteHeader(http.StatusOK)
h.proxy.Logger.Error("error reading index response", "error", err) _, _ = io.Copy(w, resp.Body)
}
} }
// buildIndexPath builds the sparse index path for a crate name. // buildIndexPath builds the sparse index path for a crate name.
@ -171,11 +125,11 @@ func (h *CargoHandler) buildIndexPath(name string) string {
name = strings.ToLower(name) name = strings.ToLower(name)
switch len(name) { switch len(name) {
case cargoIndexLen1: case 1:
return fmt.Sprintf("1/%s", name) return fmt.Sprintf("1/%s", name)
case cargoIndexLen2: case 2:
return fmt.Sprintf("2/%s", name) return fmt.Sprintf("2/%s", name)
case cargoIndexLen3: case 3:
return fmt.Sprintf("3/%c/%s", name[0], name) return fmt.Sprintf("3/%c/%s", name[0], name)
default: default:
return fmt.Sprintf("%s/%s/%s", name[0:2], name[2:4], name) return fmt.Sprintf("%s/%s/%s", name[0:2], name[2:4], name)
@ -197,17 +151,10 @@ func (h *CargoHandler) handleDownload(w http.ResponseWriter, r *http.Request) {
h.proxy.Logger.Info("cargo download request", h.proxy.Logger.Info("cargo download request",
"crate", name, "version", version, "filename", filename) "crate", name, "version", version, "filename", filename)
downloadURL := fmt.Sprintf( result, err := h.proxy.GetOrFetchArtifact(r.Context(), "cargo", name, version, filename)
"%s/%s/%s",
h.downloadURL,
url.PathEscape(name),
url.PathEscape(filename),
)
result, err := h.proxy.GetOrFetchArtifactFromURL(
r.Context(), "cargo", name, version, filename, downloadURL,
)
if err != nil { if err != nil {
h.proxy.serveArtifactError(w, err, "failed to fetch crate") h.proxy.Logger.Error("failed to get artifact", "error", err)
http.Error(w, "failed to fetch crate", http.StatusBadGateway)
return return
} }

View file

@ -2,22 +2,15 @@ package handler
import ( import (
"encoding/json" "encoding/json"
"io"
"log/slog" "log/slog"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
"strings"
"testing" "testing"
"time"
"github.com/git-pkgs/cooldown"
"github.com/git-pkgs/registries/fetch"
) )
func cargoTestProxy() *Proxy { func cargoTestProxy() *Proxy {
return &Proxy{ return &Proxy{
Logger: slog.Default(), Logger: slog.Default(),
HTTPClient: http.DefaultClient,
} }
} }
@ -34,8 +27,8 @@ func TestCargoBuildIndexPath(t *testing.T) {
{"abcd", "ab/cd/abcd"}, {"abcd", "ab/cd/abcd"},
{"serde", "se/rd/serde"}, {"serde", "se/rd/serde"},
{"tokio", "to/ki/tokio"}, {"tokio", "to/ki/tokio"},
{"A", "1/a"}, // lowercase {"A", "1/a"}, // lowercase
{"SERDE", "se/rd/serde"}, // lowercase {"SERDE", "se/rd/serde"}, // lowercase
{"rand_core", "ra/nd/rand_core"}, {"rand_core", "ra/nd/rand_core"},
} }
@ -72,75 +65,6 @@ func TestCargoConfigEndpoint(t *testing.T) {
} }
} }
func TestCargoHandlerUsesConfiguredUpstreams(t *testing.T) {
t.Run("index", func(t *testing.T) {
var requestPath, authHeader string
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
requestPath = r.URL.Path
authHeader = r.Header.Get("Authorization")
if authHeader != "Bearer cargo-token" {
w.WriteHeader(http.StatusUnauthorized)
return
}
w.Header().Set("Content-Type", "text/plain")
_, _ = io.WriteString(w, `{"name":"serde","vers":"1.0.0"}`)
}))
defer upstream.Close()
proxy, _, _, _ := setupTestProxy(t)
proxy.HTTPClient = upstream.Client()
proxy.AuthForURL = func(string) (string, string) {
return "Authorization", "Bearer cargo-token"
}
h := NewCargoHandler(
proxy,
"http://proxy.test",
upstream.URL+"/index/",
"https://crates.example.test/files/",
)
req := httptest.NewRequest(http.MethodGet, "/se/rd/serde", nil)
w := httptest.NewRecorder()
h.Routes().ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("status = %d, want %d; body: %s", w.Code, http.StatusOK, w.Body.String())
}
if requestPath != "/index/se/rd/serde" {
t.Errorf("upstream path = %q, want %q", requestPath, "/index/se/rd/serde")
}
if authHeader != "Bearer cargo-token" {
t.Errorf("Authorization = %q, want %q", authHeader, "Bearer cargo-token")
}
})
t.Run("download", func(t *testing.T) {
proxy, _, _, artifactFetcher := setupTestProxy(t)
artifactFetcher.artifact = &fetch.Artifact{
Body: io.NopCloser(strings.NewReader("crate")),
ContentType: "application/gzip",
}
h := NewCargoHandler(
proxy,
"http://proxy.test",
"https://index.example.test/root/",
"https://crates.example.test/files/",
)
req := httptest.NewRequest(http.MethodGet, "/crates/serde/1.0.0/download", nil)
w := httptest.NewRecorder()
h.Routes().ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("status = %d, want %d; body: %s", w.Code, http.StatusOK, w.Body.String())
}
want := "https://crates.example.test/files/serde/serde-1.0.0.crate"
if artifactFetcher.fetchedURL != want {
t.Errorf("fetched URL = %q, want %q", artifactFetcher.fetchedURL, want)
}
})
}
func TestCargoIndexProxy(t *testing.T) { func TestCargoIndexProxy(t *testing.T) {
// Create a mock upstream index server // Create a mock upstream index server
indexContent := `{"name":"serde","vers":"1.0.0","deps":[],"cksum":"abc123"} indexContent := `{"name":"serde","vers":"1.0.0","deps":[],"cksum":"abc123"}
@ -221,57 +145,3 @@ func TestCargoRoutes(t *testing.T) {
t.Errorf("config.json status = %d, want %d", w.Code, http.StatusOK) t.Errorf("config.json status = %d, want %d", w.Code, http.StatusOK)
} }
} }
type filterTestCase struct {
line string
expected bool
}
func TestCargoCooldown(t *testing.T) {
now := time.Now()
createCase := func(name string, version string, age time.Duration, expected bool) filterTestCase {
return filterTestCase{line: `{"name":"` + name + `","vers":"` + version + `","cksum":"abcd","features":{},"yanked":false,"pubtime":"` + now.Add(-1*age).Format(time.RFC3339) + `"}`, expected: expected}
}
testCases := []filterTestCase{
// one week ago
createCase("serde", "1.0.0", 168*time.Hour, true),
// one hour ago
createCase("serde", "1.0.1", 1*time.Hour, false),
// two hours ago with custom filter (1h)
createCase("tokio", "1.0.0", 2*time.Hour, true),
// one hour ago with custom filter (1h)
createCase("tokio", "1.0.0", 1*time.Minute, false),
}
var testInput strings.Builder
var expectedOutput strings.Builder
for _, testCase := range testCases {
testInput.WriteString(testCase.line + "\n")
if testCase.expected {
expectedOutput.WriteString(testCase.line + "\n")
}
}
proxy := testProxy()
proxy.Cooldown = &cooldown.Config{
Default: "3d",
Packages: map[string]string{"pkg:cargo/tokio": "1h"},
}
h := &CargoHandler{
proxy: proxy,
proxyURL: "http://localhost:8080",
}
recorder := httptest.NewRecorder()
h.applyCooldownFiltering(recorder, []byte(testInput.String()))
output := recorder.Body.String()
if output != expectedOutput.String() {
t.Errorf("output = %q, want %q", output, expectedOutput.String())
}
}

View file

@ -1,22 +1,16 @@
package handler package handler
import ( import (
"context"
"encoding/json" "encoding/json"
"errors"
"fmt" "fmt"
"io" "io"
"net/http" "net/http"
"path"
"strings" "strings"
"time"
) )
const ( const (
composerUpstream = "https://packagist.org" composerUpstream = "https://packagist.org"
composerRepo = "https://repo.packagist.org" composerRepo = "https://repo.packagist.org"
composerUnset = "__unset"
vendorPackageParts = 2
) )
// ComposerHandler handles Composer/Packagist registry protocol requests. // ComposerHandler handles Composer/Packagist registry protocol requests.
@ -61,10 +55,10 @@ func (h *ComposerHandler) Routes() http.Handler {
func (h *ComposerHandler) handleServiceIndex(w http.ResponseWriter, r *http.Request) { func (h *ComposerHandler) handleServiceIndex(w http.ResponseWriter, r *http.Request) {
// Return a minimal service index pointing to our proxy // Return a minimal service index pointing to our proxy
index := map[string]any{ index := map[string]any{
"packages": map[string]any{}, "packages": map[string]any{},
"metadata-url": h.proxyURL + "/composer/p2/%package%.json", "metadata-url": h.proxyURL + "/composer/p2/%package%.json",
"notify-batch": h.upstreamURL + "/downloads/", "notify-batch": h.upstreamURL + "/downloads/",
"search": h.proxyURL + "/composer/search.json?q=%query%&type=%type%", "search": h.proxyURL + "/composer/search.json?q=%query%&type=%type%",
"providers-lazy-url": h.proxyURL + "/composer/p2/%package%.json", "providers-lazy-url": h.proxyURL + "/composer/p2/%package%.json",
} }
@ -77,8 +71,8 @@ func (h *ComposerHandler) handlePackageMetadata(w http.ResponseWriter, r *http.R
// Parse path: /p2/{vendor}/{package}.json // Parse path: /p2/{vendor}/{package}.json
path := strings.TrimPrefix(r.URL.Path, "/p2/") path := strings.TrimPrefix(r.URL.Path, "/p2/")
path = strings.TrimSuffix(path, ".json") path = strings.TrimSuffix(path, ".json")
parts := strings.SplitN(path, "/", vendorPackageParts) parts := strings.SplitN(path, "/", 2)
if len(parts) != vendorPackageParts || parts[0] == "" || parts[1] == "" { if len(parts) != 2 || parts[0] == "" || parts[1] == "" {
http.Error(w, "invalid package path", http.StatusBadRequest) http.Error(w, "invalid package path", http.StatusBadRequest)
return return
} }
@ -88,18 +82,34 @@ func (h *ComposerHandler) handlePackageMetadata(w http.ResponseWriter, r *http.R
h.proxy.Logger.Info("composer metadata request", "package", packageName) h.proxy.Logger.Info("composer metadata request", "package", packageName)
// Fetch from repo.packagist.org (Composer v2 metadata)
upstreamURL := fmt.Sprintf("%s/p2/%s/%s.json", h.repoURL, vendor, pkg) upstreamURL := fmt.Sprintf("%s/p2/%s/%s.json", h.repoURL, vendor, pkg)
body, _, err := h.proxy.FetchOrCacheMetadata(r.Context(), "composer", packageName, upstreamURL) req, err := http.NewRequestWithContext(r.Context(), http.MethodGet, upstreamURL, nil)
if err != nil {
http.Error(w, "failed to create request", http.StatusInternalServerError)
return
}
resp, err := http.DefaultClient.Do(req)
if err != nil { if err != nil {
if errors.Is(err, ErrUpstreamNotFound) {
http.Error(w, "not found", http.StatusNotFound)
return
}
h.proxy.Logger.Error("upstream request failed", "error", err) h.proxy.Logger.Error("upstream request failed", "error", err)
http.Error(w, "upstream request failed", http.StatusBadGateway) http.Error(w, "upstream request failed", http.StatusBadGateway)
return return
} }
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != http.StatusOK {
w.WriteHeader(resp.StatusCode)
_, _ = io.Copy(w, resp.Body)
return
}
body, err := io.ReadAll(resp.Body)
if err != nil {
http.Error(w, "failed to read response", http.StatusInternalServerError)
return
}
rewritten, err := h.rewriteMetadata(body) rewritten, err := h.rewriteMetadata(body)
if err != nil { if err != nil {
@ -114,9 +124,6 @@ func (h *ComposerHandler) handlePackageMetadata(w http.ResponseWriter, r *http.R
} }
// rewriteMetadata rewrites dist URLs in Composer metadata to point at this proxy. // rewriteMetadata rewrites dist URLs in Composer metadata to point at this proxy.
// If the metadata uses the minified Composer v2 format, it is expanded first so
// that every version entry contains all fields. If cooldown is enabled, versions
// published too recently are filtered out.
func (h *ComposerHandler) rewriteMetadata(body []byte) ([]byte, error) { func (h *ComposerHandler) rewriteMetadata(body []byte) ([]byte, error) {
var metadata map[string]any var metadata map[string]any
if err := json.Unmarshal(body, &metadata); err != nil { if err := json.Unmarshal(body, &metadata); err != nil {
@ -128,170 +135,44 @@ func (h *ComposerHandler) rewriteMetadata(body []byte) ([]byte, error) {
return body, nil return body, nil
} }
minified := metadata["minified"] == "composer/2.0"
for packageName, versions := range packages { for packageName, versions := range packages {
versionList, ok := versions.([]any) versionList, ok := versions.([]any)
if !ok { if !ok {
continue continue
} }
if minified { for _, v := range versionList {
versionList = expandMinifiedVersions(versionList) vmap, ok := v.(map[string]any)
} if !ok {
packages[packageName] = h.filterAndRewriteVersions(packageName, versionList)
}
delete(metadata, "minified")
return json.Marshal(metadata)
}
// expandMinifiedVersions expands the Composer v2 minified format where each
// version entry only contains fields that differ from the previous entry.
// The "~dev" sentinel string resets the inheritance chain, and the "__unset"
// value removes a field from the inherited state.
func expandMinifiedVersions(versionList []any) []any {
expanded := make([]any, 0, len(versionList))
inherited := map[string]any{}
for _, v := range versionList {
// The "~dev" sentinel resets the inheritance chain for dev versions.
if s, ok := v.(string); ok && s == "~dev" {
inherited = map[string]any{}
continue
}
vmap, ok := v.(map[string]any)
if !ok {
continue
}
// Merge inherited fields into a new map, then overlay current fields.
// Deep copy values to avoid shared references between versions.
merged := make(map[string]any, len(inherited)+len(vmap))
for k, val := range inherited {
merged[k] = deepCopyValue(val)
}
for k, val := range vmap {
if val == composerUnset {
delete(merged, k)
continue continue
} }
merged[k] = val
}
// Update inherited state for next iteration. version, _ := vmap["version"].(string)
inherited = merged dist, ok := vmap["dist"].(map[string]any)
if !ok {
continue
}
expanded = append(expanded, merged) // Rewrite the dist URL
} if url, ok := dist["url"].(string); ok && url != "" {
// Extract filename from URL
filename := "package.zip"
if idx := strings.LastIndex(url, "/"); idx >= 0 {
filename = url[idx+1:]
}
return expanded // Build new URL through our proxy
} parts := strings.SplitN(packageName, "/", 2)
if len(parts) == 2 {
// deepCopyValue returns a deep copy of JSON-like values (maps, slices, scalars). newURL := fmt.Sprintf("%s/composer/files/%s/%s/%s/%s",
func deepCopyValue(v any) any { h.proxyURL, parts[0], parts[1], version, filename)
switch val := v.(type) { dist["url"] = newURL
case map[string]any: }
m := make(map[string]any, len(val)) }
for k, v := range val {
m[k] = deepCopyValue(v)
}
return m
case []any:
s := make([]any, len(val))
for i, v := range val {
s[i] = deepCopyValue(v)
}
return s
default:
return v
}
}
// filterAndRewriteVersions applies cooldown filtering and rewrites dist URLs
// for a single package's version list.
func (h *ComposerHandler) filterAndRewriteVersions(packageName string, versionList []any) []any {
packagePURL := canonicalPackagePURL("composer", packageName)
filtered := versionList[:0]
for _, v := range versionList {
vmap, ok := v.(map[string]any)
if !ok {
continue
}
version, _ := vmap["version"].(string)
if h.shouldFilterVersion(packagePURL, packageName, version, vmap) {
continue
}
h.rewriteDistURL(vmap, packageName, version)
filtered = append(filtered, v)
}
return filtered
}
// shouldFilterVersion returns true if the version should be excluded due to cooldown.
func (h *ComposerHandler) shouldFilterVersion(packagePURL, packageName, version string, vmap map[string]any) bool {
if h.proxy.Cooldown == nil || !h.proxy.Cooldown.Enabled() {
return false
}
timeStr, ok := vmap["time"].(string)
if !ok {
return false
}
publishedAt, err := time.Parse(time.RFC3339, timeStr)
if err != nil {
return false
}
if !h.proxy.Cooldown.IsAllowed("composer", packagePURL, publishedAt) {
h.proxy.Logger.Info("cooldown: filtering composer version",
"package", packageName, "version", version)
return true
}
return false
}
// rewriteDistURL rewrites the dist URL in a version entry to point at this proxy.
func (h *ComposerHandler) rewriteDistURL(vmap map[string]any, packageName, version string) {
dist, ok := vmap["dist"].(map[string]any)
if !ok {
return
}
url, ok := dist["url"].(string)
if !ok || url == "" {
return
}
filename := "package.zip"
if idx := strings.LastIndex(url, "/"); idx >= 0 {
filename = url[idx+1:]
}
// GitHub zipball URLs end with a bare commit hash (no extension).
// Append .zip so the archives library can detect the format.
if path.Ext(filename) == "" {
if distType, _ := dist["type"].(string); distType == "zip" {
filename += ".zip"
} }
} }
parts := strings.SplitN(packageName, "/", vendorPackageParts) return json.Marshal(metadata)
if len(parts) == vendorPackageParts {
newURL := fmt.Sprintf("%s/composer/files/%s/%s/%s/%s",
h.proxyURL, parts[0], parts[1], version, filename)
dist["url"] = newURL
}
} }
// handleDownload serves a package file, fetching and caching from upstream if needed. // handleDownload serves a package file, fetching and caching from upstream if needed.
@ -306,127 +187,50 @@ func (h *ComposerHandler) handleDownload(w http.ResponseWriter, r *http.Request)
h.proxy.Logger.Info("composer download request", h.proxy.Logger.Info("composer download request",
"package", packageName, "version", version, "filename", filename) "package", packageName, "version", version, "filename", filename)
// We need to fetch the metadata to get the actual download URL since // We need to fetch the metadata to get the actual download URL
// Packagist URLs include a hash. Packagist serves dev versions (e.g. // since Packagist URLs include a hash
// "3.x-dev", "dev-master") from a separate "~dev" metadata file, while metaURL := fmt.Sprintf("%s/p2/%s/%s.json", h.repoURL, vendor, pkg)
// 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", req, err := http.NewRequestWithContext(r.Context(), http.MethodGet, metaURL, nil)
"package", packageName, "version", version, if err != nil {
"metadata_urls", metaURLs) http.Error(w, "failed to create request", http.StatusInternalServerError)
var downloadURL string
for _, metaURL := range metaURLs {
url, err := h.findDownloadURLFromMetadata(r.Context(), metaURL, packageName, version)
if err != nil {
h.proxy.Logger.Error("failed to fetch metadata", "error", err, "url", metaURL)
http.Error(w, "failed to fetch metadata", http.StatusBadGateway)
return
}
if url != "" {
downloadURL = url
break
}
}
if downloadURL == "" {
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 return
} }
h.proxy.Logger.Debug("resolved download URL", resp, err := http.DefaultClient.Do(req)
"package", packageName, "version", version,
"download_url", downloadURL)
result, err := h.proxy.GetOrFetchArtifactFromURL(r.Context(), "composer", packageName, version, filename, downloadURL)
if err != nil { if err != nil {
h.proxy.serveArtifactError(w, err, "failed to fetch package") h.proxy.Logger.Error("failed to fetch metadata", "error", err)
http.Error(w, "failed to fetch metadata", http.StatusBadGateway)
return return
} }
ServeArtifact(w, result)
}
// isDevVersion reports whether a Composer version string refers to a
// development (unstable, branch) version rather than a tagged release.
// Composer formats these as either "dev-<branch>" (e.g. "dev-master") or
// "<alias>-dev" (e.g. "3.x-dev").
func isDevVersion(version string) bool {
return strings.HasPrefix(version, "dev-") || strings.HasSuffix(version, "-dev")
}
// metadataURLsForVersion returns the upstream metadata URLs 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 {
stable := fmt.Sprintf("%s/p2/%s/%s.json", h.repoURL, vendor, pkg)
dev := fmt.Sprintf("%s/p2/%s/%s~dev.json", h.repoURL, vendor, pkg)
if isDevVersion(version) {
return []string{dev, stable}
}
return []string{stable, dev}
}
// findDownloadURLFromMetadata fetches a metadata document and returns the dist
// URL for the given version, or an empty string 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 string so the caller can fall back.
func (h *ComposerHandler) findDownloadURLFromMetadata(ctx context.Context, metaURL, packageName, version string) (string, error) {
h.proxy.Logger.Debug("fetching upstream metadata for download lookup",
"url", metaURL, "package", packageName, "version", version)
req, err := http.NewRequestWithContext(ctx, http.MethodGet, metaURL, nil)
if err != nil {
return "", err
}
resp, err := h.proxy.HTTPClient.Do(req)
if err != nil {
return "", err
}
defer func() { _ = resp.Body.Close() }() defer func() { _ = resp.Body.Close() }()
h.proxy.Logger.Debug("upstream metadata response",
"url", metaURL, "status", resp.StatusCode)
if resp.StatusCode != http.StatusOK { if resp.StatusCode != http.StatusOK {
return "", nil http.Error(w, "package not found", http.StatusNotFound)
return
} }
var metadata map[string]any var metadata map[string]any
if err := json.NewDecoder(resp.Body).Decode(&metadata); err != nil { if err := json.NewDecoder(resp.Body).Decode(&metadata); err != nil {
return "", err http.Error(w, "failed to parse metadata", http.StatusInternalServerError)
return
} }
// Expand minified Composer v2 format so that inherited fields (including // Find the download URL for this version
// dist) are present on every version entry. Without this, versions that downloadURL := h.findDownloadURL(metadata, packageName, version)
// inherit dist from a previous entry will appear to have no download URL. if downloadURL == "" {
if metadata["minified"] == "composer/2.0" { http.Error(w, "version not found", http.StatusNotFound)
h.proxy.Logger.Debug("expanding minified metadata", "url", metaURL) return
if packages, ok := metadata["packages"].(map[string]any); ok {
for pkgName, versions := range packages {
versionList, ok := versions.([]any)
if !ok {
continue
}
packages[pkgName] = expandMinifiedVersions(versionList)
}
}
} }
url := h.findDownloadURL(metadata, packageName, version) result, err := h.proxy.GetOrFetchArtifactFromURL(r.Context(), "composer", packageName, version, filename, downloadURL)
h.proxy.Logger.Debug("download URL lookup result", if err != nil {
"url", metaURL, "package", packageName, "version", version, h.proxy.Logger.Error("failed to get artifact", "error", err)
"download_url", url) http.Error(w, "failed to fetch package", http.StatusBadGateway)
return url, nil return
}
ServeArtifact(w, result)
} }
// findDownloadURL finds the dist URL for a specific version in metadata. // findDownloadURL finds the dist URL for a specific version in metadata.
@ -474,7 +278,7 @@ func (h *ComposerHandler) proxyUpstream(w http.ResponseWriter, r *http.Request)
return return
} }
resp, err := h.proxy.HTTPClient.Do(req) resp, err := http.DefaultClient.Do(req)
if err != nil { if err != nil {
h.proxy.Logger.Error("upstream request failed", "error", err) h.proxy.Logger.Error("upstream request failed", "error", err)
http.Error(w, "upstream request failed", http.StatusBadGateway) http.Error(w, "upstream request failed", http.StatusBadGateway)

View file

@ -1,616 +0,0 @@
package handler
import (
"context"
"encoding/json"
"log/slog"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/git-pkgs/cooldown"
)
func TestComposerRewriteMetadata(t *testing.T) {
h := &ComposerHandler{
proxy: testProxy(),
proxyURL: "http://localhost:8080",
}
input := `{
"packages": {
"symfony/console": [
{
"version": "6.0.0",
"dist": {
"url": "https://repo.packagist.org/files/symfony/console/6.0.0/abc123.zip",
"type": "zip"
}
}
]
}
}`
output, err := h.rewriteMetadata([]byte(input))
if err != nil {
t.Fatalf("rewriteMetadata failed: %v", err)
}
var result map[string]any
if err := json.Unmarshal(output, &result); err != nil {
t.Fatalf("failed to parse output: %v", err)
}
packages := result["packages"].(map[string]any)
versions := packages["symfony/console"].([]any)
v := versions[0].(map[string]any)
dist := v["dist"].(map[string]any)
expected := "http://localhost:8080/composer/files/symfony/console/6.0.0/abc123.zip"
if dist["url"] != expected {
t.Errorf("dist url = %q, want %q", dist["url"], expected)
}
}
func TestComposerRewriteMetadataExpandsMinified(t *testing.T) {
h := &ComposerHandler{
proxy: testProxy(),
proxyURL: "http://localhost:8080",
}
// Minified format: first version has all fields, subsequent versions
// only include fields that changed. The proxy must expand this so every
// version has all fields (including "name").
input := `{
"minified": "composer/2.0",
"packages": {
"symfony/console": [
{
"name": "symfony/console",
"description": "Symfony Console Component",
"version": "6.0.0",
"dist": {
"url": "https://repo.packagist.org/files/symfony/console/6.0.0/abc123.zip",
"type": "zip"
}
},
{
"version": "5.4.0",
"dist": {
"url": "https://repo.packagist.org/files/symfony/console/5.4.0/def456.zip",
"type": "zip"
}
}
]
}
}`
output, err := h.rewriteMetadata([]byte(input))
if err != nil {
t.Fatalf("rewriteMetadata failed: %v", err)
}
var result map[string]any
if err := json.Unmarshal(output, &result); err != nil {
t.Fatalf("failed to parse output: %v", err)
}
// The minified key should be removed from output
if _, ok := result["minified"]; ok {
t.Error("expected minified key to be removed from output")
}
packages := result["packages"].(map[string]any)
versions := packages["symfony/console"].([]any)
// Second version should have inherited the "name" and "description" fields
v1 := versions[1].(map[string]any)
if v1["name"] != "symfony/console" {
t.Errorf("second version name = %v, want %q", v1["name"], "symfony/console")
}
if v1["description"] != "Symfony Console Component" {
t.Errorf("second version description = %v, want %q", v1["description"], "Symfony Console Component")
}
}
func TestComposerRewriteMetadataMinifiedDevReset(t *testing.T) {
h := &ComposerHandler{
proxy: testProxy(),
proxyURL: "http://localhost:8080",
}
// The ~dev sentinel resets the inheritance chain for dev versions.
input := `{
"minified": "composer/2.0",
"packages": {
"symfony/console": [
{
"name": "symfony/console",
"description": "Symfony Console Component",
"license": ["MIT"],
"version": "6.0.0",
"dist": {
"url": "https://repo.packagist.org/files/symfony/console/6.0.0/abc123.zip",
"type": "zip"
}
},
"~dev",
{
"name": "symfony/console",
"version": "dev-main",
"dist": {
"url": "https://repo.packagist.org/files/symfony/console/dev-main/xyz789.zip",
"type": "zip"
}
}
]
}
}`
output, err := h.rewriteMetadata([]byte(input))
if err != nil {
t.Fatalf("rewriteMetadata failed: %v", err)
}
var result map[string]any
if err := json.Unmarshal(output, &result); err != nil {
t.Fatalf("failed to parse output: %v", err)
}
packages := result["packages"].(map[string]any)
versions := packages["symfony/console"].([]any)
if len(versions) != 2 {
t.Fatalf("expected 2 versions, got %d", len(versions))
}
// Dev version should NOT have inherited "license" or "description"
// from the tagged version (the ~dev sentinel resets inheritance).
devVersion := versions[1].(map[string]any)
if devVersion["version"] != "dev-main" {
t.Errorf("dev version = %v, want %q", devVersion["version"], "dev-main")
}
if _, ok := devVersion["license"]; ok {
t.Error("dev version should not have inherited license field after ~dev reset")
}
if _, ok := devVersion["description"]; ok {
t.Error("dev version should not have inherited description field after ~dev reset")
}
}
func TestComposerRewriteMetadataUnset(t *testing.T) {
h := &ComposerHandler{
proxy: &Proxy{Logger: slog.Default()},
proxyURL: "http://localhost:8080",
}
// In the minified format, "__unset" removes a field from the inherited
// state. v1.29.0 has require-dev, v1.28.0 unsets it, v1.27.0 inherits the
// unset state. Composer rejects metadata where require-dev (or any link
// field) is the literal string "__unset" rather than an object.
input := `{
"minified": "composer/2.0",
"packages": {
"venturecraft/revisionable": [
{
"name": "venturecraft/revisionable",
"version": "1.29.0",
"require": {"php": ">=5.4"},
"require-dev": {"orchestra/testbench": "~3.0"},
"dist": {"url": "https://example.com/a.zip", "type": "zip"}
},
{
"version": "1.28.0",
"require-dev": "__unset"
},
{
"version": "1.27.0"
},
{
"version": "1.26.0",
"require-dev": {"foo/bar": "1.0"}
}
]
}
}`
output, err := h.rewriteMetadata([]byte(input))
if err != nil {
t.Fatalf("rewriteMetadata failed: %v", err)
}
var result map[string]any
if err := json.Unmarshal(output, &result); err != nil {
t.Fatalf("failed to parse output: %v", err)
}
versions := result["packages"].(map[string]any)["venturecraft/revisionable"].([]any)
if len(versions) != 4 {
t.Fatalf("expected 4 versions, got %d", len(versions))
}
byVersion := map[string]map[string]any{}
for _, v := range versions {
vmap := v.(map[string]any)
byVersion[vmap["version"].(string)] = vmap
}
if _, ok := byVersion["1.29.0"]["require-dev"].(map[string]any); !ok {
t.Errorf("1.29.0 require-dev should be an object, got %T", byVersion["1.29.0"]["require-dev"])
}
if rd, ok := byVersion["1.28.0"]["require-dev"]; ok {
t.Errorf("1.28.0 require-dev should be absent, got %v", rd)
}
if rd, ok := byVersion["1.27.0"]["require-dev"]; ok {
t.Errorf("1.27.0 require-dev should be absent (inherited unset), got %v", rd)
}
if _, ok := byVersion["1.26.0"]["require-dev"].(map[string]any); !ok {
t.Errorf("1.26.0 require-dev should be an object, got %T", byVersion["1.26.0"]["require-dev"])
}
if _, ok := byVersion["1.27.0"]["require"].(map[string]any); !ok {
t.Error("1.27.0 should still inherit require from 1.29.0")
}
}
func TestComposerRewriteMetadataCooldownPreservesNames(t *testing.T) {
now := time.Now()
old := now.Add(-10 * 24 * time.Hour).Format(time.RFC3339)
veryOld := now.Add(-20 * 24 * time.Hour).Format(time.RFC3339)
recent := now.Add(-1 * time.Hour).Format(time.RFC3339)
proxy := &Proxy{Logger: slog.Default()}
proxy.Cooldown = &cooldown.Config{Default: "3d"}
h := &ComposerHandler{
proxy: proxy,
proxyURL: "http://localhost:8080",
}
// Minified format where "name" only appears in first version.
// When cooldown filters the first version, remaining versions must
// still have the "name" field after expansion.
input := `{
"minified": "composer/2.0",
"packages": {
"symfony/console": [
{
"name": "symfony/console",
"description": "Symfony Console Component",
"version": "7.0.0",
"time": "` + recent + `",
"dist": {"url": "https://repo.packagist.org/7.0.0.zip", "type": "zip"}
},
{
"version": "6.0.0",
"time": "` + old + `",
"dist": {"url": "https://repo.packagist.org/6.0.0.zip", "type": "zip"}
},
{
"version": "5.0.0",
"time": "` + veryOld + `",
"dist": {"url": "https://repo.packagist.org/5.0.0.zip", "type": "zip"}
}
]
}
}`
output, err := h.rewriteMetadata([]byte(input))
if err != nil {
t.Fatalf("rewriteMetadata failed: %v", err)
}
var result map[string]any
if err := json.Unmarshal(output, &result); err != nil {
t.Fatalf("failed to parse output: %v", err)
}
packages := result["packages"].(map[string]any)
versions := packages["symfony/console"].([]any)
// v7.0.0 should be filtered by cooldown, leaving v6.0.0 and v5.0.0
if len(versions) != 2 {
t.Fatalf("expected 2 versions after cooldown, got %d", len(versions))
}
// Both remaining versions must have the "name" field
for _, v := range versions {
vmap := v.(map[string]any)
if vmap["name"] != "symfony/console" {
t.Errorf("version %v missing name field, got %v", vmap["version"], vmap["name"])
}
}
}
func TestComposerRewriteDistURLGitHubZipball(t *testing.T) {
// GitHub zipball URLs end with a bare commit hash, no file extension.
// The proxy must produce a filename with .zip extension so that the
// archives library can detect the format when browsing source.
h := &ComposerHandler{
proxy: testProxy(),
proxyURL: "http://localhost:8080",
}
vmap := map[string]any{
"version": "v7.4.8",
"dist": map[string]any{
"url": "https://api.github.com/repos/symfony/asset/zipball/d2e2f014ccd6ec9fae8dbe6336a4164346a2a856",
"type": "zip",
"shasum": "",
"reference": "d2e2f014ccd6ec9fae8dbe6336a4164346a2a856",
},
}
h.rewriteDistURL(vmap, "symfony/asset", "v7.4.8")
dist := vmap["dist"].(map[string]any)
url := dist["url"].(string)
// The rewritten URL's filename must have a .zip extension
if !strings.HasSuffix(url, ".zip") {
t.Errorf("rewritten dist URL filename has no .zip extension: %s", url)
}
}
func TestComposerRewriteMetadataGitHubZipballFilenames(t *testing.T) {
// End-to-end: metadata with GitHub zipball URLs should produce
// download URLs that end in .zip so browse source can open them.
h := &ComposerHandler{
proxy: testProxy(),
proxyURL: "http://localhost:8080",
}
input := `{
"packages": {
"symfony/config": [
{
"version": "v7.4.8",
"dist": {
"url": "https://api.github.com/repos/symfony/config/zipball/c7369cc1da250fcbfe0c5a9d109e419661549c39",
"type": "zip",
"reference": "c7369cc1da250fcbfe0c5a9d109e419661549c39"
}
}
]
}
}`
output, err := h.rewriteMetadata([]byte(input))
if err != nil {
t.Fatalf("rewriteMetadata failed: %v", err)
}
var result map[string]any
if err := json.Unmarshal(output, &result); err != nil {
t.Fatalf("failed to parse output: %v", err)
}
packages := result["packages"].(map[string]any)
versions := packages["symfony/config"].([]any)
v := versions[0].(map[string]any)
dist := v["dist"].(map[string]any)
url := dist["url"].(string)
if !strings.HasSuffix(url, ".zip") {
t.Errorf("rewritten URL should end in .zip, got %s", url)
}
}
func TestComposerExpandMinifiedSharedDistReferences(t *testing.T) {
// When a minified version inherits the dist field from a previous version
// (i.e. it doesn't include its own dist), expanding + rewriting must not
// corrupt the dist URLs via shared map references.
h := &ComposerHandler{
proxy: testProxy(),
proxyURL: "http://localhost:8080",
}
// In this minified payload, v5.3.0 does NOT include a dist field,
// so it inherits v5.4.0's dist. After expansion and URL rewriting,
// each version must have its own correct dist URL.
input := `{
"minified": "composer/2.0",
"packages": {
"vendor/pkg": [
{
"name": "vendor/pkg",
"version": "5.4.0",
"dist": {
"url": "https://api.github.com/repos/vendor/pkg/zipball/aaa111",
"type": "zip",
"reference": "aaa111"
}
},
{
"version": "5.3.0"
}
]
}
}`
output, err := h.rewriteMetadata([]byte(input))
if err != nil {
t.Fatalf("rewriteMetadata failed: %v", err)
}
var result map[string]any
if err := json.Unmarshal(output, &result); err != nil {
t.Fatalf("failed to parse output: %v", err)
}
packages := result["packages"].(map[string]any)
versions := packages["vendor/pkg"].([]any)
if len(versions) != 2 {
t.Fatalf("expected 2 versions, got %d", len(versions))
}
v1 := versions[0].(map[string]any)
v2 := versions[1].(map[string]any)
dist1 := v1["dist"].(map[string]any)
dist2 := v2["dist"].(map[string]any)
url1 := dist1["url"].(string)
url2 := dist2["url"].(string)
// Each version must have its own URL with its own version in the path
if !strings.Contains(url1, "/5.4.0/") {
t.Errorf("v5.4.0 dist URL should contain /5.4.0/, got %s", url1)
}
if !strings.Contains(url2, "/5.3.0/") {
t.Errorf("v5.3.0 dist URL should contain /5.3.0/, got %s", url2)
}
// The two URLs must be different
if url1 == url2 {
t.Errorf("both versions have the same dist URL (shared reference bug): %s", url1)
}
}
// TestComposerDownloadDevVersionUsesDevMetadata is a regression test for the
// bug that made it impossible to install a *-dev dependency from dist.
//
// Packagist serves development versions (e.g. "3.x-dev", "dev-master") from a
// separate "{package}~dev.json" metadata file; the regular "{package}.json"
// file contains only tagged releases. The download handler used to fetch only
// the regular file, so it could never find the dist URL for a dev version and
// returned 404 — causing Composer to silently fall back to a git clone.
//
// This test serves both files from a mock upstream and asserts that:
// - the OLD behavior (regular file only) cannot resolve the dev version, and
// - the FIXED behavior (consulting the ~dev file) does.
func TestComposerDownloadDevVersionUsesDevMetadata(t *testing.T) {
const (
pkg = "phpmd/phpmd"
vendor = "phpmd"
name = "phpmd"
version = "3.x-dev"
distURL = "https://api.github.com/repos/phpmd/phpmd/zipball/2a9217f60aaf27bf6ddad9188f254d020ab70745"
)
// Regular metadata: tagged releases only — no dev versions.
stableBody := `{
"packages": {
"phpmd/phpmd": [
{"version": "2.15.0", "dist": {"url": "https://example.com/2.15.0.zip", "type": "zip"}}
]
}
}`
// ~dev metadata: where the 3.x-dev version actually lives.
devBody := `{
"packages": {
"phpmd/phpmd": [
{"version": "3.x-dev", "dist": {"url": "` + distURL + `", "type": "zip"}}
]
}
}`
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/p2/phpmd/phpmd.json":
_, _ = w.Write([]byte(stableBody))
case "/p2/phpmd/phpmd~dev.json":
_, _ = w.Write([]byte(devBody))
default:
http.NotFound(w, r)
}
}))
defer srv.Close()
h := &ComposerHandler{
proxy: testProxy(),
repoURL: srv.URL,
proxyURL: "http://localhost:8080",
}
ctx := context.Background()
// OLD behavior: fetching only the regular file fails to resolve the dev
// version, which is what produced the 404 before the fix.
stableURL := srv.URL + "/p2/phpmd/phpmd.json"
got, err := h.findDownloadURLFromMetadata(ctx, stableURL, pkg, version)
if err != nil {
t.Fatalf("unexpected error fetching regular metadata: %v", err)
}
if got != "" {
t.Fatalf("regular metadata unexpectedly contained dev version %q (got %q); "+
"the test no longer reproduces the original bug", version, got)
}
// 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)
}
var resolved string
for _, u := range urls {
resolved, err = h.findDownloadURLFromMetadata(ctx, u, pkg, version)
if err != nil {
t.Fatalf("unexpected error fetching metadata %q: %v", u, err)
}
if resolved != "" {
break
}
}
if resolved != distURL {
t.Errorf("dev version dist URL = %q, want %q", resolved, distURL)
}
}
func TestComposerRewriteMetadataCooldown(t *testing.T) {
now := time.Now()
old := now.Add(-10 * 24 * time.Hour).Format(time.RFC3339)
recent := now.Add(-1 * time.Hour).Format(time.RFC3339)
proxy := &Proxy{Logger: slog.Default()}
proxy.Cooldown = &cooldown.Config{Default: "3d"}
h := &ComposerHandler{
proxy: proxy,
proxyURL: "http://localhost:8080",
}
input := `{
"packages": {
"symfony/console": [
{
"version": "5.0.0",
"time": "` + old + `",
"dist": {"url": "https://repo.packagist.org/5.0.0.zip", "type": "zip"}
},
{
"version": "6.0.0",
"time": "` + recent + `",
"dist": {"url": "https://repo.packagist.org/6.0.0.zip", "type": "zip"}
}
]
}
}`
output, err := h.rewriteMetadata([]byte(input))
if err != nil {
t.Fatalf("rewriteMetadata failed: %v", err)
}
var result map[string]any
if err := json.Unmarshal(output, &result); err != nil {
t.Fatalf("failed to parse output: %v", err)
}
packages := result["packages"].(map[string]any)
versions := packages["symfony/console"].([]any)
if len(versions) != 1 {
t.Fatalf("expected 1 version after cooldown, got %d", len(versions))
}
v := versions[0].(map[string]any)
if v["version"] != "5.0.0" {
t.Errorf("expected version 5.0.0, got %v", v["version"])
}
}

View file

@ -43,8 +43,8 @@ func (h *ConanHandler) Routes() http.Handler {
mux.HandleFunc("GET /v1/files/{name}/{version}/{user}/{channel}/{revision}/package/{pkgref}/{pkgrev}/{filename}", h.handlePackageFile) mux.HandleFunc("GET /v1/files/{name}/{version}/{user}/{channel}/{revision}/package/{pkgref}/{pkgrev}/{filename}", h.handlePackageFile)
mux.HandleFunc("GET /v2/files/{name}/{version}/{user}/{channel}/{revision}/package/{pkgref}/{pkgrev}/{filename}", h.handlePackageFile) mux.HandleFunc("GET /v2/files/{name}/{version}/{user}/{channel}/{revision}/package/{pkgref}/{pkgrev}/{filename}", h.handlePackageFile)
// Proxy all other endpoints (metadata, search, etc.) with caching // Proxy all other endpoints (metadata, search, etc.)
mux.HandleFunc("GET /", h.proxyCached) mux.HandleFunc("GET /", h.proxyUpstream)
return mux return mux
} }
@ -84,7 +84,8 @@ func (h *ConanHandler) handleRecipeFile(w http.ResponseWriter, r *http.Request)
result, err := h.proxy.GetOrFetchArtifactFromURL(r.Context(), "conan", packageName, storageVersion, storageFilename, upstreamURL) result, err := h.proxy.GetOrFetchArtifactFromURL(r.Context(), "conan", packageName, storageVersion, storageFilename, upstreamURL)
if err != nil { if err != nil {
h.proxy.serveArtifactError(w, err, "failed to fetch file") h.proxy.Logger.Error("failed to get artifact", "error", err)
http.Error(w, "failed to fetch file", http.StatusBadGateway)
return return
} }
@ -121,7 +122,8 @@ func (h *ConanHandler) handlePackageFile(w http.ResponseWriter, r *http.Request)
result, err := h.proxy.GetOrFetchArtifactFromURL(r.Context(), "conan", packageName, storageVersion, storageFilename, upstreamURL) result, err := h.proxy.GetOrFetchArtifactFromURL(r.Context(), "conan", packageName, storageVersion, storageFilename, upstreamURL)
if err != nil { if err != nil {
h.proxy.serveArtifactError(w, err, "failed to fetch file") h.proxy.Logger.Error("failed to get artifact", "error", err)
http.Error(w, "failed to fetch file", http.StatusBadGateway)
return return
} }
@ -145,20 +147,6 @@ func (h *ConanHandler) shouldCacheFile(filename string) bool {
return false return false
} }
// 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
}
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. // proxyUpstream forwards a request to conan center without caching.
func (h *ConanHandler) proxyUpstream(w http.ResponseWriter, r *http.Request) { func (h *ConanHandler) proxyUpstream(w http.ResponseWriter, r *http.Request) {
upstreamURL := h.upstreamURL + r.URL.Path upstreamURL := h.upstreamURL + r.URL.Path
@ -179,7 +167,7 @@ func (h *ConanHandler) proxyUpstream(w http.ResponseWriter, r *http.Request) {
req.Header.Set("Authorization", auth) req.Header.Set("Authorization", auth)
} }
resp, err := h.proxy.HTTPClient.Do(req) resp, err := http.DefaultClient.Do(req)
if err != nil { if err != nil {
h.proxy.Logger.Error("upstream request failed", "error", err) h.proxy.Logger.Error("upstream request failed", "error", err)
http.Error(w, "upstream request failed", http.StatusBadGateway) http.Error(w, "upstream request failed", http.StatusBadGateway)

View file

@ -1,476 +0,0 @@
package handler
import (
"io"
"log/slog"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
const testProxyURL = "http://localhost:8080"
func conanTestProxy() *Proxy {
return &Proxy{
Logger: slog.Default(),
HTTPClient: http.DefaultClient,
}
}
func TestConanShouldCacheFile(t *testing.T) {
h := &ConanHandler{}
tests := []struct {
filename string
want bool
}{
{"conan_sources.tgz", true},
{"conan_export.tgz", true},
{"conan_package.tgz", true},
{"conanfile.py", false},
{"conanmanifest.txt", false},
{"conaninfo.txt", false},
{"random.tgz", false},
{"", false},
}
for _, tt := range tests {
got := h.shouldCacheFile(tt.filename)
if got != tt.want {
t.Errorf("shouldCacheFile(%q) = %v, want %v", tt.filename, got, tt.want)
}
}
}
func TestConanPingV1(t *testing.T) {
h := &ConanHandler{
proxy: conanTestProxy(),
proxyURL: testProxyURL,
}
req := httptest.NewRequest(http.MethodGet, "/v1/ping", nil)
w := httptest.NewRecorder()
h.handlePing(w, req)
if w.Code != http.StatusOK {
t.Errorf("status = %d, want %d", w.Code, http.StatusOK)
}
caps := w.Header().Get("X-Conan-Server-Capabilities")
if caps != "revisions" {
t.Errorf("X-Conan-Server-Capabilities = %q, want %q", caps, "revisions")
}
}
func TestConanPingV2(t *testing.T) {
h := &ConanHandler{
proxy: conanTestProxy(),
proxyURL: testProxyURL,
}
req := httptest.NewRequest(http.MethodGet, "/v2/ping", nil)
w := httptest.NewRecorder()
h.handlePing(w, req)
if w.Code != http.StatusOK {
t.Errorf("status = %d, want %d", w.Code, http.StatusOK)
}
caps := w.Header().Get("X-Conan-Server-Capabilities")
if caps != "revisions" {
t.Errorf("X-Conan-Server-Capabilities = %q, want %q", caps, "revisions")
}
}
func TestConanProxyUpstream(t *testing.T) {
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/v2/conans/search" {
w.WriteHeader(http.StatusNotFound)
return
}
if r.URL.Query().Get("q") != "zlib" {
w.WriteHeader(http.StatusBadRequest)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(`{"results":["zlib/1.2.13"]}`))
}))
defer upstream.Close()
h := &ConanHandler{
proxy: conanTestProxy(),
upstreamURL: upstream.URL,
proxyURL: "http://proxy.local",
}
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)
}
}
func TestConanProxyUpstreamNotFound(t *testing.T) {
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNotFound)
}))
defer upstream.Close()
h := &ConanHandler{
proxy: conanTestProxy(),
upstreamURL: upstream.URL,
proxyURL: "http://proxy.local",
}
req := httptest.NewRequest(http.MethodGet, "/v2/conans/nonexistent", nil)
w := httptest.NewRecorder()
h.proxyUpstream(w, req)
if w.Code != http.StatusNotFound {
t.Errorf("status = %d, want %d", w.Code, http.StatusNotFound)
}
}
func TestConanProxyUpstreamCopiesHeaders(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("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(`{}`))
}))
defer upstream.Close()
h := &ConanHandler{
proxy: conanTestProxy(),
upstreamURL: upstream.URL,
proxyURL: "http://proxy.local",
}
req := httptest.NewRequest(http.MethodGet, "/v2/conans/test", nil)
w := httptest.NewRecorder()
h.proxyUpstream(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")
}
}
func TestConanProxyUpstreamForwardsAuthHeader(t *testing.T) {
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
auth := r.Header.Get("Authorization")
if auth != "Bearer mytoken" {
w.WriteHeader(http.StatusUnauthorized)
return
}
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(`{"ok":true}`))
}))
defer upstream.Close()
h := &ConanHandler{
proxy: conanTestProxy(),
upstreamURL: upstream.URL,
proxyURL: "http://proxy.local",
}
req := httptest.NewRequest(http.MethodGet, "/v2/conans/test", nil)
req.Header.Set("Authorization", "Bearer mytoken")
w := httptest.NewRecorder()
h.proxyUpstream(w, req)
if w.Code != http.StatusOK {
t.Errorf("status = %d, want %d", w.Code, http.StatusOK)
}
}
func TestConanProxyUpstreamBadUpstream(t *testing.T) {
h := &ConanHandler{
proxy: conanTestProxy(),
upstreamURL: "http://127.0.0.1:1", // unreachable
proxyURL: "http://proxy.local",
}
req := httptest.NewRequest(http.MethodGet, "/v2/conans/test", nil)
w := httptest.NewRecorder()
h.proxyUpstream(w, req)
if w.Code != http.StatusBadGateway {
t.Errorf("status = %d, want %d", w.Code, http.StatusBadGateway)
}
}
func TestConanRecipeFileNonCacheable(t *testing.T) {
// When a recipe file is not cacheable (e.g. conanfile.py), it should be proxied upstream.
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/plain")
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte("conanfile content"))
}))
defer upstream.Close()
h := &ConanHandler{
proxy: conanTestProxy(),
upstreamURL: upstream.URL,
proxyURL: "http://proxy.local",
}
req := httptest.NewRequest(http.MethodGet, "/v2/files/zlib/1.2.13/_/_/abc123/recipe/conanfile.py", nil)
req.SetPathValue("name", "zlib")
req.SetPathValue("version", "1.2.13")
req.SetPathValue("user", "_")
req.SetPathValue("channel", "_")
req.SetPathValue("revision", "abc123")
req.SetPathValue("filename", "conanfile.py")
w := httptest.NewRecorder()
h.handleRecipeFile(w, req)
if w.Code != http.StatusOK {
t.Errorf("status = %d, want %d", w.Code, http.StatusOK)
}
body := w.Body.String()
if body != "conanfile content" {
t.Errorf("body = %q, want %q", body, "conanfile content")
}
}
func TestConanPackageFileNonCacheable(t *testing.T) {
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/plain")
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte("conaninfo content"))
}))
defer upstream.Close()
h := &ConanHandler{
proxy: conanTestProxy(),
upstreamURL: upstream.URL,
proxyURL: "http://proxy.local",
}
req := httptest.NewRequest(http.MethodGet, "/v2/files/zlib/1.2.13/_/_/abc123/package/pkgref1/pkgrev1/conaninfo.txt", nil)
req.SetPathValue("name", "zlib")
req.SetPathValue("version", "1.2.13")
req.SetPathValue("user", "_")
req.SetPathValue("channel", "_")
req.SetPathValue("revision", "abc123")
req.SetPathValue("pkgref", "pkgref1")
req.SetPathValue("pkgrev", "pkgrev1")
req.SetPathValue("filename", "conaninfo.txt")
w := httptest.NewRecorder()
h.handlePackageFile(w, req)
if w.Code != http.StatusOK {
t.Errorf("status = %d, want %d", w.Code, http.StatusOK)
}
body := w.Body.String()
if body != "conaninfo content" {
t.Errorf("body = %q, want %q", body, "conaninfo content")
}
}
func TestConanRoutes(t *testing.T) {
h := &ConanHandler{
proxy: conanTestProxy(),
upstreamURL: "http://localhost:1", // won't be called for ping
proxyURL: "http://proxy.local",
}
routes := h.Routes()
tests := []struct {
path string
wantStatus int
}{
{"/v1/ping", http.StatusOK},
{"/v2/ping", http.StatusOK},
}
for _, tt := range tests {
req := httptest.NewRequest(http.MethodGet, tt.path, nil)
w := httptest.NewRecorder()
routes.ServeHTTP(w, req)
if w.Code != tt.wantStatus {
t.Errorf("GET %s: status = %d, want %d", tt.path, w.Code, tt.wantStatus)
}
}
}
func TestConanProxyUpstreamPreservesQueryString(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" {
w.WriteHeader(http.StatusBadRequest)
return
}
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(`ok`))
}))
defer upstream.Close()
h := &ConanHandler{
proxy: conanTestProxy(),
upstreamURL: upstream.URL,
proxyURL: "http://proxy.local",
}
req := httptest.NewRequest(http.MethodGet, "/v2/conans/search?q=boost&page=2", nil)
w := httptest.NewRecorder()
h.proxyUpstream(w, req)
if w.Code != http.StatusOK {
t.Errorf("status = %d, want %d", w.Code, http.StatusOK)
}
}
func TestConanProxyUpstreamLargeResponse(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)
_, _ = w.Write([]byte(largeBody))
}))
defer upstream.Close()
h := &ConanHandler{
proxy: conanTestProxy(),
upstreamURL: upstream.URL,
proxyURL: "http://proxy.local",
}
req := httptest.NewRequest(http.MethodGet, "/v2/conans/test", nil)
w := httptest.NewRecorder()
h.proxyUpstream(w, req)
if w.Code != http.StatusOK {
t.Errorf("status = %d, want %d", w.Code, http.StatusOK)
}
if w.Body.Len() != len(largeBody) {
t.Errorf("body length = %d, want %d", w.Body.Len(), len(largeBody))
}
}
func TestNewConanHandler(t *testing.T) {
proxy := conanTestProxy()
h := NewConanHandler(proxy, "http://localhost:8080/")
if h.proxy != proxy {
t.Error("proxy not set correctly")
}
if h.upstreamURL != conanUpstream {
t.Errorf("upstreamURL = %q, want %q", h.upstreamURL, conanUpstream)
}
if h.proxyURL != testProxyURL {
t.Errorf("proxyURL = %q, want %q (trailing slash should be trimmed)", h.proxyURL, testProxyURL)
}
}
func TestNewConanHandlerNoTrailingSlash(t *testing.T) {
proxy := conanTestProxy()
h := NewConanHandler(proxy, testProxyURL)
if h.proxyURL != testProxyURL {
t.Errorf("proxyURL = %q, want %q", h.proxyURL, testProxyURL)
}
}
func TestConanProxyUpstreamNoAuthHeaderWhenNotProvided(t *testing.T) {
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
auth := r.Header.Get("Authorization")
if auth != "" {
w.WriteHeader(http.StatusBadRequest)
_, _ = w.Write([]byte("unexpected auth header"))
return
}
w.WriteHeader(http.StatusOK)
}))
defer upstream.Close()
h := &ConanHandler{
proxy: conanTestProxy(),
upstreamURL: upstream.URL,
proxyURL: "http://proxy.local",
}
req := httptest.NewRequest(http.MethodGet, "/v2/conans/test", nil)
w := httptest.NewRecorder()
h.proxyUpstream(w, req)
if w.Code != http.StatusOK {
t.Errorf("status = %d, want %d", w.Code, http.StatusOK)
}
}
func TestConanProxyUpstreamCopiesBody(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")
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(expected))
}))
defer upstream.Close()
h := &ConanHandler{
proxy: conanTestProxy(),
upstreamURL: upstream.URL,
proxyURL: "http://proxy.local",
}
req := httptest.NewRequest(http.MethodGet, "/v2/conans/zlib/1.2.13/_/_/latest", nil)
w := httptest.NewRecorder()
h.proxyUpstream(w, req)
if w.Code != http.StatusOK {
t.Errorf("status = %d, want %d", w.Code, http.StatusOK)
}
got, _ := io.ReadAll(w.Body)
if string(got) != expected {
t.Errorf("body = %q, want %q", string(got), expected)
}
}
func TestConanProxyUpstreamPreservesStatusCodes(t *testing.T) {
codes := []int{
http.StatusOK,
http.StatusNotFound,
http.StatusForbidden,
http.StatusInternalServerError,
}
for _, code := range codes {
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(code)
}))
h := &ConanHandler{
proxy: conanTestProxy(),
upstreamURL: upstream.URL,
proxyURL: "http://proxy.local",
}
req := httptest.NewRequest(http.MethodGet, "/v2/test", nil)
w := httptest.NewRecorder()
h.proxyUpstream(w, req)
if w.Code != code {
t.Errorf("status = %d, want %d", w.Code, code)
}
upstream.Close()
}
}

View file

@ -1,16 +1,13 @@
package handler package handler
import ( import (
"encoding/json"
"io" "io"
"net/http" "net/http"
"strings" "strings"
"time"
) )
const ( const (
condaUpstream = "https://conda.anaconda.org" condaUpstream = "https://conda.anaconda.org"
minCondaParts = 3 // name-version-build requires at least 3 hyphen-separated parts
) )
// CondaHandler handles Conda/Anaconda registry protocol requests. // CondaHandler handles Conda/Anaconda registry protocol requests.
@ -34,9 +31,9 @@ func (h *CondaHandler) Routes() http.Handler {
mux := http.NewServeMux() mux := http.NewServeMux()
// Channel index (repodata) // Channel index (repodata)
mux.HandleFunc("GET /{channel}/{arch}/repodata.json", h.handleRepodata) mux.HandleFunc("GET /{channel}/{arch}/repodata.json", h.proxyUpstream)
mux.HandleFunc("GET /{channel}/{arch}/repodata.json.bz2", h.proxyCached) mux.HandleFunc("GET /{channel}/{arch}/repodata.json.bz2", h.proxyUpstream)
mux.HandleFunc("GET /{channel}/{arch}/current_repodata.json", h.handleRepodata) mux.HandleFunc("GET /{channel}/{arch}/current_repodata.json", h.proxyUpstream)
// Package downloads (cache these) // Package downloads (cache these)
mux.HandleFunc("GET /{channel}/{arch}/{filename}", h.handleDownload) mux.HandleFunc("GET /{channel}/{arch}/{filename}", h.handleDownload)
@ -72,7 +69,8 @@ func (h *CondaHandler) handleDownload(w http.ResponseWriter, r *http.Request) {
result, err := h.proxy.GetOrFetchArtifactFromURL(r.Context(), "conda", packageName, version, filename, upstreamURL) result, err := h.proxy.GetOrFetchArtifactFromURL(r.Context(), "conda", packageName, version, filename, upstreamURL)
if err != nil { if err != nil {
h.proxy.serveArtifactError(w, err, "failed to fetch package") h.proxy.Logger.Error("failed to get artifact", "error", err)
http.Error(w, "failed to fetch package", http.StatusBadGateway)
return return
} }
@ -100,7 +98,7 @@ func (h *CondaHandler) parseFilename(filename string) (name, version string) {
// Split by hyphens, the format is name-version-build // Split by hyphens, the format is name-version-build
// The name can contain hyphens, so we need to find version-build at the end // The name can contain hyphens, so we need to find version-build at the end
parts := strings.Split(base, "-") parts := strings.Split(base, "-")
if len(parts) < minCondaParts { if len(parts) < 3 {
return "", "" return "", ""
} }
@ -121,25 +119,24 @@ func (h *CondaHandler) parseFilename(filename string) (name, version string) {
return name, version return name, version
} }
// handleRepodata proxies repodata.json, applying cooldown filtering when enabled. // proxyUpstream forwards a request to Anaconda without caching.
func (h *CondaHandler) handleRepodata(w http.ResponseWriter, r *http.Request) { func (h *CondaHandler) proxyUpstream(w http.ResponseWriter, r *http.Request) {
if h.proxy.Cooldown == nil || !h.proxy.Cooldown.Enabled() {
h.proxyCached(w, r)
return
}
upstreamURL := h.upstreamURL + r.URL.Path upstreamURL := h.upstreamURL + r.URL.Path
h.proxy.Logger.Debug("fetching repodata for cooldown filtering", "url", upstreamURL) h.proxy.Logger.Debug("proxying to upstream", "url", upstreamURL)
req, err := http.NewRequestWithContext(r.Context(), http.MethodGet, upstreamURL, nil) req, err := http.NewRequestWithContext(r.Context(), http.MethodGet, upstreamURL, nil)
if err != nil { if err != nil {
http.Error(w, "failed to create request", http.StatusInternalServerError) http.Error(w, "failed to create request", http.StatusInternalServerError)
return return
} }
req.Header.Set(headerAcceptEncoding, "gzip")
resp, err := h.proxy.HTTPClient.Do(req) // Copy accept-encoding for compression
if ae := r.Header.Get("Accept-Encoding"); ae != "" {
req.Header.Set("Accept-Encoding", ae)
}
resp, err := http.DefaultClient.Do(req)
if err != nil { if err != nil {
h.proxy.Logger.Error("upstream request failed", "error", err) h.proxy.Logger.Error("upstream request failed", "error", err)
http.Error(w, "upstream request failed", http.StatusBadGateway) http.Error(w, "upstream request failed", http.StatusBadGateway)
@ -147,96 +144,12 @@ func (h *CondaHandler) handleRepodata(w http.ResponseWriter, r *http.Request) {
} }
defer func() { _ = resp.Body.Close() }() defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != http.StatusOK { for k, vv := range resp.Header {
for k, vv := range resp.Header { for _, v := range vv {
for _, v := range vv { w.Header().Add(k, v)
w.Header().Add(k, v)
}
}
w.WriteHeader(resp.StatusCode)
_, _ = io.Copy(w, resp.Body)
return
}
body, err := h.proxy.ReadMetadata(resp.Body)
if err != nil {
http.Error(w, "failed to read response", http.StatusInternalServerError)
return
}
filtered, err := h.applyCooldownFiltering(body)
if err != nil {
h.proxy.Logger.Warn("failed to filter repodata, proxying original", "error", err)
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write(body)
return
}
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write(filtered)
}
// condaTimestampDivisor converts Conda's millisecond timestamps to seconds.
const condaTimestampDivisor = 1000
// 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
}
var repodata map[string]any
if err := json.Unmarshal(body, &repodata); 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)
}
} }
} }
return json.Marshal(repodata) w.WriteHeader(resp.StatusCode)
} _, _ = io.Copy(w, resp.Body)
// 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, "/", "_")
h.proxy.ProxyCached(w, r, h.upstreamURL+r.URL.Path, "conda", cacheKey, "*/*")
}
// proxyUpstream forwards a request to Anaconda without caching.
func (h *CondaHandler) proxyUpstream(w http.ResponseWriter, r *http.Request) {
h.proxy.ProxyUpstream(w, r, h.upstreamURL+r.URL.Path, []string{headerAcceptEncoding})
} }

View file

@ -1,14 +1,8 @@
package handler package handler
import ( import (
"encoding/json"
"log/slog" "log/slog"
"net/http"
"net/http/httptest"
"testing" "testing"
"time"
"github.com/git-pkgs/cooldown"
) )
func TestCondaParseFilename(t *testing.T) { func TestCondaParseFilename(t *testing.T) {
@ -55,251 +49,3 @@ func TestCondaIsPackageFile(t *testing.T) {
} }
} }
} }
func TestCondaCooldownFiltering(t *testing.T) {
now := time.Now()
oldTimestamp := float64(now.Add(-7 * 24 * time.Hour).UnixMilli())
recentTimestamp := float64(now.Add(-1 * time.Hour).UnixMilli())
repodata := map[string]any{
"info": map[string]any{},
"packages": map[string]any{
"numpy-1.24.0-old.tar.bz2": map[string]any{
"name": "numpy",
"version": "1.24.0",
"timestamp": oldTimestamp,
},
"numpy-1.25.0-new.tar.bz2": map[string]any{
"name": "numpy",
"version": "1.25.0",
"timestamp": recentTimestamp,
},
},
"packages.conda": map[string]any{
"scipy-1.11.0-old.conda": map[string]any{
"name": "scipy",
"version": "1.11.0",
"timestamp": oldTimestamp,
},
"scipy-1.12.0-new.conda": map[string]any{
"name": "scipy",
"version": "1.12.0",
"timestamp": recentTimestamp,
},
},
}
body, err := json.Marshal(repodata)
if err != nil {
t.Fatal(err)
}
proxy := testProxy()
proxy.Cooldown = &cooldown.Config{
Default: "3d",
}
h := &CondaHandler{
proxy: proxy,
proxyURL: "http://localhost:8080",
}
filtered, err := h.applyCooldownFiltering(body)
if err != nil {
t.Fatal(err)
}
var result map[string]any
if err := json.Unmarshal(filtered, &result); err != nil {
t.Fatal(err)
}
packages := result["packages"].(map[string]any)
if len(packages) != 1 {
t.Fatalf("expected 1 package in packages, got %d", len(packages))
}
if _, ok := packages["numpy-1.24.0-old.tar.bz2"]; !ok {
t.Error("expected old numpy to survive filtering")
}
condaPkgs := result["packages.conda"].(map[string]any)
if len(condaPkgs) != 1 {
t.Fatalf("expected 1 package in packages.conda, got %d", len(condaPkgs))
}
if _, ok := condaPkgs["scipy-1.11.0-old.conda"]; !ok {
t.Error("expected old scipy to survive filtering")
}
}
func TestCondaCooldownFilteringWithPackageOverride(t *testing.T) {
now := time.Now()
recentTimestamp := float64(now.Add(-2 * time.Hour).UnixMilli())
repodata := map[string]any{
"info": map[string]any{},
"packages": map[string]any{
"special-1.0.0-build.tar.bz2": map[string]any{
"name": "special",
"version": "1.0.0",
"timestamp": recentTimestamp,
},
},
"packages.conda": map[string]any{},
}
body, err := json.Marshal(repodata)
if err != nil {
t.Fatal(err)
}
proxy := testProxy()
proxy.Cooldown = &cooldown.Config{
Default: "3d",
Packages: map[string]string{"pkg:conda/special": "1h"},
}
h := &CondaHandler{
proxy: proxy,
proxyURL: "http://localhost:8080",
}
filtered, err := h.applyCooldownFiltering(body)
if err != nil {
t.Fatal(err)
}
var result map[string]any
if err := json.Unmarshal(filtered, &result); err != nil {
t.Fatal(err)
}
packages := result["packages"].(map[string]any)
if len(packages) != 1 {
t.Fatalf("expected 1 package (override allows it), got %d", len(packages))
}
}
func TestCondaCooldownFilteringNoTimestamp(t *testing.T) {
repodata := map[string]any{
"info": map[string]any{},
"packages": map[string]any{
"old-pkg-1.0.0-build.tar.bz2": map[string]any{
"name": "old-pkg",
"version": "1.0.0",
// no timestamp field
},
},
"packages.conda": map[string]any{},
}
body, err := json.Marshal(repodata)
if err != nil {
t.Fatal(err)
}
proxy := testProxy()
proxy.Cooldown = &cooldown.Config{
Default: "3d",
}
h := &CondaHandler{
proxy: proxy,
proxyURL: "http://localhost:8080",
}
filtered, err := h.applyCooldownFiltering(body)
if err != nil {
t.Fatal(err)
}
var result map[string]any
if err := json.Unmarshal(filtered, &result); err != nil {
t.Fatal(err)
}
packages := result["packages"].(map[string]any)
if len(packages) != 1 {
t.Fatalf("entries without timestamp should pass through, got %d", len(packages))
}
}
func TestCondaHandleRepodataWithCooldown(t *testing.T) {
now := time.Now()
oldTimestamp := float64(now.Add(-7 * 24 * time.Hour).UnixMilli())
recentTimestamp := float64(now.Add(-1 * time.Hour).UnixMilli())
repodataJSON, _ := json.Marshal(map[string]any{
"info": map[string]any{},
"packages": map[string]any{
"old-1.0.0-build.tar.bz2": map[string]any{
"name": "testpkg", "version": "1.0.0", "timestamp": oldTimestamp,
},
"new-2.0.0-build.tar.bz2": map[string]any{
"name": "testpkg", "version": "2.0.0", "timestamp": recentTimestamp,
},
},
"packages.conda": map[string]any{},
})
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write(repodataJSON)
}))
defer upstream.Close()
proxy := testProxy()
proxy.Cooldown = &cooldown.Config{
Default: "3d",
}
h := &CondaHandler{
proxy: proxy,
upstreamURL: upstream.URL,
proxyURL: "http://proxy.local",
}
req := httptest.NewRequest(http.MethodGet, "/conda-forge/noarch/repodata.json", nil)
req.SetPathValue("channel", "conda-forge")
req.SetPathValue("arch", "noarch")
w := httptest.NewRecorder()
h.handleRepodata(w, req)
if w.Code != http.StatusOK {
t.Fatalf("status = %d, want %d", w.Code, http.StatusOK)
}
var result map[string]any
if err := json.Unmarshal(w.Body.Bytes(), &result); err != nil {
t.Fatal(err)
}
packages := result["packages"].(map[string]any)
if len(packages) != 1 {
t.Fatalf("expected 1 package after filtering, got %d", len(packages))
}
}
func TestCondaHandleRepodataWithoutCooldown(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(`{"info":{},"packages":{},"packages.conda":{}}`))
}))
defer upstream.Close()
h := &CondaHandler{
proxy: &Proxy{Logger: slog.Default(), HTTPClient: http.DefaultClient},
upstreamURL: upstream.URL,
proxyURL: "http://proxy.local",
}
req := httptest.NewRequest(http.MethodGet, "/conda-forge/noarch/repodata.json", nil)
req.SetPathValue("channel", "conda-forge")
req.SetPathValue("arch", "noarch")
w := httptest.NewRecorder()
h.handleRepodata(w, req)
// Without cooldown, should proxy directly (response comes from upstream)
if w.Code != http.StatusOK {
t.Fatalf("status = %d, want %d", w.Code, http.StatusOK)
}
}

View file

@ -2,7 +2,6 @@ package handler
import ( import (
"encoding/json" "encoding/json"
"errors"
"fmt" "fmt"
"io" "io"
"net/http" "net/http"
@ -11,40 +10,28 @@ import (
) )
const ( const (
dockerHubRegistry = "https://registry-1.docker.io" dockerHubRegistry = "https://registry-1.docker.io"
blobMatchCount = 3 // full match + name + digest dockerHubAuth = "https://auth.docker.io"
manifestMatchCount = 3 // full match + name + reference
tagsListMatchCount = 2 // full match + name
registrySelectorParts = 3 // upstream + name + repository
) )
// ContainerHandler handles OCI/Docker container registry protocol requests. // ContainerHandler handles OCI/Docker container registry protocol requests.
// It implements the OCI Distribution Spec for pulling images. // It implements the OCI Distribution Spec for pulling images.
// Reference: https://github.com/opencontainers/distribution-spec/blob/main/spec.md // Reference: https://github.com/opencontainers/distribution-spec/blob/main/spec.md
type ContainerHandler struct { type ContainerHandler struct {
proxy *Proxy proxy *Proxy
registryURL string registryURL string
proxyURL string authURL string
namedRegistries map[string]string proxyURL string
} }
// NewContainerHandler creates a new container registry protocol handler. // NewContainerHandler creates a new container registry protocol handler.
// Named registries are selected with the repository prefix func NewContainerHandler(proxy *Proxy, proxyURL string) *ContainerHandler {
// upstream/{name}/, leaving unprefixed requests compatible with the Docker Hub return &ContainerHandler{
// mirror behavior.
func NewContainerHandler(proxy *Proxy, proxyURL string, namedRegistries ...map[string]string) *ContainerHandler {
h := &ContainerHandler{
proxy: proxy, proxy: proxy,
registryURL: dockerHubRegistry, registryURL: dockerHubRegistry,
authURL: dockerHubAuth,
proxyURL: strings.TrimSuffix(proxyURL, "/"), proxyURL: strings.TrimSuffix(proxyURL, "/"),
} }
if len(namedRegistries) > 0 {
h.namedRegistries = make(map[string]string, len(namedRegistries[0]))
for name, registryURL := range namedRegistries[0] {
h.namedRegistries[name] = strings.TrimSuffix(registryURL, "/")
}
}
return h
} }
// Routes returns the HTTP handler for container registry requests. // Routes returns the HTTP handler for container registry requests.
@ -97,68 +84,46 @@ func (h *ContainerHandler) handleBlobDownload(w http.ResponseWriter, r *http.Req
return return
} }
registryURL, upstreamName, cacheName, ok := h.registryForName(name) h.proxy.Logger.Info("container blob request", "name", name, "digest", digest)
if !ok {
h.containerError(w, http.StatusNotFound, "NAME_UNKNOWN", "unknown upstream registry")
return
}
h.proxy.Logger.Info("container blob request", "name", upstreamName, "digest", digest) // Get auth token for upstream
token, err := h.getAuthToken(r.Context(), name, "pull")
filename := digest
cached, err := h.proxy.GetCachedArtifact(r.Context(), "oci", cacheName, digest, filename)
if err != nil { if err != nil {
h.proxy.Logger.Error("failed to check blob cache", "error", err) h.proxy.Logger.Error("failed to get auth token", "error", err)
h.containerError(w, http.StatusInternalServerError, "INTERNAL_ERROR", "failed to check blob cache") h.containerError(w, http.StatusUnauthorized, "UNAUTHORIZED", "failed to authenticate")
return
}
if cached != nil {
w.Header().Set("Docker-Content-Digest", digest)
if cached.ContentType != "" {
w.Header().Set("Content-Type", cached.ContentType)
} else {
w.Header().Set("Content-Type", "application/octet-stream")
}
serveArtifact(w, r.Method, cached)
return return
} }
// For HEAD requests, just proxy to upstream // For HEAD requests, just proxy to upstream
if r.Method == http.MethodHead { if r.Method == http.MethodHead {
h.proxyBlobHead(w, r, registryURL, upstreamName, digest) h.proxyBlobHead(w, r, name, digest, token)
return return
} }
// Try to get from cache, or fetch from the authentication-aware upstream client. // Try to get from cache first
filename := digest
result, err := h.proxy.GetOrFetchArtifactFromURL( result, err := h.proxy.GetOrFetchArtifactFromURL(
r.Context(), r.Context(),
"oci", "oci",
cacheName, name,
digest, // use digest as version digest, // use digest as version
filename, filename,
fmt.Sprintf("%s/v2/%s/blobs/%s", registryURL, upstreamName, digest), fmt.Sprintf("%s/v2/%s/blobs/%s", h.registryURL, name, digest),
) )
if err != nil { if err != nil {
if errors.Is(err, ErrUpstreamNotFound) { // Fetch directly with auth
h.containerError(w, http.StatusNotFound, "BLOB_UNKNOWN", "blob unknown to registry") h.proxyBlobWithAuth(w, r, name, digest, token)
return
}
h.proxy.Logger.Error("failed to fetch blob", "error", err)
h.containerError(w, http.StatusBadGateway, "INTERNAL_ERROR", "failed to fetch blob")
return return
} }
w.Header().Set("Docker-Content-Digest", digest) w.Header().Set("Docker-Content-Digest", digest)
if result.ContentType != "" { w.Header().Set("Content-Type", "application/octet-stream")
w.Header().Set("Content-Type", result.ContentType)
} else {
w.Header().Set("Content-Type", "application/octet-stream")
}
ServeArtifact(w, result) ServeArtifact(w, result)
} }
// handleManifest serves immutable manifests from cache and revalidates mutable tags. // handleManifest proxies manifest requests to upstream.
// Manifests change when tags are updated, so we proxy these directly.
// Path format: {name}/manifests/{reference} // Path format: {name}/manifests/{reference}
func (h *ContainerHandler) handleManifest(w http.ResponseWriter, r *http.Request, path string) { func (h *ContainerHandler) handleManifest(w http.ResponseWriter, r *http.Request, path string) {
if r.Method != http.MethodGet && r.Method != http.MethodHead { if r.Method != http.MethodGet && r.Method != http.MethodHead {
@ -172,14 +137,58 @@ func (h *ContainerHandler) handleManifest(w http.ResponseWriter, r *http.Request
return return
} }
registryURL, upstreamName, _, ok := h.registryForName(name) h.proxy.Logger.Info("container manifest request", "name", name, "reference", reference)
if !ok {
h.containerError(w, http.StatusNotFound, "NAME_UNKNOWN", "unknown upstream registry") // Get auth token
token, err := h.getAuthToken(r.Context(), name, "pull")
if err != nil {
h.proxy.Logger.Error("failed to get auth token", "error", err)
h.containerError(w, http.StatusUnauthorized, "UNAUTHORIZED", "failed to authenticate")
return return
} }
h.proxy.Logger.Info("container manifest request", "name", upstreamName, "reference", reference) // Proxy to upstream
h.serveManifest(w, r, registryURL, upstreamName, reference) upstreamURL := fmt.Sprintf("%s/v2/%s/manifests/%s", h.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
}
req.Header.Set("Authorization", "Bearer "+token)
// Forward Accept header for content negotiation
if accept := r.Header.Get("Accept"); accept != "" {
req.Header.Set("Accept", accept)
} else {
// Default accept headers for manifests
req.Header.Set("Accept", strings.Join([]string{
"application/vnd.oci.image.manifest.v1+json",
"application/vnd.oci.image.index.v1+json",
"application/vnd.docker.distribution.manifest.v2+json",
"application/vnd.docker.distribution.manifest.list.v2+json",
"application/vnd.docker.distribution.manifest.v1+prettyjws",
}, ", "))
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
h.proxy.Logger.Error("failed to fetch manifest", "error", err)
h.containerError(w, http.StatusBadGateway, "INTERNAL_ERROR", "failed to fetch from upstream")
return
}
defer func() { _ = resp.Body.Close() }()
// Copy relevant headers
for _, header := range []string{"Content-Type", "Content-Length", "Docker-Content-Digest", "ETag"} {
if v := resp.Header.Get(header); v != "" {
w.Header().Set(header, v)
}
}
w.WriteHeader(resp.StatusCode)
_, _ = io.Copy(w, resp.Body)
} }
// handleTagsList proxies tag list requests to upstream. // handleTagsList proxies tag list requests to upstream.
@ -195,13 +204,14 @@ func (h *ContainerHandler) handleTagsList(w http.ResponseWriter, r *http.Request
return return
} }
registryURL, upstreamName, _, ok := h.registryForName(name) // Get auth token
if !ok { token, err := h.getAuthToken(r.Context(), name, "pull")
h.containerError(w, http.StatusNotFound, "NAME_UNKNOWN", "unknown upstream registry") if err != nil {
h.containerError(w, http.StatusUnauthorized, "UNAUTHORIZED", "failed to authenticate")
return return
} }
upstreamURL := fmt.Sprintf("%s/v2/%s/tags/list", registryURL, upstreamName) upstreamURL := fmt.Sprintf("%s/v2/%s/tags/list", h.registryURL, name)
if r.URL.RawQuery != "" { if r.URL.RawQuery != "" {
upstreamURL += "?" + r.URL.RawQuery upstreamURL += "?" + r.URL.RawQuery
} }
@ -212,7 +222,9 @@ func (h *ContainerHandler) handleTagsList(w http.ResponseWriter, r *http.Request
return return
} }
resp, err := h.proxy.HTTPClient.Do(req) req.Header.Set("Authorization", "Bearer "+token)
resp, err := http.DefaultClient.Do(req)
if err != nil { if err != nil {
h.containerError(w, http.StatusBadGateway, "INTERNAL_ERROR", "failed to fetch from upstream") h.containerError(w, http.StatusBadGateway, "INTERNAL_ERROR", "failed to fetch from upstream")
return return
@ -224,9 +236,46 @@ func (h *ContainerHandler) handleTagsList(w http.ResponseWriter, r *http.Request
_, _ = io.Copy(w, resp.Body) _, _ = io.Copy(w, resp.Body)
} }
// getAuthToken gets a bearer token for the specified repository.
// Docker Hub requires auth even for public images.
func (h *ContainerHandler) getAuthToken(_ interface{ Done() <-chan struct{} }, repository, action string) (string, error) {
// For Docker Hub: https://auth.docker.io/token?service=registry.docker.io&scope=repository:{repo}:pull
authURL := fmt.Sprintf("%s/token?service=registry.docker.io&scope=repository:%s:%s",
h.authURL, repository, action)
req, err := http.NewRequest(http.MethodGet, authURL, nil)
if err != nil {
return "", err
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return "", err
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != http.StatusOK {
return "", fmt.Errorf("auth failed with status %d", resp.StatusCode)
}
var tokenResp struct {
Token string `json:"token"`
AccessToken string `json:"access_token"`
}
if err := json.NewDecoder(resp.Body).Decode(&tokenResp); err != nil {
return "", err
}
if tokenResp.Token != "" {
return tokenResp.Token, nil
}
return tokenResp.AccessToken, nil
}
// proxyBlobHead handles HEAD requests for blobs. // proxyBlobHead handles HEAD requests for blobs.
func (h *ContainerHandler) proxyBlobHead(w http.ResponseWriter, r *http.Request, registryURL, name, digest string) { func (h *ContainerHandler) proxyBlobHead(w http.ResponseWriter, r *http.Request, name, digest, token string) {
upstreamURL := fmt.Sprintf("%s/v2/%s/blobs/%s", registryURL, name, digest) upstreamURL := fmt.Sprintf("%s/v2/%s/blobs/%s", h.registryURL, name, digest)
req, err := http.NewRequestWithContext(r.Context(), http.MethodHead, upstreamURL, nil) req, err := http.NewRequestWithContext(r.Context(), http.MethodHead, upstreamURL, nil)
if err != nil { if err != nil {
@ -234,7 +283,9 @@ func (h *ContainerHandler) proxyBlobHead(w http.ResponseWriter, r *http.Request,
return return
} }
resp, err := h.proxy.HTTPClient.Do(req) req.Header.Set("Authorization", "Bearer "+token)
resp, err := http.DefaultClient.Do(req)
if err != nil { if err != nil {
h.containerError(w, http.StatusBadGateway, "INTERNAL_ERROR", "failed to fetch from upstream") h.containerError(w, http.StatusBadGateway, "INTERNAL_ERROR", "failed to fetch from upstream")
return return
@ -250,22 +301,33 @@ func (h *ContainerHandler) proxyBlobHead(w http.ResponseWriter, r *http.Request,
w.WriteHeader(resp.StatusCode) w.WriteHeader(resp.StatusCode)
} }
// registryForName resolves a client-visible OCI repository name to an upstream // proxyBlobWithAuth proxies a blob download with authentication.
// registry and its repository name. Named upstreams use upstream/{name}/ as a func (h *ContainerHandler) proxyBlobWithAuth(w http.ResponseWriter, r *http.Request, name, digest, token string) {
// reserved prefix; all other names continue to target Docker Hub. upstreamURL := fmt.Sprintf("%s/v2/%s/blobs/%s", h.registryURL, name, digest)
func (h *ContainerHandler) registryForName(name string) (registryURL, upstreamName, cacheName string, ok bool) {
parts := strings.SplitN(name, "/", registrySelectorParts) req, err := http.NewRequestWithContext(r.Context(), http.MethodGet, upstreamURL, nil)
if len(parts) >= 2 && parts[0] == "upstream" { if err != nil {
if len(parts) != registrySelectorParts || parts[2] == "" { h.containerError(w, http.StatusInternalServerError, "INTERNAL_ERROR", "failed to create request")
return "", "", "", false return
}
registryURL, ok = h.namedRegistries[parts[1]]
if !ok || registryURL == "" {
return "", "", "", false
}
return registryURL, parts[2], name, true
} }
return h.registryURL, name, name, true
req.Header.Set("Authorization", "Bearer "+token)
resp, err := http.DefaultClient.Do(req)
if err != nil {
h.containerError(w, http.StatusBadGateway, "INTERNAL_ERROR", "failed to fetch from upstream")
return
}
defer func() { _ = resp.Body.Close() }()
for _, header := range []string{"Content-Type", "Content-Length", "Docker-Content-Digest"} {
if v := resp.Header.Get(header); v != "" {
w.Header().Set(header, v)
}
}
w.WriteHeader(resp.StatusCode)
_, _ = io.Copy(w, resp.Body)
} }
// containerError writes an OCI-compliant error response. // containerError writes an OCI-compliant error response.
@ -285,7 +347,7 @@ var blobPathPattern = regexp.MustCompile(`^(.+)/blobs/(sha256:[a-f0-9]+)$`)
// parseBlobPath extracts repository name and digest from a blob path. // parseBlobPath extracts repository name and digest from a blob path.
func (h *ContainerHandler) parseBlobPath(path string) (name, digest string) { func (h *ContainerHandler) parseBlobPath(path string) (name, digest string) {
matches := blobPathPattern.FindStringSubmatch(path) matches := blobPathPattern.FindStringSubmatch(path)
if len(matches) != blobMatchCount { if len(matches) != 3 {
return "", "" return "", ""
} }
return matches[1], matches[2] return matches[1], matches[2]
@ -297,7 +359,7 @@ var manifestPathPattern = regexp.MustCompile(`^(.+)/manifests/(.+)$`)
// parseManifestPath extracts repository name and reference from a manifest path. // parseManifestPath extracts repository name and reference from a manifest path.
func (h *ContainerHandler) parseManifestPath(path string) (name, reference string) { func (h *ContainerHandler) parseManifestPath(path string) (name, reference string) {
matches := manifestPathPattern.FindStringSubmatch(path) matches := manifestPathPattern.FindStringSubmatch(path)
if len(matches) != manifestMatchCount { if len(matches) != 3 {
return "", "" return "", ""
} }
return matches[1], matches[2] return matches[1], matches[2]
@ -309,7 +371,7 @@ var tagsListPathPattern = regexp.MustCompile(`^(.+)/tags/list$`)
// parseTagsListPath extracts repository name from a tags list path. // parseTagsListPath extracts repository name from a tags list path.
func (h *ContainerHandler) parseTagsListPath(path string) string { func (h *ContainerHandler) parseTagsListPath(path string) string {
matches := tagsListPathPattern.FindStringSubmatch(path) matches := tagsListPathPattern.FindStringSubmatch(path)
if len(matches) != tagsListMatchCount { if len(matches) != 2 {
return "" return ""
} }
return matches[1] return matches[1]

View file

@ -1,251 +0,0 @@
package handler
import (
"bytes"
"context"
"crypto/sha256"
"database/sql"
"encoding/hex"
"fmt"
"io"
"net/http"
"regexp"
"strconv"
"strings"
"time"
"github.com/git-pkgs/proxy/internal/database"
)
const (
containerManifestCacheEcosystem = "oci-manifest"
containerStaleWarning = `110 - "Response is Stale"`
)
var manifestDigestReferencePattern = regexp.MustCompile(`^[a-z0-9]+:[a-f0-9]+$`)
type cachedContainerManifest struct {
body []byte
contentType string
contentDigest string
etag string
size int64
fetchedAt time.Time
}
func (h *ContainerHandler) serveManifest(w http.ResponseWriter, r *http.Request, registryURL, name, reference string) {
accept := containerManifestAccept(r)
cacheKey := h.containerManifestCacheKey(registryURL, name, reference, accept)
cached, err := h.loadContainerManifest(r.Context(), cacheKey)
if err != nil {
h.proxy.Logger.Warn("failed to read cached container manifest", "error", err)
cached = nil
}
immutable := manifestDigestReferencePattern.MatchString(reference)
if cached != nil && (immutable || h.containerManifestFresh(cached)) {
writeContainerManifest(w, r.Method, 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
}
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, cached, err)
return
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode == http.StatusNotModified && cached != nil {
cached.fetchedAt = time.Now()
if err := h.storeContainerManifest(r.Context(), cacheKey, cached); err != nil {
h.proxy.Logger.Warn("failed to refresh cached container manifest", "error", err)
}
writeContainerManifest(w, r.Method, cached, false)
return
}
if resp.StatusCode != http.StatusOK {
if cached != nil && shouldServeStaleManifest(resp.StatusCode) {
writeContainerManifest(w, r.Method, cached, true)
return
}
copyContainerManifestHeaders(w.Header(), resp.Header)
w.WriteHeader(resp.StatusCode)
_, _ = io.Copy(w, resp.Body)
return
}
if r.Method == http.MethodHead {
copyContainerManifestHeaders(w.Header(), resp.Header)
w.WriteHeader(http.StatusOK)
return
}
body, err := h.proxy.ReadMetadata(resp.Body)
if err != nil {
h.serveStaleManifestOrError(w, r, cached, fmt.Errorf("reading manifest: %w", err))
return
}
manifest := &cachedContainerManifest{
body: body,
contentType: resp.Header.Get("Content-Type"),
contentDigest: resp.Header.Get("Docker-Content-Digest"),
etag: resp.Header.Get("ETag"),
size: int64(len(body)),
fetchedAt: time.Now(),
}
if manifest.contentDigest == "" {
manifest.contentDigest = sha256Digest(body)
}
if err := h.storeContainerManifest(r.Context(), cacheKey, manifest); err != nil {
h.proxy.Logger.Warn("failed to cache container manifest", "error", err)
}
if manifest.contentDigest != reference && manifestDigestReferencePattern.MatchString(manifest.contentDigest) {
digestKey := h.containerManifestCacheKey(registryURL, name, manifest.contentDigest, accept)
if err := h.storeContainerManifest(r.Context(), digestKey, manifest); err != nil {
h.proxy.Logger.Warn("failed to cache container manifest by digest", "error", err)
}
}
writeContainerManifest(w, r.Method, manifest, false)
}
func (h *ContainerHandler) serveStaleManifestOrError(w http.ResponseWriter, r *http.Request, cached *cachedContainerManifest, err error) {
if cached != nil {
h.proxy.Logger.Warn("upstream manifest fetch failed, serving stale cache", "error", err)
writeContainerManifest(w, r.Method, cached, true)
return
}
h.proxy.Logger.Error("failed to fetch manifest", "error", err)
h.containerError(w, http.StatusBadGateway, "INTERNAL_ERROR", "failed to fetch from upstream")
}
func (h *ContainerHandler) containerManifestFresh(manifest *cachedContainerManifest) bool {
return h.proxy.MetadataTTL > 0 && !manifest.fetchedAt.IsZero() && time.Since(manifest.fetchedAt) < h.proxy.MetadataTTL
}
func (h *ContainerHandler) containerManifestCacheKey(registryURL, name, reference, accept string) string {
identity := strings.Join([]string{registryURL, name, reference, accept}, "\x00")
sum := sha256.Sum256([]byte(identity))
return hex.EncodeToString(sum[:])
}
func (h *ContainerHandler) loadContainerManifest(ctx context.Context, cacheKey string) (*cachedContainerManifest, error) {
if h.proxy.DB == nil || h.proxy.Storage == nil {
return nil, nil
}
entry, err := h.proxy.DB.GetMetadataCache(containerManifestCacheEcosystem, cacheKey)
if err != nil || entry == nil {
return nil, err
}
reader, err := h.proxy.Storage.Open(ctx, entry.StoragePath)
if err != nil {
return nil, nil
}
defer func() { _ = reader.Close() }()
body, err := h.proxy.ReadMetadata(reader)
if err != nil {
return nil, err
}
manifest := &cachedContainerManifest{body: body, size: int64(len(body))}
if entry.ContentType.Valid {
manifest.contentType = entry.ContentType.String
}
if entry.ContentDigest.Valid {
manifest.contentDigest = entry.ContentDigest.String
} else {
manifest.contentDigest = sha256Digest(body)
}
if entry.ETag.Valid {
manifest.etag = entry.ETag.String
}
if entry.Size.Valid {
manifest.size = entry.Size.Int64
}
if entry.FetchedAt.Valid {
manifest.fetchedAt = entry.FetchedAt.Time
}
return manifest, nil
}
func (h *ContainerHandler) storeContainerManifest(ctx context.Context, cacheKey string, manifest *cachedContainerManifest) error {
if h.proxy.DB == nil || h.proxy.Storage == nil {
return nil
}
storagePath := metadataStoragePath(containerManifestCacheEcosystem, cacheKey)
size, _, err := h.proxy.Storage.Store(ctx, storagePath, bytes.NewReader(manifest.body))
if err != nil {
return fmt.Errorf("storing manifest: %w", err)
}
manifest.size = size
return h.proxy.DB.UpsertMetadataCache(&database.MetadataCacheEntry{
Ecosystem: containerManifestCacheEcosystem,
Name: cacheKey,
StoragePath: storagePath,
ETag: sql.NullString{String: manifest.etag, Valid: manifest.etag != ""},
ContentType: sql.NullString{String: manifest.contentType, Valid: manifest.contentType != ""},
ContentDigest: sql.NullString{String: manifest.contentDigest, Valid: manifest.contentDigest != ""},
Size: sql.NullInt64{Int64: size, Valid: true},
FetchedAt: sql.NullTime{Time: manifest.fetchedAt, Valid: !manifest.fetchedAt.IsZero()},
})
}
func writeContainerManifest(w http.ResponseWriter, method string, manifest *cachedContainerManifest, stale bool) {
if manifest.contentType != "" {
w.Header().Set("Content-Type", manifest.contentType)
}
w.Header().Set("Content-Length", strconv.FormatInt(manifest.size, 10))
if manifest.contentDigest != "" {
w.Header().Set("Docker-Content-Digest", manifest.contentDigest)
}
if manifest.etag != "" {
w.Header().Set("ETag", manifest.etag)
}
if stale {
w.Header().Set("Warning", containerStaleWarning)
}
w.WriteHeader(http.StatusOK)
if method != http.MethodHead {
_, _ = w.Write(manifest.body)
}
}
func containerManifestAccept(r *http.Request) string {
if accept := r.Header.Get("Accept"); accept != "" {
return accept
}
return strings.Join([]string{
"application/vnd.oci.image.manifest.v1+json",
"application/vnd.oci.image.index.v1+json",
"application/vnd.docker.distribution.manifest.v2+json",
"application/vnd.docker.distribution.manifest.list.v2+json",
"application/vnd.docker.distribution.manifest.v1+prettyjws",
}, ", ")
}
func copyContainerManifestHeaders(destination, source http.Header) {
for _, header := range []string{"Content-Type", "Content-Length", "Docker-Content-Digest", "ETag", "WWW-Authenticate"} {
if value := source.Get(header); value != "" {
destination.Set(header, value)
}
}
}
func shouldServeStaleManifest(status int) bool {
return status == http.StatusTooManyRequests || status >= http.StatusInternalServerError
}
func sha256Digest(body []byte) string {
digest := sha256.Sum256(body)
return "sha256:" + hex.EncodeToString(digest[:])
}

View file

@ -1,16 +1,9 @@
package handler package handler
import ( import (
"encoding/json"
"io"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
"strconv"
"testing" "testing"
"time"
upstreamhttp "github.com/git-pkgs/proxy/internal/httpclient"
"github.com/git-pkgs/registries/fetch"
) )
func TestContainerHandler_parseBlobPath(t *testing.T) { func TestContainerHandler_parseBlobPath(t *testing.T) {
@ -85,8 +78,8 @@ func TestContainerHandler_parseManifestPath(t *testing.T) {
wantReference: "sha256:abc123", wantReference: "sha256:abc123",
}, },
{ {
path: "invalid/path", path: "invalid/path",
wantName: "", wantName: "",
}, },
} }
@ -134,570 +127,6 @@ func TestContainerHandler_parseTagsListPath(t *testing.T) {
} }
} }
func TestContainerHandler_NamedOCIRegistryServesHelmArtifacts(t *testing.T) {
digest := "sha256:abc123def456abc123def456abc123def456abc123def456abc123def456abcd"
manifest := `{"schemaVersion":2,"config":{"mediaType":"application/vnd.cncf.helm.config.v1+json"},"layers":[{"mediaType":"application/vnd.cncf.helm.chart.content.v1.tar+gzip","digest":"` + digest + `"}]}`
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/v2/owner/demo/manifests/1.0.0":
w.Header().Set("Content-Type", "application/vnd.oci.image.manifest.v1+json")
w.Header().Set("Docker-Content-Digest", digest)
_, _ = io.WriteString(w, manifest)
case "/v2/owner/demo/blobs/" + digest:
w.Header().Set("Content-Type", "application/vnd.cncf.helm.chart.content.v1.tar+gzip")
_, _ = io.WriteString(w, "chart archive")
default:
http.NotFound(w, r)
}
}))
defer 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 := NewContainerHandler(proxy, "http://proxy.example", map[string]string{"ghcr": upstream.URL})
manifestResponse := httptest.NewRecorder()
h.Routes().ServeHTTP(manifestResponse,
httptest.NewRequest(http.MethodGet, "/upstream/ghcr/owner/demo/manifests/1.0.0", nil))
if manifestResponse.Code != http.StatusOK {
t.Fatalf("manifest status = %d, want 200: %s", manifestResponse.Code, manifestResponse.Body.String())
}
if got := manifestResponse.Header().Get("Content-Type"); got != "application/vnd.oci.image.manifest.v1+json" {
t.Errorf("manifest Content-Type = %q", got)
}
blobResponse := httptest.NewRecorder()
h.Routes().ServeHTTP(blobResponse,
httptest.NewRequest(http.MethodGet, "/upstream/ghcr/owner/demo/blobs/"+digest, nil))
if blobResponse.Code != http.StatusOK {
t.Fatalf("blob status = %d, want 200: %s", blobResponse.Code, blobResponse.Body.String())
}
if got := blobResponse.Header().Get("Content-Type"); got != "application/vnd.cncf.helm.chart.content.v1.tar+gzip" {
t.Errorf("blob Content-Type = %q", got)
}
}
func TestContainerHandler_BlobDownload_DiscoversBearerChallenge(t *testing.T) {
digest := "sha256:abc123def456abc123def456abc123def456abc123def456abc123def456abcd"
registryRequests := 0
tokenRequests := 0
var upstream *httptest.Server
upstream = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/token":
tokenRequests++
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]any{
"token": "discovered-token",
"expires_in": 3600,
})
case "/v2/library/nginx/blobs/" + digest:
registryRequests++
if r.Header.Get("Authorization") != "Bearer discovered-token" {
w.Header().Set("WWW-Authenticate", `Bearer realm="`+upstream.URL+`/token",service="registry.test",scope="repository:library/nginx:pull"`)
http.Error(w, "authentication required", http.StatusUnauthorized)
return
}
w.Header().Set("Content-Type", "application/octet-stream")
_, _ = io.WriteString(w, "upstream blob")
default:
http.NotFound(w, r)
}
}))
defer upstream.Close()
proxy, _, _, _ := setupTestProxy(t)
authTransport := upstreamhttp.NewTransport(http.DefaultTransport, nil)
client := &http.Client{Transport: authTransport}
artifactFetcher := fetch.NewFetcher(
fetch.WithHTTPClient(client),
fetch.WithMaxRetries(0),
)
t.Cleanup(func() { _ = artifactFetcher.Close() })
proxy.Fetcher = artifactFetcher
proxy.HTTPClient = client
h := &ContainerHandler{
proxy: proxy,
registryURL: upstream.URL,
proxyURL: "http://localhost:8080",
}
for range 2 {
req := httptest.NewRequest(http.MethodGet, "/library/nginx/blobs/"+digest, nil)
w := httptest.NewRecorder()
h.Routes().ServeHTTP(w, req)
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 != "upstream blob" {
t.Errorf("body = %q, want %q", got, "upstream blob")
}
}
if tokenRequests != 1 {
t.Errorf("token requests = %d, want 1", tokenRequests)
}
if registryRequests != 2 {
t.Errorf("registry requests = %d, want 2", registryRequests)
}
}
func TestContainerHandler_CachedImagePullSurvivesRegistryAndTokenOutages(t *testing.T) {
digest := "sha256:abc123def456abc123def456abc123def456abc123def456abc123def456abcd"
manifest := `{"schemaVersion":2,"mediaType":"application/vnd.oci.image.manifest.v1+json"}`
blob := "cached image blob"
registryAvailable := true
tokenAvailable := true
registryRequests := 0
tokenRequests := 0
tokenServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
tokenRequests++
if !tokenAvailable {
http.Error(w, "token service unavailable", http.StatusServiceUnavailable)
return
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]any{
"token": "discovered-token",
"expires_in": 3600,
})
}))
defer tokenServer.Close()
registryServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
registryRequests++
if !registryAvailable {
http.Error(w, "registry unavailable", http.StatusServiceUnavailable)
return
}
if r.Header.Get("Authorization") != "Bearer discovered-token" {
w.Header().Set("WWW-Authenticate", `Bearer realm="`+tokenServer.URL+`",service="registry.test",scope="repository:library/nginx:pull"`)
http.Error(w, "authentication required", http.StatusUnauthorized)
return
}
switch r.URL.Path {
case "/v2/library/nginx/manifests/latest":
w.Header().Set("Content-Type", "application/vnd.oci.image.manifest.v1+json")
w.Header().Set("Docker-Content-Digest", digest)
_, _ = io.WriteString(w, manifest)
case "/v2/library/nginx/blobs/" + digest:
w.Header().Set("Content-Type", "application/octet-stream")
_, _ = io.WriteString(w, blob)
default:
http.NotFound(w, r)
}
}))
defer registryServer.Close()
warmProxy, db, store, _ := setupTestProxy(t)
warmClient := &http.Client{Transport: upstreamhttp.NewTransport(http.DefaultTransport, nil)}
warmFetcher := fetch.NewFetcher(
fetch.WithHTTPClient(warmClient),
fetch.WithMaxRetries(0),
)
t.Cleanup(func() { _ = warmFetcher.Close() })
warmProxy.Fetcher = warmFetcher
warmProxy.HTTPClient = warmClient
warmProxy.MetadataTTL = time.Hour
warmHandler := (&ContainerHandler{
proxy: warmProxy,
registryURL: registryServer.URL,
proxyURL: "http://localhost:8080",
}).Routes()
for _, request := range []struct {
path string
body string
}{
{path: "/library/nginx/manifests/latest", body: manifest},
{path: "/library/nginx/blobs/" + digest, body: blob},
} {
response := httptest.NewRecorder()
warmHandler.ServeHTTP(response, httptest.NewRequest(http.MethodGet, request.path, nil))
if response.Code != http.StatusOK {
t.Fatalf("warming %s: status = %d, want %d; body: %s", request.path, response.Code, http.StatusOK, response.Body.String())
}
if got := response.Body.String(); got != request.body {
t.Fatalf("warming %s: body = %q, want %q", request.path, got, request.body)
}
}
warmRegistryRequests := registryRequests
warmTokenRequests := tokenRequests
registryAvailable = false
tokenAvailable = false
offlineClient := &http.Client{Transport: upstreamhttp.NewTransport(http.DefaultTransport, nil)}
offlineFetcher := fetch.NewFetcher(
fetch.WithHTTPClient(offlineClient),
fetch.WithMaxRetries(0),
)
t.Cleanup(func() { _ = offlineFetcher.Close() })
offlineProxy := NewProxy(db, store, offlineFetcher, fetch.NewResolver(), warmProxy.Logger)
offlineProxy.HTTPClient = offlineClient
offlineProxy.MetadataTTL = time.Hour
offlineHandler := (&ContainerHandler{
proxy: offlineProxy,
registryURL: registryServer.URL,
proxyURL: "http://localhost:8080",
}).Routes()
for _, request := range []struct {
name string
path string
body string
}{
{name: "tag manifest", path: "/library/nginx/manifests/latest", body: manifest},
{name: "digest manifest", path: "/library/nginx/manifests/" + digest, body: manifest},
{name: "blob", path: "/library/nginx/blobs/" + digest, body: blob},
} {
t.Run(request.name, func(t *testing.T) {
response := httptest.NewRecorder()
offlineHandler.ServeHTTP(response, httptest.NewRequest(http.MethodGet, request.path, nil))
if response.Code != http.StatusOK {
t.Fatalf("status = %d, want %d; body: %s", response.Code, http.StatusOK, response.Body.String())
}
if got := response.Body.String(); got != request.body {
t.Errorf("body = %q, want %q", got, request.body)
}
if got := response.Header().Get("Docker-Content-Digest"); got != digest {
t.Errorf("Docker-Content-Digest = %q, want %q", got, digest)
}
})
}
if registryRequests != warmRegistryRequests {
t.Errorf("offline registry requests = %d, want 0", registryRequests-warmRegistryRequests)
}
if tokenRequests != warmTokenRequests {
t.Errorf("offline token requests = %d, want 0", tokenRequests-warmTokenRequests)
}
}
func TestContainerHandler_BlobDownload_CacheHitSkipsAuth(t *testing.T) {
proxy, db, store, fetcher := setupTestProxy(t)
digest := "sha256:abc123def456abc123def456abc123def456abc123def456abc123def456abcd"
seedPackage(t, db, store, "oci", "library/nginx", digest, digest, "cached blob")
upstreamRequests := 0
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
upstreamRequests++
http.Error(w, "upstream unavailable", http.StatusServiceUnavailable)
}))
defer upstream.Close()
h := &ContainerHandler{
proxy: proxy,
registryURL: upstream.URL,
proxyURL: "http://localhost:8080",
}
req := httptest.NewRequest(http.MethodGet, "/library/nginx/blobs/"+digest, nil)
w := httptest.NewRecorder()
h.Routes().ServeHTTP(w, req)
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 != "cached blob" {
t.Errorf("body = %q, want %q", got, "cached blob")
}
if upstreamRequests != 0 {
t.Errorf("upstream requests = %d, want 0", upstreamRequests)
}
if fetcher.fetchCalled {
t.Error("fetcher should not be called on cache hit")
}
}
func TestContainerHandler_BlobHead_CacheHitSkipsUpstreamAndAuth(t *testing.T) {
proxy, db, store, fetcher := setupTestProxy(t)
digest := "sha256:abc123def456abc123def456abc123def456abc123def456abc123def456abcd"
seedPackage(t, db, store, "oci", "library/nginx", digest, digest, "cached blob")
upstreamRequests := 0
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
upstreamRequests++
http.Error(w, "upstream unavailable", http.StatusServiceUnavailable)
}))
defer upstream.Close()
proxy.HTTPClient = upstream.Client()
h := &ContainerHandler{
proxy: proxy,
registryURL: upstream.URL,
proxyURL: "http://localhost:8080",
}
req := httptest.NewRequest(http.MethodHead, "/library/nginx/blobs/"+digest, nil)
w := httptest.NewRecorder()
h.Routes().ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("status = %d, want %d; body: %s", w.Code, http.StatusOK, w.Body.String())
}
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")
}
if w.Body.Len() != 0 {
t.Errorf("HEAD response body length = %d, want 0", w.Body.Len())
}
if upstreamRequests != 0 {
t.Errorf("upstream requests = %d, want 0", upstreamRequests)
}
if fetcher.fetchCalled {
t.Error("fetcher should not be called on cache hit")
}
}
func TestContainerHandler_BlobHead_DirectServeRedirects(t *testing.T) {
proxy, db, store, fetcher := setupTestProxy(t)
digest := "sha256:abc123def456abc123def456abc123def456abc123def456abc123def456abcd"
seedPackage(t, db, store, "oci", "library/nginx", digest, digest, "cached blob")
store.signedURL = "https://storage.example.test/cached-blob?signature=test"
proxy.DirectServe = true
h := &ContainerHandler{
proxy: proxy,
registryURL: "https://registry.example.test",
proxyURL: "http://localhost:8080",
}
req := httptest.NewRequest(http.MethodHead, "/library/nginx/blobs/"+digest, nil)
w := httptest.NewRecorder()
h.Routes().ServeHTTP(w, req)
if w.Code != http.StatusFound {
t.Fatalf("status = %d, want %d", w.Code, http.StatusFound)
}
if got := w.Header().Get("Location"); got != store.signedURL {
t.Errorf("Location = %q, want %q", got, store.signedURL)
}
wantETag := `"` + sha256Hex("cached blob") + `"`
if got := w.Header().Get("ETag"); got != wantETag {
t.Errorf("ETag = %q, want %q", got, wantETag)
}
if w.Body.Len() != 0 {
t.Errorf("HEAD response body length = %d, want 0", w.Body.Len())
}
if fetcher.fetchCalled {
t.Error("fetcher should not be called on cache hit")
}
}
func TestContainerHandler_ManifestByDigest_CacheHitSkipsUpstream(t *testing.T) {
digest := "sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
manifest := `{"schemaVersion":2,"mediaType":"application/vnd.oci.image.manifest.v1+json"}`
upstreamAvailable := true
upstreamRequests := 0
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
upstreamRequests++
if !upstreamAvailable {
http.Error(w, "upstream unavailable", http.StatusServiceUnavailable)
return
}
if r.URL.Path != "/v2/library/nginx/manifests/"+digest {
http.NotFound(w, r)
return
}
w.Header().Set("Content-Type", "application/vnd.oci.image.manifest.v1+json")
w.Header().Set("Docker-Content-Digest", digest)
w.Header().Set("ETag", `"manifest-etag"`)
if r.Method != http.MethodHead {
_, _ = io.WriteString(w, manifest)
}
}))
defer upstream.Close()
proxy, _, _, _ := setupTestProxy(t)
proxy.HTTPClient = upstream.Client()
h := &ContainerHandler{proxy: proxy, registryURL: upstream.URL, proxyURL: "http://localhost:8080"}
first := httptest.NewRecorder()
h.Routes().ServeHTTP(first, httptest.NewRequest(http.MethodGet, "/library/nginx/manifests/"+digest, nil))
if first.Code != http.StatusOK {
t.Fatalf("initial status = %d, want %d; body: %s", first.Code, http.StatusOK, first.Body.String())
}
if first.Body.String() != manifest {
t.Fatalf("initial body = %q, want %q", first.Body.String(), manifest)
}
upstreamAvailable = false
second := httptest.NewRecorder()
h.Routes().ServeHTTP(second, httptest.NewRequest(http.MethodGet, "/library/nginx/manifests/"+digest, nil))
if second.Code != http.StatusOK {
t.Fatalf("cached status = %d, want %d; body: %s", second.Code, http.StatusOK, second.Body.String())
}
if second.Body.String() != manifest {
t.Errorf("cached body = %q, want %q", second.Body.String(), manifest)
}
if got := second.Header().Get("Docker-Content-Digest"); got != digest {
t.Errorf("cached Docker-Content-Digest = %q, want %q", got, digest)
}
head := httptest.NewRecorder()
h.Routes().ServeHTTP(head, httptest.NewRequest(http.MethodHead, "/library/nginx/manifests/"+digest, nil))
if head.Code != http.StatusOK {
t.Fatalf("cached HEAD status = %d, want %d", head.Code, http.StatusOK)
}
wantLength := strconv.Itoa(len(manifest))
if got := head.Header().Get("Content-Length"); got != wantLength {
t.Errorf("cached HEAD Content-Length = %q, want %q", got, wantLength)
}
if head.Body.Len() != 0 {
t.Errorf("cached HEAD body length = %d, want 0", head.Body.Len())
}
if upstreamRequests != 1 {
t.Errorf("upstream requests = %d, want 1", upstreamRequests)
}
}
func TestContainerHandler_ManifestByTag_UsesStaleCacheOnUpstreamFailure(t *testing.T) {
digest := "sha256:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"
manifest := `{"schemaVersion":2,"mediaType":"application/vnd.oci.image.index.v1+json"}`
upstreamAvailable := true
upstreamRequests := 0
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
upstreamRequests++
if !upstreamAvailable {
http.Error(w, "upstream unavailable", http.StatusServiceUnavailable)
return
}
w.Header().Set("Content-Type", "application/vnd.oci.image.index.v1+json")
w.Header().Set("Docker-Content-Digest", digest)
_, _ = io.WriteString(w, manifest)
}))
defer upstream.Close()
proxy, _, _, _ := setupTestProxy(t)
proxy.HTTPClient = upstream.Client()
proxy.MetadataTTL = 0
h := &ContainerHandler{proxy: proxy, registryURL: upstream.URL, proxyURL: "http://localhost:8080"}
first := httptest.NewRecorder()
h.Routes().ServeHTTP(first, httptest.NewRequest(http.MethodGet, "/library/nginx/manifests/latest", nil))
if first.Code != http.StatusOK {
t.Fatalf("initial status = %d, want %d; body: %s", first.Code, http.StatusOK, first.Body.String())
}
upstreamAvailable = false
second := httptest.NewRecorder()
h.Routes().ServeHTTP(second, httptest.NewRequest(http.MethodGet, "/library/nginx/manifests/latest", nil))
if second.Code != http.StatusOK {
t.Fatalf("stale status = %d, want %d; body: %s", second.Code, http.StatusOK, second.Body.String())
}
if second.Body.String() != manifest {
t.Errorf("stale body = %q, want %q", second.Body.String(), manifest)
}
if got := second.Header().Get("Warning"); got != `110 - "Response is Stale"` {
t.Errorf("Warning = %q, want stale warning", got)
}
if got := second.Header().Get("Docker-Content-Digest"); got != digest {
t.Errorf("stale Docker-Content-Digest = %q, want %q", got, digest)
}
if upstreamRequests != 2 {
t.Errorf("upstream requests = %d, want 2", upstreamRequests)
}
}
func TestContainerHandler_ManifestByTag_CachesDigestAlias(t *testing.T) {
digest := "sha256:cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"
manifest := `{"schemaVersion":2,"mediaType":"application/vnd.oci.image.manifest.v1+json"}`
upstreamAvailable := true
upstreamRequests := 0
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
upstreamRequests++
if !upstreamAvailable {
http.Error(w, "upstream unavailable", http.StatusServiceUnavailable)
return
}
if r.URL.Path != "/v2/library/nginx/manifests/latest" {
http.NotFound(w, r)
return
}
w.Header().Set("Content-Type", "application/vnd.oci.image.manifest.v1+json")
w.Header().Set("Docker-Content-Digest", digest)
_, _ = io.WriteString(w, manifest)
}))
defer upstream.Close()
proxy, _, _, _ := setupTestProxy(t)
proxy.HTTPClient = upstream.Client()
h := &ContainerHandler{proxy: proxy, registryURL: upstream.URL, proxyURL: "http://localhost:8080"}
first := httptest.NewRecorder()
h.Routes().ServeHTTP(first, httptest.NewRequest(http.MethodGet, "/library/nginx/manifests/latest", nil))
if first.Code != http.StatusOK {
t.Fatalf("tag status = %d, want %d; body: %s", first.Code, http.StatusOK, first.Body.String())
}
upstreamAvailable = false
byDigest := httptest.NewRecorder()
h.Routes().ServeHTTP(byDigest, httptest.NewRequest(http.MethodGet, "/library/nginx/manifests/"+digest, nil))
if byDigest.Code != http.StatusOK {
t.Fatalf("digest status = %d, want %d; body: %s", byDigest.Code, http.StatusOK, byDigest.Body.String())
}
if byDigest.Body.String() != manifest {
t.Errorf("digest body = %q, want %q", byDigest.Body.String(), manifest)
}
if got := byDigest.Header().Get("Docker-Content-Digest"); got != digest {
t.Errorf("Docker-Content-Digest = %q, want %q", got, digest)
}
if upstreamRequests != 1 {
t.Errorf("upstream requests = %d, want 1", upstreamRequests)
}
}
func TestContainerHandler_ManifestByTag_StaleHeadChecksUpstream(t *testing.T) {
oldDigest := "sha256:dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd"
newDigest := "sha256:eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"
currentDigest := oldDigest
upstreamRequests := 0
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
upstreamRequests++
w.Header().Set("Content-Type", "application/vnd.oci.image.manifest.v1+json")
w.Header().Set("Docker-Content-Digest", currentDigest)
w.Header().Set("ETag", `"`+currentDigest+`"`)
if r.Method != http.MethodHead {
_, _ = io.WriteString(w, `{"schemaVersion":2}`)
}
}))
defer upstream.Close()
proxy, _, _, _ := setupTestProxy(t)
proxy.HTTPClient = upstream.Client()
proxy.MetadataTTL = 0
h := &ContainerHandler{proxy: proxy, registryURL: upstream.URL, proxyURL: "http://localhost:8080"}
first := httptest.NewRecorder()
h.Routes().ServeHTTP(first, httptest.NewRequest(http.MethodGet, "/library/nginx/manifests/latest", nil))
if first.Code != http.StatusOK {
t.Fatalf("initial status = %d, want %d", first.Code, http.StatusOK)
}
currentDigest = newDigest
head := httptest.NewRecorder()
h.Routes().ServeHTTP(head, httptest.NewRequest(http.MethodHead, "/library/nginx/manifests/latest", nil))
if head.Code != http.StatusOK {
t.Fatalf("HEAD status = %d, want %d", head.Code, http.StatusOK)
}
if got := head.Header().Get("Docker-Content-Digest"); got != newDigest {
t.Errorf("Docker-Content-Digest = %q, want %q", got, newDigest)
}
if upstreamRequests != 2 {
t.Errorf("upstream requests = %d, want 2", upstreamRequests)
}
}
func TestContainerHandler_Routes_VersionCheck(t *testing.T) { func TestContainerHandler_Routes_VersionCheck(t *testing.T) {
h := NewContainerHandler(nil, "http://localhost:8080") h := NewContainerHandler(nil, "http://localhost:8080")

View file

@ -1,6 +1,7 @@
package handler package handler
import ( import (
"io"
"net/http" "net/http"
"strings" "strings"
) )
@ -30,14 +31,14 @@ func (h *CRANHandler) Routes() http.Handler {
mux := http.NewServeMux() mux := http.NewServeMux()
// Package indexes // Package indexes
mux.HandleFunc("GET /src/contrib/PACKAGES", h.proxyCached) mux.HandleFunc("GET /src/contrib/PACKAGES", h.proxyUpstream)
mux.HandleFunc("GET /src/contrib/PACKAGES.gz", h.proxyCached) mux.HandleFunc("GET /src/contrib/PACKAGES.gz", h.proxyUpstream)
mux.HandleFunc("GET /src/contrib/PACKAGES.rds", h.proxyCached) mux.HandleFunc("GET /src/contrib/PACKAGES.rds", h.proxyUpstream)
// Binary package indexes // Binary package indexes
mux.HandleFunc("GET /bin/{platform}/contrib/{rversion}/PACKAGES", h.proxyCached) mux.HandleFunc("GET /bin/{platform}/contrib/{rversion}/PACKAGES", h.proxyUpstream)
mux.HandleFunc("GET /bin/{platform}/contrib/{rversion}/PACKAGES.gz", h.proxyCached) mux.HandleFunc("GET /bin/{platform}/contrib/{rversion}/PACKAGES.gz", h.proxyUpstream)
mux.HandleFunc("GET /bin/{platform}/contrib/{rversion}/PACKAGES.rds", h.proxyCached) mux.HandleFunc("GET /bin/{platform}/contrib/{rversion}/PACKAGES.rds", h.proxyUpstream)
// Source package downloads // Source package downloads
mux.HandleFunc("GET /src/contrib/{filename}", h.handleSourceDownload) mux.HandleFunc("GET /src/contrib/{filename}", h.handleSourceDownload)
@ -72,7 +73,8 @@ func (h *CRANHandler) handleSourceDownload(w http.ResponseWriter, r *http.Reques
result, err := h.proxy.GetOrFetchArtifactFromURL(r.Context(), "cran", name, version, filename, upstreamURL) result, err := h.proxy.GetOrFetchArtifactFromURL(r.Context(), "cran", name, version, filename, upstreamURL)
if err != nil { if err != nil {
h.proxy.serveArtifactError(w, err, "failed to fetch package") h.proxy.Logger.Error("failed to get artifact", "error", err)
http.Error(w, "failed to fetch package", http.StatusBadGateway)
return return
} }
@ -106,7 +108,8 @@ func (h *CRANHandler) handleBinaryDownload(w http.ResponseWriter, r *http.Reques
result, err := h.proxy.GetOrFetchArtifactFromURL(r.Context(), "cran", name, storageVersion, filename, upstreamURL) result, err := h.proxy.GetOrFetchArtifactFromURL(r.Context(), "cran", name, storageVersion, filename, upstreamURL)
if err != nil { if err != nil {
h.proxy.serveArtifactError(w, err, "failed to fetch package") h.proxy.Logger.Error("failed to get artifact", "error", err)
http.Error(w, "failed to fetch package", http.StatusBadGateway)
return return
} }
@ -148,14 +151,36 @@ func (h *CRANHandler) isBinaryPackage(filename string) bool {
return strings.HasSuffix(filename, ".zip") || strings.HasSuffix(filename, ".tgz") return strings.HasSuffix(filename, ".zip") || strings.HasSuffix(filename, ".tgz")
} }
// 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, "*/*")
}
// proxyUpstream forwards a request to CRAN without caching. // proxyUpstream forwards a request to CRAN without caching.
func (h *CRANHandler) proxyUpstream(w http.ResponseWriter, r *http.Request) { func (h *CRANHandler) proxyUpstream(w http.ResponseWriter, r *http.Request) {
h.proxy.ProxyUpstream(w, r, h.upstreamURL+r.URL.Path, []string{headerAcceptEncoding}) upstreamURL := h.upstreamURL + r.URL.Path
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
}
if ae := r.Header.Get("Accept-Encoding"); ae != "" {
req.Header.Set("Accept-Encoding", ae)
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
h.proxy.Logger.Error("upstream request failed", "error", err)
http.Error(w, "upstream request failed", http.StatusBadGateway)
return
}
defer func() { _ = resp.Body.Close() }()
for k, vv := range resp.Header {
for _, v := range vv {
w.Header().Add(k, v)
}
}
w.WriteHeader(resp.StatusCode)
_, _ = io.Copy(w, resp.Body)
} }

View file

@ -2,6 +2,7 @@ package handler
import ( import (
"fmt" "fmt"
"io"
"net/http" "net/http"
"regexp" "regexp"
"strings" "strings"
@ -9,7 +10,6 @@ import (
const ( const (
debianUpstream = "http://deb.debian.org/debian" debianUpstream = "http://deb.debian.org/debian"
debMatchCount = 4 // full match + name + version + arch
) )
// DebianHandler handles APT/Debian repository protocol requests. // DebianHandler handles APT/Debian repository protocol requests.
@ -21,13 +21,10 @@ type DebianHandler struct {
} }
// NewDebianHandler creates a new Debian/APT protocol handler. // NewDebianHandler creates a new Debian/APT protocol handler.
func NewDebianHandler(proxy *Proxy, proxyURL string, upstreamURL string) *DebianHandler { func NewDebianHandler(proxy *Proxy, proxyURL string) *DebianHandler {
if upstreamURL == "" {
upstreamURL = debianUpstream
}
return &DebianHandler{ return &DebianHandler{
proxy: proxy, proxy: proxy,
upstreamURL: strings.TrimSuffix(upstreamURL, "/"), upstreamURL: debianUpstream,
proxyURL: strings.TrimSuffix(proxyURL, "/"), proxyURL: strings.TrimSuffix(proxyURL, "/"),
} }
} }
@ -43,11 +40,6 @@ func (h *DebianHandler) Routes() http.Handler {
path := strings.TrimPrefix(r.URL.Path, "/") path := strings.TrimPrefix(r.URL.Path, "/")
if containsPathTraversal(path) {
http.Error(w, "invalid path", http.StatusBadRequest)
return
}
// Route based on path type // Route based on path type
switch { switch {
case strings.HasPrefix(path, "pool/"): case strings.HasPrefix(path, "pool/"):
@ -84,7 +76,8 @@ func (h *DebianHandler) handlePackageDownload(w http.ResponseWriter, r *http.Req
result, err := h.proxy.GetOrFetchArtifactFromURL( result, err := h.proxy.GetOrFetchArtifactFromURL(
r.Context(), "deb", name, version, filename, downloadURL) r.Context(), "deb", name, version, filename, downloadURL)
if err != nil { if err != nil {
h.proxy.serveArtifactError(w, err, "failed to fetch package") h.proxy.Logger.Error("failed to get debian package", "error", err)
http.Error(w, "failed to fetch package", http.StatusBadGateway)
return return
} }
@ -95,13 +88,67 @@ func (h *DebianHandler) handlePackageDownload(w http.ResponseWriter, r *http.Req
// handleMetadata proxies repository metadata files. // handleMetadata proxies repository metadata files.
// These change frequently so we don't cache them. // These change frequently so we don't cache them.
func (h *DebianHandler) handleMetadata(w http.ResponseWriter, r *http.Request, path string) { func (h *DebianHandler) handleMetadata(w http.ResponseWriter, r *http.Request, path string) {
cacheKey := strings.ReplaceAll(path, "/", "_") upstreamURL := fmt.Sprintf("%s/%s", h.upstreamURL, path)
h.proxy.ProxyCached(w, r, fmt.Sprintf("%s/%s", h.upstreamURL, path), "debian", cacheKey, "*/*")
h.proxy.Logger.Debug("debian metadata request", "path", path)
req, err := http.NewRequestWithContext(r.Context(), r.Method, upstreamURL, nil)
if err != nil {
http.Error(w, "failed to create request", http.StatusInternalServerError)
return
}
// Forward relevant headers
for _, header := range []string{"Accept", "Accept-Encoding", "If-Modified-Since", "If-None-Match"} {
if v := r.Header.Get(header); v != "" {
req.Header.Set(header, v)
}
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
h.proxy.Logger.Error("failed to fetch upstream metadata", "error", err)
http.Error(w, "failed to fetch from upstream", http.StatusBadGateway)
return
}
defer func() { _ = resp.Body.Close() }()
// Copy response headers
for _, header := range []string{"Content-Type", "Content-Length", "Last-Modified", "ETag"} {
if v := resp.Header.Get(header); v != "" {
w.Header().Set(header, v)
}
}
w.WriteHeader(resp.StatusCode)
_, _ = io.Copy(w, resp.Body)
} }
// proxyFile proxies any file directly without caching. // proxyFile proxies any file directly without caching.
func (h *DebianHandler) proxyFile(w http.ResponseWriter, r *http.Request, path string) { func (h *DebianHandler) proxyFile(w http.ResponseWriter, r *http.Request, path string) {
h.proxy.ProxyFile(w, r, fmt.Sprintf("%s/%s", h.upstreamURL, path)) upstreamURL := fmt.Sprintf("%s/%s", h.upstreamURL, path)
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 := http.DefaultClient.Do(req)
if err != nil {
http.Error(w, "failed to fetch from upstream", http.StatusBadGateway)
return
}
defer func() { _ = resp.Body.Close() }()
for key, values := range resp.Header {
for _, v := range values {
w.Header().Add(key, v)
}
}
w.WriteHeader(resp.StatusCode)
_, _ = io.Copy(w, resp.Body)
} }
// debPackagePattern matches .deb filenames to extract name, version, and arch. // debPackagePattern matches .deb filenames to extract name, version, and arch.
@ -120,7 +167,7 @@ func (h *DebianHandler) parsePoolPath(path string) (name, version, arch string)
// Parse the filename // Parse the filename
matches := debPackagePattern.FindStringSubmatch(filename) matches := debPackagePattern.FindStringSubmatch(filename)
if len(matches) != debMatchCount { if len(matches) != 4 {
return "", "", "" return "", "", ""
} }

View file

@ -1,28 +1,89 @@
package handler package handler
import ( import (
"net/http"
"net/http/httptest"
"testing" "testing"
) )
func TestDebianHandler_parsePoolPath(t *testing.T) { func TestDebianHandler_parsePoolPath(t *testing.T) {
h := &DebianHandler{} h := &DebianHandler{}
assertPathParser(t, "parsePoolPath", h.parsePoolPath, []pathParseCase{ tests := []struct {
{"pool/main/n/nginx/nginx_1.18.0-6_amd64.deb", "nginx", "1.18.0-6", "amd64"}, path string
{"pool/main/libn/libncurses/libncurses6_6.2-1_amd64.deb", "libncurses6", "6.2-1", "amd64"}, wantName string
{"pool/contrib/v/virtualbox/virtualbox_6.1.38-1_amd64.deb", "virtualbox", "6.1.38-1", "amd64"}, wantVersion string
{"pool/main/g/git/git_2.39.2-1_arm64.deb", "git", "2.39.2-1", "arm64"}, wantArch string
}{
{ {
"pool/universe/n/nmap/nmap_7.91+dfsg1+really7.80+dfsg1-2ubuntu0.1_amd64.deb", path: "pool/main/n/nginx/nginx_1.18.0-6_amd64.deb",
"nmap", "7.91+dfsg1+really7.80+dfsg1-2ubuntu0.1", "amd64", wantName: "nginx",
wantVersion: "1.18.0-6",
wantArch: "amd64",
}, },
{"pool/main/o/openssl/openssl_3.0.2-0ubuntu1.15~build1_amd64.deb", "openssl", "3.0.2-0ubuntu1.15~build1", "amd64"}, {
{"invalid/path", "", "", ""}, path: "pool/main/libn/libncurses/libncurses6_6.2-1_amd64.deb",
{"pool/main/n/nginx/nginx.deb", "", "", ""}, wantName: "libncurses6",
}) wantVersion: "6.2-1",
wantArch: "amd64",
},
{
path: "pool/contrib/v/virtualbox/virtualbox_6.1.38-1_amd64.deb",
wantName: "virtualbox",
wantVersion: "6.1.38-1",
wantArch: "amd64",
},
{
path: "pool/main/g/git/git_2.39.2-1_arm64.deb",
wantName: "git",
wantVersion: "2.39.2-1",
wantArch: "arm64",
},
{
path: "invalid/path",
wantName: "",
wantVersion: "",
wantArch: "",
},
{
path: "pool/main/n/nginx/nginx.deb",
wantName: "",
wantVersion: "",
wantArch: "",
},
}
for _, tt := range tests {
t.Run(tt.path, func(t *testing.T) {
name, version, arch := h.parsePoolPath(tt.path)
if name != tt.wantName {
t.Errorf("parsePoolPath() name = %q, want %q", name, tt.wantName)
}
if version != tt.wantVersion {
t.Errorf("parsePoolPath() version = %q, want %q", version, tt.wantVersion)
}
if arch != tt.wantArch {
t.Errorf("parsePoolPath() arch = %q, want %q", arch, tt.wantArch)
}
})
}
} }
func TestDebianHandler_Routes(t *testing.T) { func TestDebianHandler_Routes(t *testing.T) {
h := NewDebianHandler(nil, "http://localhost:8080", "") h := NewDebianHandler(nil, "http://localhost:8080")
assertRoutesBasics(t, h.Routes(), "/dists/stable/Release", "/pool/../../../etc/passwd")
// Test that handler doesn't panic on initialization
handler := h.Routes()
if handler == nil {
t.Fatal("Routes() returned nil")
}
// Test method not allowed
req := httptest.NewRequest(http.MethodPost, "/dists/stable/Release", nil)
w := httptest.NewRecorder()
handler.ServeHTTP(w, req)
if w.Code != http.StatusMethodNotAllowed {
t.Errorf("POST request: got status %d, want %d", w.Code, http.StatusMethodNotAllowed)
}
} }

File diff suppressed because it is too large Load diff

View file

@ -1,39 +0,0 @@
package handler
import (
"net/http"
"strings"
)
type filenameDownload struct {
ecosystem string
suffix string
parseErr string
fetchErr string
parse func(string) (name, version string)
}
func (p *Proxy) handleFilenameDownload(w http.ResponseWriter, r *http.Request, d filenameDownload) {
filename := r.PathValue("filename")
if filename == "" || !strings.HasSuffix(filename, d.suffix) {
http.Error(w, "invalid filename", http.StatusBadRequest)
return
}
name, version := d.parse(filename)
if name == "" || version == "" {
http.Error(w, d.parseErr, http.StatusBadRequest)
return
}
p.Logger.Info(d.ecosystem+" download request",
"name", name, "version", version, "filename", filename)
result, err := p.GetOrFetchArtifact(r.Context(), d.ecosystem, name, version, filename)
if err != nil {
p.serveArtifactError(w, err, d.fetchErr)
return
}
ServeArtifact(w, result)
}

View file

@ -1,13 +1,10 @@
package handler package handler
import ( import (
"bufio"
"encoding/json"
"fmt" "fmt"
"io" "io"
"net/http" "net/http"
"strings" "strings"
"time"
) )
const ( const (
@ -38,13 +35,13 @@ func (h *GemHandler) Routes() http.Handler {
mux.HandleFunc("GET /gems/{filename}", h.handleDownload) mux.HandleFunc("GET /gems/{filename}", h.handleDownload)
// Specs indexes (compressed Ruby Marshal format) // Specs indexes (compressed Ruby Marshal format)
mux.HandleFunc("GET /specs.4.8.gz", h.proxyCached) mux.HandleFunc("GET /specs.4.8.gz", h.proxyUpstream)
mux.HandleFunc("GET /latest_specs.4.8.gz", h.proxyCached) mux.HandleFunc("GET /latest_specs.4.8.gz", h.proxyUpstream)
mux.HandleFunc("GET /prerelease_specs.4.8.gz", h.proxyCached) mux.HandleFunc("GET /prerelease_specs.4.8.gz", h.proxyUpstream)
// Compact index (bundler 2.x+) // Compact index (bundler 2.x+)
mux.HandleFunc("GET /versions", h.proxyCached) mux.HandleFunc("GET /versions", h.proxyUpstream)
mux.HandleFunc("GET /info/{name}", h.handleCompactIndex) mux.HandleFunc("GET /info/{name}", h.proxyUpstream)
// Quick index // Quick index
mux.HandleFunc("GET /quick/Marshal.4.8/{filename}", h.proxyUpstream) mux.HandleFunc("GET /quick/Marshal.4.8/{filename}", h.proxyUpstream)
@ -58,13 +55,30 @@ func (h *GemHandler) Routes() http.Handler {
// handleDownload serves a gem file, fetching and caching from upstream if needed. // handleDownload serves a gem file, fetching and caching from upstream if needed.
func (h *GemHandler) handleDownload(w http.ResponseWriter, r *http.Request) { func (h *GemHandler) handleDownload(w http.ResponseWriter, r *http.Request) {
h.proxy.handleFilenameDownload(w, r, filenameDownload{ filename := r.PathValue("filename")
ecosystem: "gem", if filename == "" || !strings.HasSuffix(filename, ".gem") {
suffix: ".gem", http.Error(w, "invalid filename", http.StatusBadRequest)
parseErr: "could not parse gem filename", return
fetchErr: "failed to fetch gem", }
parse: h.parseGemFilename,
}) // Extract name and version from filename (e.g., "rails-7.1.0.gem")
name, version := h.parseGemFilename(filename)
if name == "" || version == "" {
http.Error(w, "could not parse gem filename", http.StatusBadRequest)
return
}
h.proxy.Logger.Info("gem download request",
"name", name, "version", version, "filename", filename)
result, err := h.proxy.GetOrFetchArtifact(r.Context(), "gem", name, version, filename)
if err != nil {
h.proxy.Logger.Error("failed to get artifact", "error", err)
http.Error(w, "failed to fetch gem", http.StatusBadGateway)
return
}
ServeArtifact(w, result)
} }
// parseGemFilename extracts name and version from a gem filename. // parseGemFilename extracts name and version from a gem filename.
@ -84,198 +98,6 @@ func (h *GemHandler) parseGemFilename(filename string) (name, version string) {
return "", "" return "", ""
} }
// handleCompactIndex serves the compact index for a gem, filtering versions
// based on cooldown when enabled.
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
}
h.proxy.Logger.Info("gem compact index request with cooldown", "name", name)
indexResp, filteredVersions, err := h.fetchIndexAndVersions(r, name)
if err != nil {
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 {
copyResponseHeaders(w, indexResp.Header)
w.WriteHeader(indexResp.StatusCode)
_, _ = io.Copy(w, indexResp.Body)
return
}
if filteredVersions == nil {
h.proxy.Logger.Warn("failed to fetch version timestamps, proxying unfiltered", "name", name)
copyResponseHeaders(w, indexResp.Header)
w.WriteHeader(http.StatusOK)
_, _ = io.Copy(w, indexResp.Body)
return
}
h.writeFilteredIndex(w, indexResp, name, filteredVersions)
}
// 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
}
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)
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)
}
}
return h.proxy.HTTPClient.Do(req)
}
// 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, "Content-Length") {
continue // length will change after filtering
}
for _, v := range vv {
w.Header().Add(k, v)
}
}
w.WriteHeader(http.StatusOK)
scanner := bufio.NewScanner(resp.Body)
for scanner.Scan() {
line := scanner.Text()
if line == "---" {
_, _ = fmt.Fprintln(w, line)
continue
}
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)
}
}
// copyResponseHeaders copies HTTP headers from a response to a writer.
func copyResponseHeaders(w http.ResponseWriter, headers http.Header) {
for k, vv := range headers {
for _, v := range vv {
w.Header().Add(k, v)
}
}
}
// gemVersion represents a version entry from the RubyGems versions API.
type gemVersion struct {
Number string `json:"number"`
Platform string `json:"platform"`
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)
}
var versions []gemVersion
if err := json.NewDecoder(resp.Body).Decode(&versions); err != nil {
return nil, err
}
packagePURL := canonicalPackagePURL("gem", name)
filtered := make(map[string]bool)
for _, v := range versions {
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
}
}
return filtered, nil
}
// proxyCached forwards a metadata request with caching.
func (h *GemHandler) proxyCached(w http.ResponseWriter, r *http.Request) {
upstreamURL := h.upstreamURL + r.URL.Path
cacheKey := strings.TrimPrefix(r.URL.Path, "/")
h.proxy.ProxyCached(w, r, upstreamURL, "gem", cacheKey, "*/*")
}
// proxyUpstream forwards a request to rubygems.org without caching. // proxyUpstream forwards a request to rubygems.org without caching.
func (h *GemHandler) proxyUpstream(w http.ResponseWriter, r *http.Request) { func (h *GemHandler) proxyUpstream(w http.ResponseWriter, r *http.Request) {
upstreamURL := h.upstreamURL + r.URL.Path upstreamURL := h.upstreamURL + r.URL.Path
@ -292,13 +114,13 @@ func (h *GemHandler) proxyUpstream(w http.ResponseWriter, r *http.Request) {
} }
// Copy relevant headers // Copy relevant headers
for _, h := range []string{"Accept", headerAcceptEncoding, "If-None-Match", "If-Modified-Since"} { for _, h := range []string{"Accept", "Accept-Encoding", "If-None-Match", "If-Modified-Since"} {
if v := r.Header.Get(h); v != "" { if v := r.Header.Get(h); v != "" {
req.Header.Set(h, v) req.Header.Set(h, v)
} }
} }
resp, err := h.proxy.HTTPClient.Do(req) resp, err := http.DefaultClient.Do(req)
if err != nil { if err != nil {
h.proxy.Logger.Error("upstream request failed", "error", err) h.proxy.Logger.Error("upstream request failed", "error", err)
http.Error(w, "upstream request failed", http.StatusBadGateway) http.Error(w, "upstream request failed", http.StatusBadGateway)

View file

@ -1,16 +1,8 @@
package handler package handler
import ( import (
"encoding/json"
"fmt"
"log/slog" "log/slog"
"net/http"
"net/http/httptest"
"strings"
"testing" "testing"
"time"
"github.com/git-pkgs/cooldown"
) )
func TestGemParseFilename(t *testing.T) { func TestGemParseFilename(t *testing.T) {
@ -36,217 +28,3 @@ func TestGemParseFilename(t *testing.T) {
} }
} }
} }
func TestGemCompactIndexCooldown(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)
compactIndex := "---\n1.0.0 dep1:>= 1.0|checksum:abc123\n2.0.0 dep1:>= 1.0|checksum:def456\n"
versionsJSON, _ := json.Marshal([]gemVersion{
{Number: "1.0.0", Platform: "ruby", CreatedAt: oldTime},
{Number: "2.0.0", Platform: "ruby", CreatedAt: recentTime},
})
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch {
case strings.HasPrefix(r.URL.Path, "/info/"):
w.Header().Set("Content-Type", "text/plain")
_, _ = w.Write([]byte(compactIndex))
case strings.HasPrefix(r.URL.Path, "/api/v1/versions/"):
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write(versionsJSON)
default:
w.WriteHeader(http.StatusNotFound)
}
}))
defer upstream.Close()
proxy := testProxy()
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)
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)
}
body := w.Body.String()
if !strings.Contains(body, "1.0.0") {
t.Error("expected version 1.0.0 to survive filtering")
}
if strings.Contains(body, "2.0.0") {
t.Error("expected version 2.0.0 to be filtered out")
}
if !strings.HasPrefix(body, "---\n") {
t.Error("expected compact index header to be preserved")
}
}
func TestGemCompactIndexCooldownWithPlatformVersion(t *testing.T) {
now := time.Now()
recentTime := now.Add(-1 * time.Hour).Format(time.RFC3339)
compactIndex := "---\n1.0.0 dep:>= 1.0|checksum:abc\n1.0.0-java dep:>= 1.0|checksum:def\n"
versionsJSON, _ := json.Marshal([]gemVersion{
{Number: "1.0.0", Platform: "ruby", CreatedAt: recentTime},
{Number: "1.0.0", Platform: "java", CreatedAt: recentTime},
})
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch {
case strings.HasPrefix(r.URL.Path, "/info/"):
_, _ = w.Write([]byte(compactIndex))
case strings.HasPrefix(r.URL.Path, "/api/v1/versions/"):
_, _ = w.Write(versionsJSON)
}
}))
defer upstream.Close()
proxy := testProxy()
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)
req.SetPathValue("name", "testgem")
w := httptest.NewRecorder()
h.handleCompactIndex(w, req)
body := w.Body.String()
// Both ruby and java platform versions should be filtered
lines := strings.Split(strings.TrimSpace(body), "\n")
if len(lines) != 1 { // only "---"
t.Errorf("expected only header line, got %d lines: %v", len(lines), lines)
}
}
func TestGemCompactIndexNoCooldown(t *testing.T) {
compactIndex := "---\n1.0.0 dep:>= 1.0|checksum:abc\n"
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write([]byte(compactIndex))
}))
defer upstream.Close()
h := &GemHandler{
proxy: testProxy(), // no cooldown
upstreamURL: upstream.URL,
proxyURL: "http://proxy.local",
}
req := httptest.NewRequest(http.MethodGet, "/info/testgem", nil)
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)
}
}
func TestGemCompactIndexVersionsAPIFails(t *testing.T) {
compactIndex := "---\n1.0.0 dep:>= 1.0|checksum:abc\n"
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch {
case strings.HasPrefix(r.URL.Path, "/info/"):
_, _ = w.Write([]byte(compactIndex))
case strings.HasPrefix(r.URL.Path, "/api/v1/versions/"):
w.WriteHeader(http.StatusInternalServerError)
}
}))
defer upstream.Close()
proxy := testProxy()
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)
req.SetPathValue("name", "testgem")
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)
}
body := w.Body.String()
if !strings.Contains(body, "1.0.0") {
t.Error("expected unfiltered content when versions API fails")
}
}
func TestGemFetchFilteredVersions(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)
versionsJSON, _ := json.Marshal([]gemVersion{
{Number: "1.0.0", Platform: "ruby", CreatedAt: oldTime},
{Number: "2.0.0", Platform: "ruby", CreatedAt: recentTime},
{Number: "2.0.0", Platform: "java", CreatedAt: recentTime},
})
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",
}
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")
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")
}
_ = fmt.Sprintf // silence unused import
}

View file

@ -1,17 +1,14 @@
package handler package handler
import ( import (
"errors"
"fmt" "fmt"
"io"
"net/http" "net/http"
"strings" "strings"
"github.com/git-pkgs/registries/fetch"
) )
const ( const (
goUpstream = "https://proxy.golang.org" goUpstream = "https://proxy.golang.org"
asciiCaseOffset = 32 // difference between lowercase and uppercase ASCII letters
) )
// GoHandler handles Go module proxy protocol requests. // GoHandler handles Go module proxy protocol requests.
@ -57,19 +54,18 @@ func (h *GoHandler) handleRequest(w http.ResponseWriter, r *http.Request) {
module := path[:idx] module := path[:idx]
rest := path[idx+4:] // after "/@v/" rest := path[idx+4:] // after "/@v/"
decodedMod := decodeGoModule(module)
switch { switch {
case rest == "list": case rest == "list":
// GET /{module}/@v/list - list versions // GET /{module}/@v/list - list versions
h.proxyCached(w, r, decodedMod+"/@v/list") h.proxyUpstream(w, r)
case strings.HasSuffix(rest, ".info"): case strings.HasSuffix(rest, ".info"):
// GET /{module}/@v/{version}.info - version metadata // GET /{module}/@v/{version}.info - version metadata
h.proxyCached(w, r, decodedMod+"/@v/"+rest) h.proxyUpstream(w, r)
case strings.HasSuffix(rest, ".mod"): case strings.HasSuffix(rest, ".mod"):
// GET /{module}/@v/{version}.mod - go.mod file // GET /{module}/@v/{version}.mod - go.mod file
h.proxyCached(w, r, decodedMod+"/@v/"+rest) h.proxyUpstream(w, r)
case strings.HasSuffix(rest, ".zip"): case strings.HasSuffix(rest, ".zip"):
// GET /{module}/@v/{version}.zip - source archive (cache this) // GET /{module}/@v/{version}.zip - source archive (cache this)
@ -84,8 +80,7 @@ func (h *GoHandler) handleRequest(w http.ResponseWriter, r *http.Request) {
// Check for @latest // Check for @latest
if strings.HasSuffix(path, "/@latest") { if strings.HasSuffix(path, "/@latest") {
module := strings.TrimSuffix(path, "/@latest") h.proxyUpstream(w, r)
h.proxyCached(w, r, decodeGoModule(module)+"/@latest")
return return
} }
@ -103,10 +98,6 @@ func (h *GoHandler) handleDownload(w http.ResponseWriter, r *http.Request, modul
result, err := h.proxy.GetOrFetchArtifact(r.Context(), "golang", decodedModule, version, filename) result, err := h.proxy.GetOrFetchArtifact(r.Context(), "golang", decodedModule, version, filename)
if err != nil { if err != nil {
if errors.Is(err, fetch.ErrNotFound) {
http.Error(w, "not found", http.StatusNotFound)
return
}
h.proxy.Logger.Error("failed to get artifact", "error", err) h.proxy.Logger.Error("failed to get artifact", "error", err)
http.Error(w, "failed to fetch module", http.StatusBadGateway) http.Error(w, "failed to fetch module", http.StatusBadGateway)
return return
@ -117,12 +108,33 @@ func (h *GoHandler) handleDownload(w http.ResponseWriter, r *http.Request, modul
// proxyUpstream forwards a request to proxy.golang.org without caching. // proxyUpstream forwards a request to proxy.golang.org without caching.
func (h *GoHandler) proxyUpstream(w http.ResponseWriter, r *http.Request) { func (h *GoHandler) proxyUpstream(w http.ResponseWriter, r *http.Request) {
h.proxy.ProxyUpstream(w, r, h.upstreamURL+r.URL.Path, nil) upstreamURL := h.upstreamURL + r.URL.Path
}
// proxyCached forwards a request with metadata caching. h.proxy.Logger.Debug("proxying to upstream", "url", upstreamURL)
func (h *GoHandler) proxyCached(w http.ResponseWriter, r *http.Request, cacheKey string) {
h.proxy.ProxyCached(w, r, h.upstreamURL+r.URL.Path, "golang", cacheKey, "*/*") req, err := http.NewRequestWithContext(r.Context(), http.MethodGet, upstreamURL, nil)
if err != nil {
http.Error(w, "failed to create request", http.StatusInternalServerError)
return
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
h.proxy.Logger.Error("upstream request failed", "error", err)
http.Error(w, "upstream request failed", http.StatusBadGateway)
return
}
defer func() { _ = resp.Body.Close() }()
// Copy response headers
for k, vv := range resp.Header {
for _, v := range vv {
w.Header().Add(k, v)
}
}
w.WriteHeader(resp.StatusCode)
_, _ = io.Copy(w, resp.Body)
} }
// decodeGoModule decodes an encoded module path. // decodeGoModule decodes an encoded module path.
@ -131,7 +143,7 @@ func decodeGoModule(encoded string) string {
var b strings.Builder var b strings.Builder
for i := 0; i < len(encoded); i++ { for i := 0; i < len(encoded); i++ {
if encoded[i] == '!' && i+1 < len(encoded) { if encoded[i] == '!' && i+1 < len(encoded) {
b.WriteByte(encoded[i+1] - asciiCaseOffset) // lowercase to uppercase b.WriteByte(encoded[i+1] - 32) // lowercase to uppercase
i++ i++
} else { } else {
b.WriteByte(encoded[i]) b.WriteByte(encoded[i])

View file

@ -1,49 +1,9 @@
package handler package handler
import ( import (
"errors"
"net/http"
"net/http/httptest"
"testing" "testing"
"github.com/git-pkgs/registries/fetch"
) )
func TestGoModuleDownloadUpstreamErrors(t *testing.T) {
tests := []struct {
name string
fetchErr error
wantStatus int
}{
{
name: "module not found",
fetchErr: fetch.ErrNotFound,
wantStatus: http.StatusNotFound,
},
{
name: "upstream failure",
fetchErr: errors.New("connection refused"),
wantStatus: http.StatusBadGateway,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
proxy, _, _, fetcher := setupTestProxy(t)
fetcher.fetchErr = tt.fetchErr
handler := NewGoHandler(proxy, "http://localhost:8080")
req := httptest.NewRequest(http.MethodGet, "/example.com/mod/@v/v1.0.0.zip", nil)
resp := httptest.NewRecorder()
handler.Routes().ServeHTTP(resp, req)
if resp.Code != tt.wantStatus {
t.Fatalf("status = %d, want %d", resp.Code, tt.wantStatus)
}
})
}
}
func TestDecodeGoModule(t *testing.T) { func TestDecodeGoModule(t *testing.T) {
tests := []struct { tests := []struct {
encoded string encoded string

View file

@ -1,178 +0,0 @@
package handler
import (
"errors"
"io"
"net/http"
"regexp"
"strconv"
"strings"
"time"
"github.com/git-pkgs/proxy/internal/metrics"
"github.com/git-pkgs/proxy/internal/storage"
)
const (
gradleBuildCacheContentType = "application/vnd.gradle.build-cache-artifact.v2"
gradleBuildCacheStorageRoot = "_gradle/http-build-cache"
defaultGradleMaxUploadSize = 100 << 20
)
var gradleBuildCacheKeyPattern = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._-]*$`)
// GradleBuildCacheHandler handles Gradle HttpBuildCache GET/HEAD/PUT requests.
//
// This handler accepts /{key} when mounted under a base URL.
type GradleBuildCacheHandler struct {
proxy *Proxy
}
// NewGradleBuildCacheHandler creates a Gradle HttpBuildCache handler.
func NewGradleBuildCacheHandler(proxy *Proxy) *GradleBuildCacheHandler {
return &GradleBuildCacheHandler{proxy: proxy}
}
// Routes returns the HTTP handler for Gradle HttpBuildCache requests.
func (h *GradleBuildCacheHandler) Routes() http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodGet, http.MethodHead, http.MethodPut:
default:
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
key, statusCode := h.parseCacheKey(r.URL.Path)
if statusCode != http.StatusOK {
if statusCode == http.StatusNotFound {
http.NotFound(w, r)
return
}
http.Error(w, "invalid cache key", statusCode)
return
}
if r.Method == http.MethodPut {
if h.proxy.GradleReadOnly {
http.Error(w, "gradle build cache is read-only", http.StatusMethodNotAllowed)
return
}
h.handlePut(w, r, key)
return
}
h.handleGetOrHead(w, r, key)
})
}
func (h *GradleBuildCacheHandler) parseCacheKey(urlPath string) (string, int) {
keyPath := strings.TrimPrefix(urlPath, "/")
if keyPath == "" {
return "", http.StatusNotFound
}
if containsPathTraversal(keyPath) {
return "", http.StatusBadRequest
}
if strings.Contains(keyPath, "/") {
return "", http.StatusNotFound
}
if !gradleBuildCacheKeyPattern.MatchString(keyPath) {
return "", http.StatusBadRequest
}
return keyPath, http.StatusOK
}
func (h *GradleBuildCacheHandler) cacheStoragePath(key string) string {
return gradleBuildCacheStorageRoot + "/" + key
}
func (h *GradleBuildCacheHandler) handleGetOrHead(w http.ResponseWriter, r *http.Request, key string) {
storagePath := h.cacheStoragePath(key)
w.Header().Set("Content-Type", gradleBuildCacheContentType)
if r.Method == http.MethodHead {
existsStart := time.Now()
exists, err := h.proxy.Storage.Exists(r.Context(), storagePath)
metrics.RecordStorageOperation("read", time.Since(existsStart))
if err != nil {
metrics.RecordStorageError("read")
h.proxy.Logger.Error("failed to check gradle build cache entry", "key", key, "error", err)
http.Error(w, "failed to read cache entry", http.StatusInternalServerError)
return
}
if !exists {
metrics.RecordCacheMiss("gradle")
http.NotFound(w, r)
return
}
metrics.RecordCacheHit("gradle")
sizeStart := time.Now()
size, err := h.proxy.Storage.Size(r.Context(), storagePath)
metrics.RecordStorageOperation("read", time.Since(sizeStart))
if err != nil {
metrics.RecordStorageError("read")
} else if size >= 0 {
w.Header().Set("Content-Length", strconv.FormatInt(size, 10))
}
w.WriteHeader(http.StatusOK)
return
}
readStart := time.Now()
reader, err := h.proxy.Storage.Open(r.Context(), storagePath)
metrics.RecordStorageOperation("read", time.Since(readStart))
if err != nil {
if errors.Is(err, storage.ErrNotFound) {
metrics.RecordCacheMiss("gradle")
http.NotFound(w, r)
return
}
metrics.RecordStorageError("read")
h.proxy.Logger.Error("failed to open gradle build cache entry", "key", key, "error", err)
http.Error(w, "failed to read cache entry", http.StatusInternalServerError)
return
}
defer func() { _ = reader.Close() }()
metrics.RecordCacheHit("gradle")
w.WriteHeader(http.StatusOK)
_, _ = io.Copy(w, reader)
}
func (h *GradleBuildCacheHandler) handlePut(w http.ResponseWriter, r *http.Request, key string) {
storagePath := h.cacheStoragePath(key)
maxUploadSize := h.proxy.GradleMaxUploadSize
if maxUploadSize <= 0 {
maxUploadSize = defaultGradleMaxUploadSize
}
r.Body = http.MaxBytesReader(w, r.Body, maxUploadSize)
storeStart := time.Now()
_, hash, err := h.proxy.Storage.Store(r.Context(), storagePath, r.Body)
metrics.RecordStorageOperation("write", time.Since(storeStart))
if err != nil {
var maxBytesErr *http.MaxBytesError
if errors.As(err, &maxBytesErr) {
http.Error(w, "cache entry too large", http.StatusRequestEntityTooLarge)
return
}
metrics.RecordStorageError("write")
h.proxy.Logger.Error("failed to store gradle build cache entry", "key", key, "error", err)
http.Error(w, "failed to write cache entry", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Length", "0")
w.Header().Set("ETag", `"`+hash+`"`)
w.WriteHeader(http.StatusCreated)
}

View file

@ -1,285 +0,0 @@
package handler
import (
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/git-pkgs/proxy/internal/metrics"
"github.com/prometheus/client_golang/prometheus/testutil"
)
func TestGradleBuildCacheHandler_PutGetHead(t *testing.T) {
proxy, _, _, _ := setupTestProxy(t)
h := NewGradleBuildCacheHandler(proxy)
srv := httptest.NewServer(h.Routes())
defer srv.Close()
key := "a1b2c3d4e5f6"
payload := "cache entry content"
putReq, err := http.NewRequest(http.MethodPut, srv.URL+"/"+key, strings.NewReader(payload))
if err != nil {
t.Fatalf("failed to create PUT request: %v", err)
}
putResp, err := http.DefaultClient.Do(putReq)
if err != nil {
t.Fatalf("PUT request failed: %v", err)
}
_ = putResp.Body.Close()
if putResp.StatusCode != http.StatusCreated {
t.Fatalf("PUT status = %d, want %d", putResp.StatusCode, http.StatusCreated)
}
getResp, err := http.Get(srv.URL + "/" + key)
if err != nil {
t.Fatalf("GET request failed: %v", err)
}
defer func() { _ = getResp.Body.Close() }()
if getResp.StatusCode != http.StatusOK {
t.Fatalf("GET status = %d, want %d", getResp.StatusCode, http.StatusOK)
}
if getResp.Header.Get("Content-Type") != gradleBuildCacheContentType {
t.Fatalf("GET Content-Type = %q, want %q", getResp.Header.Get("Content-Type"), gradleBuildCacheContentType)
}
body, _ := io.ReadAll(getResp.Body)
if string(body) != payload {
t.Fatalf("GET body = %q, want %q", body, payload)
}
headReq, err := http.NewRequest(http.MethodHead, srv.URL+"/"+key, nil)
if err != nil {
t.Fatalf("failed to create HEAD request: %v", err)
}
headResp, err := http.DefaultClient.Do(headReq)
if err != nil {
t.Fatalf("HEAD request failed: %v", err)
}
defer func() { _ = headResp.Body.Close() }()
if headResp.StatusCode != http.StatusOK {
t.Fatalf("HEAD status = %d, want %d", headResp.StatusCode, http.StatusOK)
}
body, _ = io.ReadAll(headResp.Body)
if len(body) != 0 {
t.Fatalf("HEAD body length = %d, want 0", len(body))
}
}
func TestGradleBuildCacheHandler_RootKeyPath(t *testing.T) {
proxy, _, _, _ := setupTestProxy(t)
h := NewGradleBuildCacheHandler(proxy)
srv := httptest.NewServer(h.Routes())
defer srv.Close()
key := "rootpathkey"
putReq, err := http.NewRequest(http.MethodPut, srv.URL+"/"+key, strings.NewReader("root"))
if err != nil {
t.Fatalf("failed to create PUT request: %v", err)
}
putResp, err := http.DefaultClient.Do(putReq)
if err != nil {
t.Fatalf("PUT request failed: %v", err)
}
_ = putResp.Body.Close()
if putResp.StatusCode != http.StatusCreated {
t.Fatalf("PUT status = %d, want %d", putResp.StatusCode, http.StatusCreated)
}
getResp, err := http.Get(srv.URL + "/" + key)
if err != nil {
t.Fatalf("GET request failed: %v", err)
}
defer func() { _ = getResp.Body.Close() }()
if getResp.StatusCode != http.StatusOK {
t.Fatalf("GET status = %d, want %d", getResp.StatusCode, http.StatusOK)
}
}
func TestGradleBuildCacheHandler_GetMiss(t *testing.T) {
proxy, _, _, _ := setupTestProxy(t)
h := NewGradleBuildCacheHandler(proxy)
srv := httptest.NewServer(h.Routes())
defer srv.Close()
resp, err := http.Get(srv.URL + "/missing-key")
if err != nil {
t.Fatalf("GET request failed: %v", err)
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != http.StatusNotFound {
t.Fatalf("status = %d, want %d", resp.StatusCode, http.StatusNotFound)
}
}
func TestGradleBuildCacheHandler_MethodNotAllowed(t *testing.T) {
proxy, _, _, _ := setupTestProxy(t)
h := NewGradleBuildCacheHandler(proxy)
req := httptest.NewRequest(http.MethodPost, "/key", nil)
w := httptest.NewRecorder()
h.Routes().ServeHTTP(w, req)
if w.Code != http.StatusMethodNotAllowed {
t.Fatalf("status = %d, want %d", w.Code, http.StatusMethodNotAllowed)
}
}
func TestGradleBuildCacheHandler_PathTraversalRejected(t *testing.T) {
proxy, _, _, _ := setupTestProxy(t)
h := NewGradleBuildCacheHandler(proxy)
req := httptest.NewRequest(http.MethodGet, "/../secret", nil)
w := httptest.NewRecorder()
h.Routes().ServeHTTP(w, req)
if w.Code != http.StatusBadRequest {
t.Fatalf("status = %d, want %d", w.Code, http.StatusBadRequest)
}
}
func TestGradleBuildCacheHandler_CachePrefixRejected(t *testing.T) {
proxy, _, _, _ := setupTestProxy(t)
h := NewGradleBuildCacheHandler(proxy)
req := httptest.NewRequest(http.MethodGet, "/cache/key", nil)
w := httptest.NewRecorder()
h.Routes().ServeHTTP(w, req)
if w.Code != http.StatusNotFound {
t.Fatalf("status = %d, want %d", w.Code, http.StatusNotFound)
}
}
func TestGradleBuildCacheHandler_PutOverwriteReturnsCreated(t *testing.T) {
proxy, _, _, _ := setupTestProxy(t)
h := NewGradleBuildCacheHandler(proxy)
srv := httptest.NewServer(h.Routes())
defer srv.Close()
key := "overwrite-key"
for i, payload := range []string{"first", "second"} {
req, err := http.NewRequest(http.MethodPut, srv.URL+"/"+key, strings.NewReader(payload))
if err != nil {
t.Fatalf("failed to create PUT request: %v", err)
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatalf("PUT request failed: %v", err)
}
_ = resp.Body.Close()
want := http.StatusCreated
if resp.StatusCode != want {
t.Fatalf("PUT #%d status = %d, want %d", i+1, resp.StatusCode, want)
}
}
}
func TestGradleBuildCacheHandler_PutReadOnly(t *testing.T) {
proxy, _, _, _ := setupTestProxy(t)
proxy.GradleReadOnly = true
h := NewGradleBuildCacheHandler(proxy)
srv := httptest.NewServer(h.Routes())
defer srv.Close()
req, err := http.NewRequest(http.MethodPut, srv.URL+"/readonly-key", strings.NewReader("payload"))
if err != nil {
t.Fatalf("failed to create PUT request: %v", err)
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatalf("PUT request failed: %v", err)
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != http.StatusMethodNotAllowed {
t.Fatalf("PUT status = %d, want %d", resp.StatusCode, http.StatusMethodNotAllowed)
}
}
func TestGradleBuildCacheHandler_PutTooLarge(t *testing.T) {
proxy, _, _, _ := setupTestProxy(t)
proxy.GradleMaxUploadSize = 4
h := NewGradleBuildCacheHandler(proxy)
srv := httptest.NewServer(h.Routes())
defer srv.Close()
req, err := http.NewRequest(http.MethodPut, srv.URL+"/oversized-key", strings.NewReader("12345"))
if err != nil {
t.Fatalf("failed to create PUT request: %v", err)
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatalf("PUT request failed: %v", err)
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != http.StatusRequestEntityTooLarge {
t.Fatalf("PUT status = %d, want %d", resp.StatusCode, http.StatusRequestEntityTooLarge)
}
}
func TestGradleBuildCacheHandler_RecordsMetrics(t *testing.T) {
proxy, _, _, _ := setupTestProxy(t)
h := NewGradleBuildCacheHandler(proxy)
srv := httptest.NewServer(h.Routes())
defer srv.Close()
hitsBefore := testutil.ToFloat64(metrics.CacheHits.WithLabelValues("gradle"))
missesBefore := testutil.ToFloat64(metrics.CacheMisses.WithLabelValues("gradle"))
key := "metrics-key"
putReq, err := http.NewRequest(http.MethodPut, srv.URL+"/"+key, strings.NewReader("payload"))
if err != nil {
t.Fatalf("failed to create PUT request: %v", err)
}
putResp, err := http.DefaultClient.Do(putReq)
if err != nil {
t.Fatalf("PUT request failed: %v", err)
}
_ = putResp.Body.Close()
getResp, err := http.Get(srv.URL + "/" + key)
if err != nil {
t.Fatalf("GET request failed: %v", err)
}
_ = getResp.Body.Close()
headReq, err := http.NewRequest(http.MethodHead, srv.URL+"/"+key, nil)
if err != nil {
t.Fatalf("failed to create HEAD request: %v", err)
}
headResp, err := http.DefaultClient.Do(headReq)
if err != nil {
t.Fatalf("HEAD request failed: %v", err)
}
_ = headResp.Body.Close()
missResp, err := http.Get(srv.URL + "/missing-key")
if err != nil {
t.Fatalf("GET miss request failed: %v", err)
}
_ = missResp.Body.Close()
hitsAfter := testutil.ToFloat64(metrics.CacheHits.WithLabelValues("gradle"))
missesAfter := testutil.ToFloat64(metrics.CacheMisses.WithLabelValues("gradle"))
if diff := hitsAfter - hitsBefore; diff != 2 {
t.Fatalf("cache hits delta = %.0f, want 2", diff)
}
if diff := missesAfter - missesBefore; diff != 1 {
t.Fatalf("cache misses delta = %.0f, want 1", diff)
}
}

View file

@ -2,21 +2,14 @@
package handler package handler
import ( import (
"bytes"
"context" "context"
"database/sql" "database/sql"
"errors"
"fmt" "fmt"
"io" "io"
"log/slog" "log/slog"
"net/http" "net/http"
"net/url"
"strconv"
"strings"
"sync"
"time" "time"
"github.com/git-pkgs/cooldown"
"github.com/git-pkgs/proxy/internal/database" "github.com/git-pkgs/proxy/internal/database"
"github.com/git-pkgs/proxy/internal/metrics" "github.com/git-pkgs/proxy/internal/metrics"
"github.com/git-pkgs/proxy/internal/storage" "github.com/git-pkgs/proxy/internal/storage"
@ -24,95 +17,13 @@ import (
"github.com/git-pkgs/registries/fetch" "github.com/git-pkgs/registries/fetch"
) )
// containsPathTraversal returns true if the path contains ".." segments
// that could be used to escape the intended directory. It checks the path
// as given and after URL-decoding, and treats backslashes as separators.
func containsPathTraversal(path string) bool {
if hasDotDotSegment(path) {
return true
}
if decoded, err := url.PathUnescape(path); err == nil && decoded != path {
return hasDotDotSegment(decoded)
}
return false
}
func hasDotDotSegment(path string) bool {
path = strings.ReplaceAll(path, "\\", "/")
for segment := range strings.SplitSeq(path, "/") {
if segment == ".." {
return true
}
}
return false
}
const defaultHTTPTimeout = 30 * time.Second
const artifactCopyBufferSize = 32 << 10
var artifactCopyBufferPool = sync.Pool{ //nolint:gochecknoglobals // shared across artifact responses
New: func() any {
buffer := make([]byte, artifactCopyBufferSize)
return &buffer
},
}
// canonicalPackagePURL returns a versionless PURL in canonical form so cooldown
// lookups match keys produced by config.CooldownConfig.NormalizedPackages.
func canonicalPackagePURL(ecosystem, name string) string {
return purl.MakePURLString(ecosystem, name, "")
}
const contentTypeJSON = "application/json"
const headerAcceptEncoding = "Accept-Encoding"
// defaultMetadataMaxSize is used when Proxy.MetadataMaxSize is unset.
const defaultMetadataMaxSize = 100 << 20
// ErrMetadataTooLarge is returned when upstream metadata exceeds the configured limit.
var ErrMetadataTooLarge = errors.New("metadata response exceeds size limit")
// ReadMetadata reads an upstream response body with a size limit to prevent OOM
// from unexpectedly large responses. Returns ErrMetadataTooLarge if the response
// is truncated by the limit.
func (p *Proxy) ReadMetadata(r io.Reader) ([]byte, error) {
limit := p.MetadataMaxSize
if limit <= 0 {
limit = defaultMetadataMaxSize
}
data, err := io.ReadAll(io.LimitReader(r, limit+1))
if err != nil {
return nil, err
}
if int64(len(data)) > limit {
return nil, ErrMetadataTooLarge
}
return data, nil
}
// Proxy provides shared functionality for protocol handlers. // Proxy provides shared functionality for protocol handlers.
type Proxy struct { type Proxy struct {
DB *database.DB DB *database.DB
Storage storage.Storage Storage storage.Storage
Fetcher fetch.FetcherInterface Fetcher fetch.FetcherInterface
Resolver *fetch.Resolver Resolver *fetch.Resolver
Logger *slog.Logger Logger *slog.Logger
Cooldown *cooldown.Config
CacheMetadata bool
MetadataTTL time.Duration
MetadataMaxSize int64
GradleReadOnly bool
GradleMaxUploadSize int64
DirectServe bool
DirectServeTTL time.Duration
// DirectServeBaseURL, if set, replaces the scheme and host of presigned
// URLs so clients receive a public address even when the proxy reaches
// storage at an internal one.
DirectServeBaseURL string
HTTPClient *http.Client
AuthForURL func(string) (headerName, headerValue string)
} }
// NewProxy creates a new Proxy with the given dependencies. // NewProxy creates a new Proxy with the given dependencies.
@ -126,16 +37,12 @@ func NewProxy(db *database.DB, store storage.Storage, fetcher fetch.FetcherInter
Fetcher: fetcher, Fetcher: fetcher,
Resolver: resolver, Resolver: resolver,
Logger: logger, Logger: logger,
HTTPClient: &http.Client{
Timeout: defaultHTTPTimeout,
},
} }
} }
// CacheResult contains information about a cached or fetched artifact. // CacheResult contains information about a cached or fetched artifact.
type CacheResult struct { type CacheResult struct {
Reader io.ReadCloser Reader io.ReadCloser
RedirectURL string
Size int64 Size int64
ContentType string ContentType string
Hash string Hash string
@ -144,153 +51,77 @@ type CacheResult struct {
// GetOrFetchArtifact retrieves an artifact from cache or fetches from upstream. // GetOrFetchArtifact retrieves an artifact from cache or fetches from upstream.
func (p *Proxy) GetOrFetchArtifact(ctx context.Context, ecosystem, name, version, filename string) (*CacheResult, error) { func (p *Proxy) GetOrFetchArtifact(ctx context.Context, ecosystem, name, version, filename string) (*CacheResult, error) {
if cached, err := p.GetCachedArtifact(ctx, ecosystem, name, version, filename); err != nil { pkgPURL := purl.MakePURLString(ecosystem, name, "")
versionPURL := purl.MakePURLString(ecosystem, name, version)
if cached, err := p.checkCache(ctx, pkgPURL, versionPURL, filename); err != nil {
return nil, err return nil, err
} else if cached != nil { } else if cached != nil {
return cached, nil return cached, nil
} }
metrics.RecordCacheMiss(ecosystem)
pkgPURL := purl.MakePURLString(ecosystem, name, "")
versionPURL := purl.MakePURLString(ecosystem, name, version)
return p.fetchAndCache(ctx, ecosystem, name, version, filename, pkgPURL, versionPURL) return p.fetchAndCache(ctx, ecosystem, name, version, filename, pkgPURL, versionPURL)
} }
// GetCachedArtifact retrieves an artifact from cache without contacting an upstream.
// It returns nil when no usable cache entry exists.
func (p *Proxy) GetCachedArtifact(ctx context.Context, ecosystem, name, version, filename string) (*CacheResult, error) {
pkgPURL := purl.MakePURLString(ecosystem, name, "")
versionPURL := purl.MakePURLString(ecosystem, name, version)
return p.checkCache(ctx, pkgPURL, versionPURL, filename)
}
// ClearCachedArtifact removes both an artifact cache record and its stored
// bytes after an external integrity check fails.
func (p *Proxy) ClearCachedArtifact(ctx context.Context, ecosystem, name, version, filename string) error {
if p.DB == nil || p.Storage == nil {
return nil
}
pkgPURL := purl.MakePURLString(ecosystem, name, "")
versionPURL := purl.MakePURLString(ecosystem, name, version)
cached, err := p.DB.GetCachedArtifact(pkgPURL, versionPURL, filename)
if err != nil {
return fmt.Errorf("looking up cached artifact: %w", err)
}
if cached == nil {
return nil
}
if err := p.Storage.Delete(ctx, cached.StoragePath); err != nil {
return fmt.Errorf("deleting cached artifact: %w", err)
}
return p.DB.ClearArtifactCache(versionPURL, filename)
}
// checkCache looks up an artifact in the cache. Returns nil if not cached. // checkCache looks up an artifact in the cache. Returns nil if not cached.
func (p *Proxy) checkCache(ctx context.Context, pkgPURL, versionPURL, filename string) (*CacheResult, error) { func (p *Proxy) checkCache(ctx context.Context, pkgPURL, versionPURL, filename string) (*CacheResult, error) {
artifact, err := p.DB.GetCachedArtifact(pkgPURL, versionPURL, filename) pkg, err := p.DB.GetPackageByPURL(pkgPURL)
if err != nil {
return nil, fmt.Errorf("checking package cache: %w", err)
}
if pkg == nil {
return nil, nil
}
ver, err := p.DB.GetVersionByPURL(versionPURL)
if err != nil {
return nil, fmt.Errorf("checking version cache: %w", err)
}
if ver == nil {
return nil, nil
}
artifact, err := p.DB.GetArtifact(versionPURL, filename)
if err != nil { if err != nil {
return nil, fmt.Errorf("checking artifact cache: %w", err) return nil, fmt.Errorf("checking artifact cache: %w", err)
} }
if artifact == nil { if artifact == nil || !artifact.IsCached() {
return nil, nil return nil, nil
} }
checks, err := newIntegrityChecks(artifact.ContentHash.String, artifact.Integrity.String)
if err != nil {
p.rejectUnusableCacheRecord(artifact, versionPURL, filename, err)
return nil, nil
}
result := &CacheResult{
Size: artifact.Size.Int64,
ContentType: artifact.ContentType.String,
Hash: artifact.ContentHash.String,
Cached: true,
}
if p.DirectServe {
signed, err := p.Storage.SignedURL(ctx, artifact.StoragePath, p.DirectServeTTL)
if err == nil {
result.RedirectURL = rewriteSignedURLHost(signed, p.DirectServeBaseURL)
p.recordCacheHit(artifact.Ecosystem, versionPURL, filename)
return result, nil
}
if !errors.Is(err, storage.ErrSignedURLUnsupported) {
p.Logger.Warn("failed to sign storage URL, falling back to streaming",
"path", artifact.StoragePath, "error", err)
}
}
start := time.Now() start := time.Now()
reader, err := p.Storage.Open(ctx, artifact.StoragePath) reader, err := p.Storage.Open(ctx, artifact.StoragePath.String)
metrics.RecordStorageOperation("read", time.Since(start)) metrics.RecordStorageOperation("read", time.Since(start))
if err != nil { if err != nil {
metrics.RecordStorageError("read") metrics.RecordStorageError("read")
p.Logger.Warn("cached artifact missing from storage, will refetch", p.Logger.Warn("cached artifact missing from storage, will refetch",
"path", artifact.StoragePath, "error", err) "path", artifact.StoragePath.String, "error", err)
return nil, nil return nil, nil
} }
result.Reader, err = checks.wrap(reader,
func(reason string) {
p.Logger.Error("cached artifact failed integrity check",
"purl", versionPURL, "filename", filename,
"path", artifact.StoragePath, "reason", reason)
metrics.RecordIntegrityFailure(purl.NormalizeEcosystem(artifact.Ecosystem))
if err := p.DB.ClearArtifactCache(versionPURL, filename); err != nil {
p.Logger.Warn("failed to clear corrupt artifact from cache", "error", err)
}
})
if err != nil {
_ = reader.Close()
p.rejectUnusableCacheRecord(artifact, versionPURL, filename, err)
return nil, nil
}
p.recordCacheHit(artifact.Ecosystem, versionPURL, filename)
return result, nil
}
// rewriteSignedURLHost replaces the scheme and host of a signed URL with those
// from baseURL, preserving the path and query (which carry the signature).
// Returns signed unchanged if baseURL is empty or either URL fails to parse.
func rewriteSignedURLHost(signed, baseURL string) string {
if baseURL == "" {
return signed
}
s, err := url.Parse(signed)
if err != nil {
return signed
}
b, err := url.Parse(baseURL)
if err != nil || b.Scheme == "" || b.Host == "" {
return signed
}
s.Scheme = b.Scheme
s.Host = b.Host
return s.String()
}
func (p *Proxy) recordCacheHit(ecosystem, versionPURL, filename string) {
_ = p.DB.RecordArtifactHit(versionPURL, filename) _ = p.DB.RecordArtifactHit(versionPURL, filename)
metrics.RecordCacheHit(ecosystem)
}
func (p *Proxy) rejectUnusableCacheRecord(artifact *database.CachedArtifact, versionPURL, filename string, cause error) { // Extract ecosystem from pkgPURL for metrics
p.Logger.Warn("cached artifact has unusable integrity metadata", if p, err := purl.Parse(pkgPURL); err == nil {
"purl", versionPURL, "filename", filename, metrics.RecordCacheHit(purl.PURLTypeToEcosystem(p.Type))
"path", artifact.StoragePath, "error", cause)
metrics.RecordIntegrityFailure(purl.NormalizeEcosystem(artifact.Ecosystem))
if err := p.DB.ClearArtifactCache(versionPURL, filename); err != nil {
p.Logger.Warn("failed to clear unusable artifact from cache", "error", err)
} }
return &CacheResult{
Reader: reader,
Size: artifact.Size.Int64,
ContentType: artifact.ContentType.String,
Hash: artifact.ContentHash.String,
Cached: true,
}, nil
} }
func (p *Proxy) fetchAndCache(ctx context.Context, ecosystem, name, version, filename, pkgPURL, versionPURL string) (*CacheResult, error) { func (p *Proxy) fetchAndCache(ctx context.Context, ecosystem, name, version, filename, pkgPURL, versionPURL string) (*CacheResult, error) {
// Record cache miss
metrics.RecordCacheMiss(ecosystem)
// Resolve download URL // Resolve download URL
info, err := p.Resolver.Resolve(ctx, ecosystem, name, version) info, err := p.Resolver.Resolve(ctx, ecosystem, name, version)
if err != nil { if err != nil {
if errors.Is(err, fetch.ErrNotFound) {
return nil, ErrUpstreamNotFound
}
return nil, fmt.Errorf("resolving download URL: %w", err) return nil, fmt.Errorf("resolving download URL: %w", err)
} }
@ -310,9 +141,6 @@ func (p *Proxy) fetchAndCache(ctx context.Context, ecosystem, name, version, fil
if err != nil { if err != nil {
metrics.RecordUpstreamFetch(ecosystem, fetchDuration) metrics.RecordUpstreamFetch(ecosystem, fetchDuration)
metrics.RecordUpstreamError(ecosystem, "fetch_failed") metrics.RecordUpstreamError(ecosystem, "fetch_failed")
if errors.Is(err, fetch.ErrNotFound) {
return nil, ErrUpstreamNotFound
}
return nil, fmt.Errorf("fetching from upstream: %w", err) return nil, fmt.Errorf("fetching from upstream: %w", err)
} }
metrics.RecordUpstreamFetch(ecosystem, fetchDuration) metrics.RecordUpstreamFetch(ecosystem, fetchDuration)
@ -330,7 +158,7 @@ func (p *Proxy) fetchAndCache(ctx context.Context, ecosystem, name, version, fil
} }
// Update database // Update database
if err := p.updateCacheDB(ecosystem, name, filename, pkgPURL, versionPURL, info.URL, storagePath, hash, size, artifact.ContentType); err != nil { if err := p.updateCacheDB(ctx, ecosystem, name, version, filename, pkgPURL, versionPURL, info.URL, storagePath, hash, size, artifact.ContentType); err != nil {
p.Logger.Warn("failed to update cache database", "error", err) p.Logger.Warn("failed to update cache database", "error", err)
// Continue anyway - we have the file // Continue anyway - we have the file
} }
@ -354,16 +182,16 @@ func (p *Proxy) fetchAndCache(ctx context.Context, ecosystem, name, version, fil
}, nil }, nil
} }
func (p *Proxy) updateCacheDB(ecosystem, name, filename, pkgPURL, versionPURL, upstreamURL, storagePath, hash string, size int64, contentType string) error { func (p *Proxy) updateCacheDB(ctx context.Context, ecosystem, name, version, filename, pkgPURL, versionPURL, upstreamURL, storagePath, hash string, size int64, contentType string) error {
now := time.Now() now := time.Now()
// Upsert package // Upsert package
pkg := &database.Package{ pkg := &database.Package{
PURL: pkgPURL, PURL: pkgPURL,
Ecosystem: ecosystem, Ecosystem: ecosystem,
Name: name, Name: name,
RegistryURL: sql.NullString{String: upstreamURL, Valid: true}, RegistryURL: sql.NullString{String: upstreamURL, Valid: true},
EnrichedAt: sql.NullTime{Time: now, Valid: true}, EnrichedAt: sql.NullTime{Time: now, Valid: true},
} }
if err := p.DB.UpsertPackage(pkg); err != nil { if err := p.DB.UpsertPackage(pkg); err != nil {
return fmt.Errorf("upserting package: %w", err) return fmt.Errorf("upserting package: %w", err)
@ -399,492 +227,50 @@ func (p *Proxy) updateCacheDB(ecosystem, name, filename, pkgPURL, versionPURL, u
// ServeArtifact writes a CacheResult to an HTTP response. // ServeArtifact writes a CacheResult to an HTTP response.
func ServeArtifact(w http.ResponseWriter, result *CacheResult) { func ServeArtifact(w http.ResponseWriter, result *CacheResult) {
serveArtifact(w, http.MethodGet, result) defer func() { _ = result.Reader.Close() }()
}
func serveArtifact(w http.ResponseWriter, method string, result *CacheResult) {
if result.RedirectURL != "" {
if result.Hash != "" {
w.Header().Set("ETag", `"`+result.Hash+`"`)
}
w.Header().Set("Location", result.RedirectURL)
w.WriteHeader(http.StatusFound)
return
}
if result.Reader != nil {
defer func() { _ = result.Reader.Close() }()
}
if result.ContentType != "" { if result.ContentType != "" {
w.Header().Set("Content-Type", result.ContentType) w.Header().Set("Content-Type", result.ContentType)
} }
if result.Size > 0 || (method == http.MethodHead && result.Size == 0) { if result.Size > 0 {
w.Header().Set("Content-Length", strconv.FormatInt(result.Size, 10)) w.Header().Set("Content-Length", fmt.Sprintf("%d", result.Size))
} }
if result.Hash != "" { if result.Hash != "" {
w.Header().Set("ETag", `"`+result.Hash+`"`) w.Header().Set("ETag", fmt.Sprintf(`"%s"`, result.Hash))
} }
w.WriteHeader(http.StatusOK) w.WriteHeader(http.StatusOK)
if method != http.MethodHead && result.Reader != nil { _, _ = io.Copy(w, result.Reader)
buffer := artifactCopyBufferPool.Get().(*[]byte)
defer artifactCopyBufferPool.Put(buffer)
// Hide optional ReaderFrom methods so io.CopyBuffer uses the pooled buffer.
_, _ = io.CopyBuffer(struct{ io.Writer }{w}, result.Reader, *buffer)
}
}
// ProxyUpstream forwards a request to an upstream URL without caching.
// It copies the request, forwards specified headers, and streams the response back.
// If forwardHeaders is nil, all response headers are copied.
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
}
// Copy request headers that affect content negotiation / caching
for _, header := range forwardHeaders {
if v := r.Header.Get(header); v != "" {
req.Header.Set(header, v)
}
}
p.applyUpstreamAuth(req)
resp, err := p.HTTPClient.Do(req)
if err != nil {
p.Logger.Error("upstream request failed", "error", err)
http.Error(w, "upstream request failed", http.StatusBadGateway)
return
}
defer func() { _ = resp.Body.Close() }()
for k, vv := range resp.Header {
for _, v := range vv {
w.Header().Add(k, v)
}
}
w.WriteHeader(resp.StatusCode)
_, _ = io.Copy(w, resp.Body)
}
// ProxyFile forwards a file request to upstream, copying all response headers.
func (p *Proxy) ProxyFile(w http.ResponseWriter, r *http.Request, upstreamURL string) {
req, err := http.NewRequestWithContext(r.Context(), r.Method, upstreamURL, nil)
if err != nil {
http.Error(w, "failed to create request", http.StatusInternalServerError)
return
}
p.applyUpstreamAuth(req)
resp, err := p.HTTPClient.Do(req)
if err != nil {
http.Error(w, "failed to fetch from upstream", http.StatusBadGateway)
return
}
defer func() { _ = resp.Body.Close() }()
for key, values := range resp.Header {
for _, v := range values {
w.Header().Add(key, v)
}
}
w.WriteHeader(resp.StatusCode)
_, _ = io.Copy(w, resp.Body)
} }
// JSONError writes a JSON error response. // JSONError writes a JSON error response.
func JSONError(w http.ResponseWriter, status int, message string) { func JSONError(w http.ResponseWriter, status int, message string) {
w.Header().Set("Content-Type", contentTypeJSON) w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status) w.WriteHeader(status)
_, _ = fmt.Fprintf(w, `{"error":%q}`, message) _, _ = fmt.Fprintf(w, `{"error":%q}`, message)
} }
// ErrUpstreamNotFound indicates the upstream returned 404.
var ErrUpstreamNotFound = fmt.Errorf("upstream: %w", fetch.ErrNotFound)
// serveArtifactError writes response for a failed fetch:
// 404 when upstream reports artifact missing, 502 otherwise.
func (p *Proxy) serveArtifactError(w http.ResponseWriter, err error, clientMsg string) {
if errors.Is(err, ErrUpstreamNotFound) {
http.Error(w, "not found", http.StatusNotFound)
return
}
p.Logger.Error("failed to get artifact", "error", err)
http.Error(w, clientMsg, http.StatusBadGateway)
}
// 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) {
if containsPathTraversal(cacheKey) {
return nil, "", fmt.Errorf("invalid cache key: %q", cacheKey)
}
storagePath := metadataStoragePath(ecosystem, cacheKey)
// Check for existing cache entry (for ETag revalidation and TTL)
var entry *database.MetadataCacheEntry
if p.CacheMetadata && p.DB != nil {
entry, _ = p.DB.GetMetadataCache(ecosystem, cacheKey)
}
// Serve from cache if within TTL (skip upstream entirely)
if entry != nil && p.MetadataTTL > 0 && entry.FetchedAt.Valid {
if time.Since(entry.FetchedAt.Time) < p.MetadataTTL {
cached, readErr := p.Storage.Open(ctx, entry.StoragePath)
if readErr == nil {
defer func() { _ = cached.Close() }()
data, readErr := p.ReadMetadata(cached)
if readErr == nil {
ct := contentTypeJSON
if entry.ContentType.Valid {
ct = entry.ContentType.String
}
metrics.RecordCacheHit(ecosystem)
return data, ct, nil
}
}
// Cache file missing/unreadable, fall through to upstream
}
}
p.recordMetadataCacheMiss(ecosystem)
accept := contentTypeJSON
if len(acceptHeaders) > 0 && acceptHeaders[0] != "" {
accept = acceptHeaders[0]
}
// Try upstream
body, contentType, etag, lastModified, err := p.fetchUpstreamMetadata(ctx, upstreamURL, entry, accept)
if errors.Is(err, errStale304) {
// 304 but cached file is gone; retry without ETag
body, contentType, etag, lastModified, err = p.fetchUpstreamMetadata(ctx, upstreamURL, nil, accept)
}
if err == nil {
if p.CacheMetadata {
p.cacheMetadataBlob(ctx, ecosystem, cacheKey, storagePath, body, contentType, etag, lastModified)
}
return body, contentType, nil
}
// Upstream failed -- fall back to cache if available
if !p.CacheMetadata || entry == nil {
return nil, "", fmt.Errorf("upstream failed and no cached metadata: %w", err)
}
p.Logger.Warn("upstream metadata fetch failed, checking cache",
"ecosystem", ecosystem, "key", cacheKey, "error", err)
cached, readErr := p.Storage.Open(ctx, entry.StoragePath)
if readErr != nil {
return nil, "", fmt.Errorf("upstream failed and cached file missing: %w", err)
}
defer func() { _ = cached.Close() }()
data, readErr := p.ReadMetadata(cached)
if readErr != nil {
return nil, "", fmt.Errorf("upstream failed and cached read error: %w", err)
}
ct := contentTypeJSON
if entry.ContentType.Valid {
ct = entry.ContentType.String
}
p.Logger.Info("serving metadata from cache",
"ecosystem", ecosystem, "key", cacheKey)
return data, ct, nil
}
func (p *Proxy) recordMetadataCacheMiss(ecosystem string) {
if p.CacheMetadata {
metrics.RecordCacheMiss(ecosystem)
}
}
// fetchUpstreamMetadata fetches metadata from upstream, using ETag for conditional revalidation.
// Returns the body, content type, ETag, upstream Last-Modified time, and any error.
func (p *Proxy) fetchUpstreamMetadata(ctx context.Context, upstreamURL string, entry *database.MetadataCacheEntry, accept string) ([]byte, string, string, time.Time, error) {
var zeroTime time.Time
req, err := http.NewRequestWithContext(ctx, http.MethodGet, upstreamURL, nil)
if err != nil {
return nil, "", "", zeroTime, fmt.Errorf("creating request: %w", err)
}
req.Header.Set("Accept", accept)
p.applyUpstreamAuth(req)
if entry != nil && entry.ETag.Valid {
req.Header.Set("If-None-Match", entry.ETag.String)
}
resp, err := p.HTTPClient.Do(req)
if err != nil {
return nil, "", "", zeroTime, fmt.Errorf("fetching metadata: %w", 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, "", "", zeroTime, errStale304
}
defer func() { _ = cached.Close() }()
data, readErr := p.ReadMetadata(cached)
if readErr != nil {
return nil, "", "", zeroTime, errStale304
}
ct := contentTypeJSON
if entry.ContentType.Valid {
ct = entry.ContentType.String
}
lm := zeroTime
if entry.LastModified.Valid {
lm = entry.LastModified.Time
}
return data, ct, entry.ETag.String, lm, nil
}
if resp.StatusCode == http.StatusNotFound {
return nil, "", "", zeroTime, ErrUpstreamNotFound
}
if resp.StatusCode != http.StatusOK {
return nil, "", "", zeroTime, fmt.Errorf("upstream returned %d", resp.StatusCode)
}
body, err := p.ReadMetadata(resp.Body)
if err != nil {
return nil, "", "", zeroTime, fmt.Errorf("reading response: %w", err)
}
contentType := resp.Header.Get("Content-Type")
if contentType == "" {
contentType = contentTypeJSON
}
etag := resp.Header.Get("ETag")
var lastModified time.Time
if lm := resp.Header.Get("Last-Modified"); lm != "" {
lastModified, _ = http.ParseTime(lm)
}
return body, contentType, etag, lastModified, nil
}
// cacheMetadataBlob stores metadata bytes in storage and updates the database.
func (p *Proxy) cacheMetadataBlob(ctx context.Context, ecosystem, cacheKey, storagePath string, data []byte, contentType, etag string, lastModified time.Time) {
if p.DB == nil || p.Storage == nil {
return
}
size, _, err := p.Storage.Store(ctx, storagePath, bytes.NewReader(data))
if err != nil {
p.Logger.Warn("failed to cache metadata", "ecosystem", ecosystem, "key", cacheKey, "error", err)
return
}
_ = p.DB.UpsertMetadataCache(&database.MetadataCacheEntry{
Ecosystem: ecosystem,
Name: cacheKey,
StoragePath: storagePath,
ETag: sql.NullString{String: etag, Valid: etag != ""},
ContentType: sql.NullString{String: contentType, Valid: contentType != ""},
Size: sql.NullInt64{Int64: size, Valid: true},
LastModified: sql.NullTime{Time: lastModified, Valid: !lastModified.IsZero()},
FetchedAt: sql.NullTime{Time: time.Now(), Valid: true},
})
}
// cachedMeta holds cache validators and freshness state from a metadata cache entry.
type cachedMeta struct {
etag string
lastModified time.Time
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{}
}
var cm cachedMeta
if entry.ETag.Valid {
cm.etag = entry.ETag.String
}
if entry.LastModified.Valid {
cm.lastModified = entry.LastModified.Time
}
// If FetchedAt is older than TTL, upstream must have failed and
// we served from stale cache (successful fetches update FetchedAt).
if p.MetadataTTL > 0 && entry.FetchedAt.Valid && time.Since(entry.FetchedAt.Time) > p.MetadataTTL {
cm.stale = true
}
return cm
}
// ProxyCached fetches metadata from upstream (with optional caching for offline fallback)
// and writes it to the response. Optional acceptHeaders specify the Accept header to send.
// 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) {
if !p.CacheMetadata {
// Stream directly without buffering when caching is off.
p.proxyMetadataStream(w, r, upstreamURL, acceptHeaders...)
return
}
body, contentType, err := p.FetchOrCacheMetadata(r.Context(), ecosystem, cacheKey, upstreamURL, acceptHeaders...)
if err != nil {
if errors.Is(err, ErrUpstreamNotFound) {
http.Error(w, "not found", http.StatusNotFound)
return
}
p.Logger.Error("metadata fetch failed", "error", err)
http.Error(w, "failed to fetch from upstream", http.StatusBadGateway)
return
}
p.writeMetadataCachedResponse(w, r, ecosystem, cacheKey, body, contentType)
}
// 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) {
cm := p.lookupCachedMeta(ecosystem, cacheKey)
if cm.etag != "" {
if match := r.Header.Get("If-None-Match"); match != "" && match == cm.etag {
w.WriteHeader(http.StatusNotModified)
return
}
}
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
}
}
}
w.Header().Set("Content-Type", contentType)
w.Header().Set("Content-Length", strconv.Itoa(len(body)))
if cm.etag != "" {
w.Header().Set("ETag", cm.etag)
}
if !cm.lastModified.IsZero() {
w.Header().Set("Last-Modified", cm.lastModified.UTC().Format(http.TimeFormat))
}
if cm.stale {
w.Header().Set("Warning", `110 - "Response is Stale"`)
}
w.WriteHeader(http.StatusOK)
_, _ = w.Write(body)
}
// proxyMetadataStream forwards an upstream metadata response by streaming it to the client
// without buffering the full body in memory.
func (p *Proxy) proxyMetadataStream(w http.ResponseWriter, r *http.Request, upstreamURL string, acceptHeaders ...string) {
req, err := http.NewRequestWithContext(r.Context(), http.MethodGet, upstreamURL, nil)
if err != nil {
http.Error(w, "failed to create request", http.StatusInternalServerError)
return
}
accept := contentTypeJSON
if len(acceptHeaders) > 0 && acceptHeaders[0] != "" {
accept = acceptHeaders[0]
}
req.Header.Set("Accept", accept)
p.applyUpstreamAuth(req)
for _, header := range []string{headerAcceptEncoding, "If-Modified-Since", "If-None-Match"} {
if v := r.Header.Get(header); v != "" {
req.Header.Set(header, v)
}
}
resp, err := p.HTTPClient.Do(req)
if err != nil {
http.Error(w, "failed to fetch from upstream", http.StatusBadGateway)
return
}
defer func() { _ = resp.Body.Close() }()
for _, header := range []string{"Content-Type", "Content-Length", "Last-Modified", "ETag"} {
if v := resp.Header.Get(header); v != "" {
w.Header().Set(header, v)
}
}
w.WriteHeader(resp.StatusCode)
_, _ = io.Copy(w, resp.Body)
}
func (p *Proxy) applyUpstreamAuth(req *http.Request) {
if p.AuthForURL == nil {
return
}
headerName, headerValue := p.AuthForURL(req.URL.String())
if headerName != "" && headerValue != "" {
req.Header.Set(headerName, headerValue)
}
}
// GetOrFetchArtifactFromURL retrieves an artifact from cache or fetches from a specific URL. // GetOrFetchArtifactFromURL retrieves an artifact from cache or fetches from a specific URL.
// This is useful for registries where download URLs are determined from metadata. // This is useful for registries where download URLs are determined from metadata.
func (p *Proxy) GetOrFetchArtifactFromURL(ctx context.Context, ecosystem, name, version, filename, downloadURL string) (*CacheResult, error) { func (p *Proxy) GetOrFetchArtifactFromURL(ctx context.Context, ecosystem, name, version, filename, downloadURL string) (*CacheResult, error) {
return p.GetOrFetchArtifactFromURLWithHeaders(ctx, ecosystem, name, version, filename, downloadURL, nil) pkgPURL := purl.MakePURLString(ecosystem, name, "")
} versionPURL := purl.MakePURLString(ecosystem, name, version)
// GetOrFetchArtifactFromURLWithHeaders retrieves an artifact from cache or fetches from a URL if cached, err := p.checkCache(ctx, pkgPURL, versionPURL, filename); err != nil {
// with additional request-specific HTTP headers.
func (p *Proxy) GetOrFetchArtifactFromURLWithHeaders(ctx context.Context, ecosystem, name, version, filename, downloadURL string, headers http.Header) (*CacheResult, error) {
if cached, err := p.GetCachedArtifact(ctx, ecosystem, name, version, filename); err != nil {
return nil, err return nil, err
} else if cached != nil { } else if cached != nil {
return cached, nil return cached, nil
} }
metrics.RecordCacheMiss(ecosystem)
pkgPURL := purl.MakePURLString(ecosystem, name, "") return p.fetchAndCacheFromURL(ctx, ecosystem, name, version, filename, pkgPURL, versionPURL, downloadURL)
versionPURL := purl.MakePURLString(ecosystem, name, version)
return p.fetchAndCacheFromURL(ctx, ecosystem, name, version, filename, pkgPURL, versionPURL, downloadURL, headers)
} }
func (p *Proxy) fetchAndCacheFromURL(ctx context.Context, ecosystem, name, version, filename, pkgPURL, versionPURL, downloadURL string, headers http.Header) (*CacheResult, error) { func (p *Proxy) fetchAndCacheFromURL(ctx context.Context, ecosystem, name, version, filename, pkgPURL, versionPURL, downloadURL string) (*CacheResult, error) {
p.Logger.Info("fetching from upstream", p.Logger.Info("fetching from upstream",
"ecosystem", ecosystem, "name", name, "version", version, "url", downloadURL) "ecosystem", ecosystem, "name", name, "version", version, "url", downloadURL)
artifact, err := p.Fetcher.FetchWithHeaders(ctx, downloadURL, headers) artifact, err := p.Fetcher.Fetch(ctx, downloadURL)
if err != nil { if err != nil {
if errors.Is(err, fetch.ErrNotFound) {
return nil, ErrUpstreamNotFound
}
return nil, fmt.Errorf("fetching from upstream: %w", err) return nil, fmt.Errorf("fetching from upstream: %w", err)
} }
@ -895,7 +281,7 @@ func (p *Proxy) fetchAndCacheFromURL(ctx context.Context, ecosystem, name, versi
return nil, fmt.Errorf("storing artifact: %w", err) return nil, fmt.Errorf("storing artifact: %w", err)
} }
if err := p.updateCacheDB(ecosystem, name, filename, pkgPURL, versionPURL, downloadURL, storagePath, hash, size, artifact.ContentType); err != nil { if err := p.updateCacheDB(ctx, ecosystem, name, version, filename, pkgPURL, versionPURL, downloadURL, storagePath, hash, size, artifact.ContentType); err != nil {
p.Logger.Warn("failed to update cache database", "error", err) p.Logger.Warn("failed to update cache database", "error", err)
} }
@ -912,3 +298,4 @@ func (p *Proxy) fetchAndCacheFromURL(ctx context.Context, ecosystem, name, versi
Cached: false, Cached: false,
}, nil }, nil
} }

View file

@ -1,300 +0,0 @@
package handler
import (
"bytes"
"context"
"crypto/sha256"
"database/sql"
"encoding/hex"
"fmt"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"path/filepath"
"strings"
"testing"
"time"
"github.com/git-pkgs/proxy/internal/database"
"github.com/git-pkgs/proxy/internal/storage"
"github.com/git-pkgs/purl"
"github.com/git-pkgs/registries/fetch"
)
const benchmarkArtifactSize = 64 << 10
const benchmarkMetadataSize = 1 << 20
type benchmarkResponseWriter struct {
header http.Header
}
func (w *benchmarkResponseWriter) Header() http.Header {
return w.header
}
func (w *benchmarkResponseWriter) Write(p []byte) (int, error) {
return len(p), nil
}
func (w *benchmarkResponseWriter) WriteHeader(_ int) {}
func benchmarkCachedProxy(b *testing.B) (*Proxy, *mockStorage) {
b.Helper()
proxy, db, store, _ := setupTestProxy(b)
content := strings.Repeat("x", benchmarkArtifactSize)
seedPackage(b, db, store, "npm", "lodash", "4.17.21", "lodash-4.17.21.tgz", content)
artifact, err := db.GetArtifact("pkg:npm/lodash@4.17.21", "lodash-4.17.21.tgz")
if err != nil {
b.Fatalf("get seeded artifact: %v", err)
}
sum := sha256.Sum256([]byte(content))
artifact.ContentHash.String = hex.EncodeToString(sum[:])
if err := db.UpsertArtifact(artifact); err != nil {
b.Fatalf("update seeded artifact hash: %v", err)
}
return proxy, store
}
func BenchmarkArtifactCacheHit(b *testing.B) {
ctx := context.Background()
b.Run("stream-64KiB", func(b *testing.B) {
proxy, _ := benchmarkCachedProxy(b)
w := &benchmarkResponseWriter{header: make(http.Header)}
b.SetBytes(benchmarkArtifactSize)
b.ReportAllocs()
b.ResetTimer()
for b.Loop() {
result, err := proxy.GetOrFetchArtifact(ctx, "npm", "lodash", "4.17.21", "lodash-4.17.21.tgz")
if err != nil {
b.Fatal(err)
}
ServeArtifact(w, result)
}
})
b.Run("direct-serve", func(b *testing.B) {
proxy, store := benchmarkCachedProxy(b)
proxy.DirectServe = true
store.signedURL = "https://storage.example/npm/lodash-4.17.21.tgz?signature=abc"
w := &benchmarkResponseWriter{header: make(http.Header)}
b.ReportAllocs()
b.ResetTimer()
for b.Loop() {
result, err := proxy.GetOrFetchArtifact(ctx, "npm", "lodash", "4.17.21", "lodash-4.17.21.tgz")
if err != nil {
b.Fatal(err)
}
ServeArtifact(w, result)
}
})
}
func BenchmarkArtifactCacheHitParallel(b *testing.B) {
proxy, _ := benchmarkCachedProxy(b)
ctx := context.Background()
b.SetBytes(benchmarkArtifactSize)
b.ReportAllocs()
b.ResetTimer()
b.RunParallel(func(pb *testing.PB) {
w := &benchmarkResponseWriter{header: make(http.Header)}
for pb.Next() {
result, err := proxy.GetOrFetchArtifact(ctx, "npm", "lodash", "4.17.21", "lodash-4.17.21.tgz")
if err != nil {
b.Error(err)
return
}
ServeArtifact(w, result)
}
})
}
func BenchmarkReadMetadata(b *testing.B) {
payload := bytes.Repeat([]byte("x"), benchmarkMetadataSize)
proxy := &Proxy{MetadataMaxSize: benchmarkMetadataSize}
b.SetBytes(benchmarkMetadataSize)
b.ReportAllocs()
var data []byte
for b.Loop() {
var err error
data, err = proxy.ReadMetadata(bytes.NewReader(payload))
if err != nil {
b.Fatal(err)
}
}
if len(data) != len(payload) {
b.Fatalf("metadata size = %d, want %d", len(data), len(payload))
}
}
func BenchmarkArtifactPURLConstruction(b *testing.B) {
for _, tc := range []struct {
name string
ecosystem string
packageID string
}{
{"npm", "npm", "lodash"},
{"scoped-npm", "npm", "@scope/package"},
{"go", "golang", "github.com/git-pkgs/proxy"},
} {
b.Run(tc.name, func(b *testing.B) {
b.ReportAllocs()
var packagePURL, versionPURL string
for b.Loop() {
packagePURL = purl.MakePURLString(tc.ecosystem, tc.packageID, "")
versionPURL = purl.MakePURLString(tc.ecosystem, tc.packageID, "1.2.3")
}
if packagePURL == "" || versionPURL == "" {
b.Fatal("empty PURL")
}
})
}
}
type benchmarkNPMServer struct {
client *http.Client
requestURL string
db *database.DB
versionPURL string
filename string
}
func newBenchmarkNPMServer(b *testing.B) *benchmarkNPMServer {
b.Helper()
ctx := context.Background()
dir := b.TempDir()
db, err := database.Create(filepath.Join(dir, "benchmark.db"))
if err != nil {
b.Fatalf("create database: %v", err)
}
b.Cleanup(func() { _ = db.Close() })
store, err := storage.OpenBucket(ctx, "file://"+filepath.Join(dir, "cache"))
if err != nil {
b.Fatalf("open storage: %v", err)
}
b.Cleanup(func() { _ = store.Close() })
content := bytes.Repeat([]byte("x"), benchmarkArtifactSize)
storagePath := storage.ArtifactPath("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)
}
pkg := &database.Package{PURL: "pkg:npm/lodash", Ecosystem: "npm", Name: "lodash"}
if err := db.UpsertPackage(pkg); err != nil {
b.Fatalf("seed package: %v", err)
}
version := &database.Version{PURL: "pkg:npm/lodash@4.17.21", PackagePURL: pkg.PURL}
if err := db.UpsertVersion(version); err != nil {
b.Fatalf("seed version: %v", err)
}
artifact := &database.Artifact{
VersionPURL: version.PURL,
Filename: "lodash-4.17.21.tgz",
UpstreamURL: "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz",
StoragePath: sql.NullString{String: storagePath, Valid: true},
ContentHash: sql.NullString{String: hash, Valid: true},
Size: sql.NullInt64{Int64: size, Valid: true},
ContentType: sql.NullString{String: "application/gzip", Valid: true},
FetchedAt: sql.NullTime{Time: time.Now(), Valid: true},
}
if err := db.UpsertArtifact(artifact); err != nil {
b.Fatalf("seed artifact: %v", err)
}
logger := slog.New(slog.NewTextHandler(io.Discard, nil))
proxy := NewProxy(db, store, &mockFetcher{}, fetch.NewResolver(), logger)
handler := NewNPMHandler(proxy, "http://proxy.example", "https://registry.npmjs.org")
server := httptest.NewServer(handler.Routes())
b.Cleanup(server.Close)
client := server.Client()
return &benchmarkNPMServer{
client: client,
requestURL: server.URL + "/lodash/-/lodash-4.17.21.tgz",
db: db,
versionPURL: version.PURL,
filename: artifact.Filename,
}
}
func (s *benchmarkNPMServer) request() error {
resp, err := s.client.Get(s.requestURL)
if err != nil {
return fmt.Errorf("GET cached artifact: %w", err)
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("GET cached artifact status = %d, want %d", resp.StatusCode, http.StatusOK)
}
n, err := io.Copy(io.Discard, resp.Body)
if err != nil {
return fmt.Errorf("read cached artifact: %w", err)
}
if n != benchmarkArtifactSize {
return fmt.Errorf("cached artifact size = %d, want %d", n, benchmarkArtifactSize)
}
return nil
}
func (s *benchmarkNPMServer) hitCount(b *testing.B) int64 {
b.Helper()
artifact, err := s.db.GetArtifact(s.versionPURL, s.filename)
if err != nil {
b.Fatalf("get artifact hit count: %v", err)
}
return artifact.HitCount
}
func benchmarkNPMArtifactCacheHitHTTP(b *testing.B, parallel bool) {
server := newBenchmarkNPMServer(b)
if err := server.request(); err != nil {
b.Fatal(err)
}
startHits := server.hitCount(b)
b.SetBytes(benchmarkArtifactSize)
b.ReportAllocs()
b.ResetTimer()
if parallel {
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
if err := server.request(); err != nil {
b.Error(err)
return
}
}
})
} else {
for b.Loop() {
if err := server.request(); err != nil {
b.Fatal(err)
}
}
}
b.StopTimer()
if hitCount := server.hitCount(b) - startHits; hitCount != int64(b.N) {
b.Fatalf("new artifact hits = %d, want %d", hitCount, b.N)
}
b.ReportMetric(float64(b.N)/b.Elapsed().Seconds(), "requests/s")
}
func BenchmarkNPMArtifactCacheHitHTTP(b *testing.B) {
benchmarkNPMArtifactCacheHitHTTP(b, false)
}
func BenchmarkNPMArtifactCacheHitHTTPParallel(b *testing.B) {
benchmarkNPMArtifactCacheHitHTTP(b, true)
}

File diff suppressed because it is too large Load diff

View file

@ -1,364 +0,0 @@
package handler
import (
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"net/http"
"net/url"
"path"
"strings"
"time"
"gopkg.in/yaml.v3"
)
const (
helmMetadataEcosystem = "helm"
helmIndexFilename = "index.yaml"
sha256HexLength = 64
)
// HelmHandler serves read-only HTTP Helm chart repositories. Each configured
// repository is mounted at /helm/{repository}/.
type HelmHandler struct {
proxy *Proxy
proxyURL string
repositories map[string]string
}
// NewHelmHandler creates a Helm chart repository protocol handler.
func NewHelmHandler(proxy *Proxy, proxyURL string, repositories map[string]string) *HelmHandler {
h := &HelmHandler{
proxyURL: strings.TrimSuffix(proxyURL, "/"),
repositories: make(map[string]string, len(repositories)),
proxy: proxy,
}
for name, repositoryURL := range repositories {
h.repositories[name] = strings.TrimSuffix(repositoryURL, "/")
}
return h
}
// Routes returns the HTTP handler for Helm chart repository requests.
func (h *HelmHandler) Routes() http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("GET /{repository}/index.yaml", h.handleIndex)
mux.HandleFunc("GET /{repository}/charts/{digest}/{filename}", h.handleChart)
return mux
}
func (h *HelmHandler) handleIndex(w http.ResponseWriter, r *http.Request) {
repository, upstreamURL, ok := h.repositoryForRequest(r)
if !ok {
http.NotFound(w, r)
return
}
body, contentType, err := h.fetchIndex(r, repository, upstreamURL)
if err != nil {
h.serveIndexError(w, err)
return
}
rewritten, err := h.rewriteIndex(repository, upstreamURL, body)
if err != nil {
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)
}
func (h *HelmHandler) handleChart(w http.ResponseWriter, r *http.Request) {
repository, upstreamURL, ok := h.repositoryForRequest(r)
if !ok {
http.NotFound(w, r)
return
}
digest, ok := normalizeHelmDigest(r.PathValue("digest"))
filename := r.PathValue("filename")
if !ok || filename == "" || strings.Contains(filename, "/") || containsPathTraversal(filename) {
http.Error(w, "invalid chart request", http.StatusBadRequest)
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)
http.Error(w, "failed to check chart cache", http.StatusInternalServerError)
return
}
if cached != nil {
h.serveChart(w, r, repository, digest, filename, cached)
return
}
body, _, err := h.fetchIndex(r, repository, upstreamURL)
if err != nil {
h.serveIndexError(w, err)
return
}
downloadURL, err := h.findChartDownload(upstreamURL, body, digest, filename)
if err != nil {
if errors.Is(err, errHelmChartNotFound) {
http.NotFound(w, r)
return
}
h.proxy.Logger.Warn("failed to read Helm index", "repository", repository, "error", err)
http.Error(w, "invalid Helm repository index", http.StatusBadGateway)
return
}
result, err := h.proxy.GetOrFetchArtifactFromURL(
r.Context(), helmMetadataEcosystem, repository, digest, filename, downloadURL)
if err != nil {
h.proxy.serveArtifactError(w, err, "failed to fetch chart")
return
}
h.serveChart(w, r, repository, digest, filename, result)
}
func (h *HelmHandler) serveChart(w http.ResponseWriter, r *http.Request, repository, digest, filename string, result *CacheResult) {
if !strings.EqualFold(result.Hash, digest) {
if result.Reader != nil {
_ = result.Reader.Close()
}
if clearErr := h.proxy.ClearCachedArtifact(r.Context(), helmMetadataEcosystem, repository, digest, filename); clearErr != nil {
h.proxy.Logger.Warn("failed to clear Helm chart with invalid digest", "error", clearErr)
}
http.Error(w, "chart digest verification failed", http.StatusBadGateway)
return
}
if result.ContentType == "" {
w.Header().Set("Content-Type", "application/gzip")
}
ServeArtifact(w, result)
}
func (h *HelmHandler) repositoryForRequest(r *http.Request) (name, upstreamURL string, ok bool) {
name = r.PathValue("repository")
upstreamURL, ok = h.repositories[name]
return name, upstreamURL, ok
}
func (h *HelmHandler) fetchIndex(r *http.Request, repository, upstreamURL string) ([]byte, string, error) {
return h.proxy.FetchOrCacheMetadata(
r.Context(),
helmMetadataEcosystem,
h.indexCacheKey(repository, upstreamURL),
upstreamURL+"/"+helmIndexFilename,
"application/x-yaml, text/yaml;q=0.9, */*;q=0.1",
)
}
func (h *HelmHandler) indexCacheKey(repository, upstreamURL string) string {
identity := repository + "\x00" + upstreamURL
digest := sha256.Sum256([]byte(identity))
return hex.EncodeToString(digest[:])
}
func (h *HelmHandler) serveIndexError(w http.ResponseWriter, err error) {
if errors.Is(err, ErrUpstreamNotFound) {
http.Error(w, "Helm repository not found", http.StatusNotFound)
return
}
h.proxy.Logger.Error("failed to fetch Helm index", "error", err)
http.Error(w, "failed to fetch Helm repository index", http.StatusBadGateway)
}
func (h *HelmHandler) rewriteIndex(repository, upstreamURL string, body []byte) ([]byte, error) {
document, entries, err := parseHelmIndex(body)
if err != nil {
return nil, err
}
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)
}
filtered := make([]*yaml.Node, 0, len(releases.Content))
for _, release := range releases.Content {
chart, err := h.parseChartRelease(chartName, upstreamURL, release)
if err != nil {
return nil, err
}
if h.chartOnCooldown(chartName, chart.created) {
continue
}
for _, download := range chart.downloads {
download.node.Value = h.chartProxyURL(repository, chart.digest, download.filename)
}
filtered = append(filtered, release)
}
releases.Content = filtered
}
return yaml.Marshal(document)
}
func (h *HelmHandler) findChartDownload(upstreamURL string, body []byte, digest, filename string) (string, error) {
_, entries, err := parseHelmIndex(body)
if err != nil {
return "", err
}
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)
}
for _, release := range releases.Content {
chart, err := h.parseChartRelease(chartName, upstreamURL, release)
if err != nil {
return "", err
}
if chart.digest != digest || h.chartOnCooldown(chartName, chart.created) {
continue
}
for _, download := range chart.downloads {
if download.filename == filename {
return download.url, nil
}
}
}
}
return "", errHelmChartNotFound
}
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)
}
type helmChartDownload struct {
node *yaml.Node
url string
filename string
}
type helmChartRelease struct {
created time.Time
digest string
downloads []helmChartDownload
}
var errHelmChartNotFound = errors.New("chart not found in Helm index")
func (h *HelmHandler) parseChartRelease(chartName, upstreamURL string, release *yaml.Node) (helmChartRelease, error) {
digestNode := helmMappingValue(release, "digest")
urlsNode := helmMappingValue(release, "urls")
if digestNode == nil || urlsNode == nil || urlsNode.Kind != yaml.SequenceNode || len(urlsNode.Content) == 0 {
return helmChartRelease{}, fmt.Errorf("chart %q has no digest or URLs", chartName)
}
digest, ok := normalizeHelmDigest(digestNode.Value)
if !ok {
return helmChartRelease{}, fmt.Errorf("chart %q has invalid digest", chartName)
}
baseURL, err := url.Parse(upstreamURL + "/" + helmIndexFilename)
if err != nil {
return helmChartRelease{}, fmt.Errorf("parsing Helm repository URL: %w", err)
}
chart := helmChartRelease{digest: digest}
if createdNode := helmMappingValue(release, "created"); createdNode != nil && createdNode.Value != "" {
chart.created, err = time.Parse(time.RFC3339Nano, createdNode.Value)
if err != nil {
return helmChartRelease{}, fmt.Errorf("chart %q has invalid creation time: %w", chartName, err)
}
}
for _, urlNode := range urlsNode.Content {
if urlNode.Kind != yaml.ScalarNode {
return helmChartRelease{}, fmt.Errorf("chart %q has invalid URL", chartName)
}
reference, err := url.Parse(urlNode.Value)
if err != nil {
return helmChartRelease{}, fmt.Errorf("parsing chart %q URL: %w", chartName, err)
}
downloadURL := baseURL.ResolveReference(reference)
if (downloadURL.Scheme != "http" && downloadURL.Scheme != "https") || downloadURL.Host == "" {
return helmChartRelease{}, fmt.Errorf("chart %q URL must be HTTP(S)", chartName)
}
filename := path.Base(downloadURL.Path)
if filename == "." || filename == "/" || filename == "" || !strings.HasSuffix(filename, ".tgz") {
return helmChartRelease{}, fmt.Errorf("chart %q URL must point to a .tgz file", chartName)
}
chart.downloads = append(chart.downloads, helmChartDownload{
node: urlNode,
url: downloadURL.String(),
filename: filename,
})
}
return chart, nil
}
func (h *HelmHandler) chartProxyURL(repository, digest, filename string) string {
return fmt.Sprintf("%s/helm/%s/charts/%s/%s", h.proxyURL,
url.PathEscape(repository), digest, url.PathEscape(filename))
}
func parseHelmIndex(body []byte) (*yaml.Node, *yaml.Node, error) {
var document yaml.Node
if err := yaml.Unmarshal(body, &document); err != nil {
return nil, nil, fmt.Errorf("parsing Helm index: %w", err)
}
entries, err := helmIndexEntries(&document)
if err != nil {
return nil, nil, err
}
return &document, entries, nil
}
func helmIndexEntries(document *yaml.Node) (*yaml.Node, error) {
if document == nil {
return nil, errors.New("helm index is empty")
}
if len(document.Content) != 1 || document.Content[0].Kind != yaml.MappingNode {
return nil, errors.New("helm index must be a mapping")
}
entries := helmMappingValue(document.Content[0], "entries")
if entries == nil || entries.Kind != yaml.MappingNode {
return nil, errors.New("helm index has no entries mapping")
}
if len(entries.Content)%2 != 0 {
return nil, errors.New("helm index entries mapping has an incomplete key-value pair")
}
return entries, nil
}
func helmMappingValue(mapping *yaml.Node, key string) *yaml.Node {
if mapping == nil || mapping.Kind != yaml.MappingNode {
return nil
}
for i := 0; i+1 < len(mapping.Content); i += 2 {
if mapping.Content[i].Value == key {
return mapping.Content[i+1]
}
}
return nil
}
func normalizeHelmDigest(value string) (string, bool) {
digest := strings.TrimPrefix(strings.ToLower(value), "sha256:")
if len(digest) != sha256HexLength {
return "", false
}
for _, char := range digest {
if (char < '0' || char > '9') && (char < 'a' || char > 'f') {
return "", false
}
}
return digest, true
}

View file

@ -1,337 +0,0 @@
package handler
import (
"crypto/sha256"
"encoding/hex"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"sync/atomic"
"testing"
"time"
"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"
)
func TestHelmHandler_RewritesIndexAndCachesChart(t *testing.T) {
chart := []byte("a Helm chart")
digest := helmSHA256Hex(chart)
var available atomic.Bool
available.Store(true)
var indexRequests atomic.Int32
var chartRequests atomic.Int32
var upstream *httptest.Server
upstream = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !available.Load() {
http.Error(w, "unavailable", http.StatusServiceUnavailable)
return
}
switch r.URL.Path {
case "/charts/index.yaml":
indexRequests.Add(1)
w.Header().Set("Content-Type", "application/x-yaml")
_, _ = fmt.Fprintf(w, `apiVersion: v1
entries:
demo:
- annotations:
example.com/retained: "true"
created: 2020-01-02T03:04:05Z
digest: %s
name: demo
urls:
- demo-1.0.0.tgz
- %s/charts/mirror/demo-1.0.0.tgz
version: 1.0.0
generated: 2020-01-02T03:04:05Z
`, digest, upstream.URL)
case "/charts/demo-1.0.0.tgz", "/charts/mirror/demo-1.0.0.tgz":
chartRequests.Add(1)
w.Header().Set("Content-Type", "application/gzip")
_, _ = w.Write(chart)
default:
http.NotFound(w, r)
}
}))
defer upstream.Close()
proxy, _, _, _ := setupTestProxy(t)
proxy.CacheMetadata = true
proxy.MetadataTTL = time.Hour
proxy.HTTPClient = upstream.Client()
fetcher := fetch.NewFetcher(fetch.WithHTTPClient(upstream.Client()), fetch.WithMaxRetries(0))
proxy.Fetcher = fetcher
t.Cleanup(func() { _ = fetcher.Close() })
h := NewHelmHandler(proxy, "http://proxy.example", map[string]string{"stable": upstream.URL + "/charts"})
indexResponse := serveHelmRequest(h, "/stable/index.yaml")
if indexResponse.Code != http.StatusOK {
t.Fatalf("index status = %d, want 200: %s", indexResponse.Code, indexResponse.Body.String())
}
if got := indexResponse.Header().Get("Content-Type"); got != "application/x-yaml" {
t.Errorf("index Content-Type = %q, want application/x-yaml", got)
}
if strings.Contains(indexResponse.Body.String(), upstream.URL) {
t.Errorf("rewritten index contains upstream URL: %s", indexResponse.Body.String())
}
if !strings.Contains(indexResponse.Body.String(), "example.com/retained") {
t.Errorf("rewritten index lost an unrelated field: %s", indexResponse.Body.String())
}
var index map[string]any
if err := yaml.Unmarshal(indexResponse.Body.Bytes(), &index); err != nil {
t.Fatalf("parse rewritten index: %v", err)
}
entries := index["entries"].(map[string]any)
release := entries["demo"].([]any)[0].(map[string]any)
urls := release["urls"].([]any)
wantURL := "http://proxy.example/helm/stable/charts/" + digest + "/demo-1.0.0.tgz"
for _, rawURL := range urls {
if rawURL != wantURL {
t.Errorf("rewritten URL = %q, want %q", rawURL, wantURL)
}
}
firstChart := serveHelmRequest(h, "/stable/charts/"+digest+"/demo-1.0.0.tgz")
if firstChart.Code != http.StatusOK {
t.Fatalf("chart status = %d, want 200: %s", firstChart.Code, firstChart.Body.String())
}
if got := firstChart.Body.String(); got != string(chart) {
t.Errorf("chart body = %q, want %q", got, chart)
}
if got := firstChart.Header().Get("Content-Type"); got != "application/gzip" {
t.Errorf("chart Content-Type = %q, want application/gzip", got)
}
// Artifact cache availability must not depend on metadata caching or a
// reachable index upstream.
proxy.CacheMetadata = false
available.Store(false)
cachedChart := serveHelmRequest(h, "/stable/charts/"+digest+"/demo-1.0.0.tgz")
if cachedChart.Code != http.StatusOK {
t.Fatalf("cached chart status = %d, want 200: %s", cachedChart.Code, cachedChart.Body.String())
}
if got := cachedChart.Body.String(); got != string(chart) {
t.Errorf("cached chart body = %q, want %q", got, chart)
}
if got := indexRequests.Load(); got != 1 {
t.Errorf("index requests = %d, want 1", got)
}
if got := chartRequests.Load(); got != 1 {
t.Errorf("chart requests = %d, want 1", got)
}
}
func TestHelmHandler_RejectsChartDigestMismatch(t *testing.T) {
chart := []byte("tampered chart")
digest := helmSHA256Hex([]byte("expected chart"))
requests := 0
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/index.yaml":
_, _ = fmt.Fprintf(w, "apiVersion: v1\nentries:\n demo:\n - digest: %s\n urls: [demo.tgz]\n", digest)
case "/demo.tgz":
requests++
_, _ = w.Write(chart)
default:
http.NotFound(w, r)
}
}))
defer upstream.Close()
proxy, _, store, _ := setupTestProxy(t)
proxy.CacheMetadata = true
proxy.MetadataTTL = time.Hour
proxy.HTTPClient = upstream.Client()
fetcher := fetch.NewFetcher(fetch.WithHTTPClient(upstream.Client()), fetch.WithMaxRetries(0))
proxy.Fetcher = fetcher
t.Cleanup(func() { _ = fetcher.Close() })
h := NewHelmHandler(proxy, "http://proxy.example", map[string]string{"test": upstream.URL})
for range 2 {
response := serveHelmRequest(h, "/test/charts/"+digest+"/demo.tgz")
if response.Code != http.StatusBadGateway {
t.Errorf("status = %d, want 502: %s", response.Code, response.Body.String())
}
}
if requests != 2 {
t.Errorf("chart requests = %d, want 2 after invalid cache entry is cleared", requests)
}
storagePath := storage.ArtifactPath(helmMetadataEcosystem, "", "test", digest, "demo.tgz")
if exists, err := store.Exists(t.Context(), storagePath); err != nil {
t.Fatalf("checking rejected chart storage: %v", err)
} else if exists {
t.Errorf("rejected chart remains in storage at %q", storagePath)
}
}
func TestHelmHandler_IndexCacheChangesWithUpstreamURL(t *testing.T) {
firstDigest := strings.Repeat("a", sha256HexLength)
secondDigest := strings.Repeat("b", sha256HexLength)
firstRequests := 0
secondRequests := 0
first := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
firstRequests++
_, _ = fmt.Fprintf(w, "apiVersion: v1\nentries:\n demo:\n - digest: %s\n urls: [demo.tgz]\n", firstDigest)
}))
defer first.Close()
second := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
secondRequests++
_, _ = fmt.Fprintf(w, "apiVersion: v1\nentries:\n demo:\n - digest: %s\n urls: [demo.tgz]\n", secondDigest)
}))
defer second.Close()
proxy, db, store, _ := setupTestProxy(t)
proxy.CacheMetadata = true
proxy.MetadataTTL = time.Hour
proxy.HTTPClient = first.Client()
firstHandler := NewHelmHandler(proxy, "http://proxy.example", map[string]string{"stable": first.URL})
if response := serveHelmRequest(firstHandler, "/stable/index.yaml"); response.Code != http.StatusOK {
t.Fatalf("first index status = %d, want 200: %s", response.Code, response.Body.String())
}
// Model a restarted server with the same database and storage but a changed
// repository URL. Its cache key must not reuse the previous index or ETag.
restartedProxy := NewProxy(db, store, &mockFetcher{}, fetch.NewResolver(), nil)
restartedProxy.CacheMetadata = true
restartedProxy.MetadataTTL = time.Hour
restartedProxy.HTTPClient = second.Client()
secondHandler := NewHelmHandler(restartedProxy, "http://proxy.example", map[string]string{"stable": second.URL})
response := serveHelmRequest(secondHandler, "/stable/index.yaml")
if response.Code != http.StatusOK {
t.Fatalf("second index status = %d, want 200: %s", response.Code, response.Body.String())
}
if !strings.Contains(response.Body.String(), secondDigest) {
t.Errorf("second index did not use the new upstream: %s", response.Body.String())
}
if firstRequests != 1 {
t.Errorf("first upstream requests = %d, want 1", firstRequests)
}
if secondRequests != 1 {
t.Errorf("second upstream requests = %d, want 1", secondRequests)
}
}
func TestHelmHandler_UsesConfiguredUpstreamAuthentication(t *testing.T) {
chart := []byte("private Helm chart")
digest := helmSHA256Hex(chart)
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Authorization") != "Bearer private-token" {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
switch r.URL.Path {
case "/index.yaml":
_, _ = fmt.Fprintf(w, "apiVersion: v1\nentries:\n demo:\n - digest: %s\n urls: [demo.tgz]\n", digest)
case "/demo.tgz":
_, _ = w.Write(chart)
default:
http.NotFound(w, r)
}
}))
defer upstream.Close()
proxy, _, _, _ := setupTestProxy(t)
proxy.CacheMetadata = true
proxy.MetadataTTL = time.Hour
authClient := &http.Client{Transport: upstreamhttp.NewTransport(http.DefaultTransport,
upstreamhttp.AuthFunc(func(string) (string, string) {
return "Authorization", "Bearer private-token"
}))}
proxy.HTTPClient = authClient
fetcher := fetch.NewFetcher(fetch.WithHTTPClient(authClient), fetch.WithMaxRetries(0))
proxy.Fetcher = fetcher
t.Cleanup(func() { _ = fetcher.Close() })
h := NewHelmHandler(proxy, "http://proxy.example", map[string]string{"private": upstream.URL})
response := serveHelmRequest(h, "/private/charts/"+digest+"/demo.tgz")
if response.Code != http.StatusOK {
t.Fatalf("status = %d, want 200: %s", response.Code, response.Body.String())
}
if got := response.Body.String(); got != string(chart) {
t.Errorf("body = %q, want %q", got, chart)
}
}
func TestHelmHandler_FiltersNewChartsFromIndex(t *testing.T) {
oldDigest := strings.Repeat("a", 64)
newDigest := strings.Repeat("b", 64)
proxy := &Proxy{Cooldown: &cooldown.Config{Default: "3d"}}
h := NewHelmHandler(proxy, "http://proxy.example", map[string]string{"test": "https://charts.example"})
body := fmt.Sprintf(`apiVersion: v1
entries:
demo:
- created: %s
digest: %s
urls: [demo-old.tgz]
- created: %s
digest: %s
urls: [demo-new.tgz]
`, 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))
if err != nil {
t.Fatalf("rewriteIndex() error = %v", err)
}
if strings.Contains(string(rewritten), newDigest) {
t.Errorf("rewritten index includes a chart still in cooldown: %s", rewritten)
}
if !strings.Contains(string(rewritten), oldDigest) {
t.Errorf("rewritten index omitted an old chart: %s", rewritten)
}
}
func TestNormalizeHelmDigest(t *testing.T) {
digest := strings.Repeat("a", 64)
for _, input := range []string{digest, "sha256:" + digest, "SHA256:" + strings.ToUpper(digest)} {
if got, ok := normalizeHelmDigest(input); !ok || got != digest {
t.Errorf("normalizeHelmDigest(%q) = %q, %t; want %q, true", input, got, ok, digest)
}
}
if _, ok := normalizeHelmDigest("bad"); ok {
t.Error("normalizeHelmDigest accepted an invalid digest")
}
}
func TestHelmIndexEntriesRejectsIncompleteMapping(t *testing.T) {
entries := &yaml.Node{
Kind: yaml.MappingNode,
Content: []*yaml.Node{
{Kind: yaml.ScalarNode, Value: "demo"},
},
}
document := &yaml.Node{
Kind: yaml.DocumentNode,
Content: []*yaml.Node{{
Kind: yaml.MappingNode,
Content: []*yaml.Node{
{Kind: yaml.ScalarNode, Value: "entries"},
entries,
},
}},
}
if _, err := helmIndexEntries(document); err == nil {
t.Fatal("helmIndexEntries() error = nil, want incomplete mapping error")
}
}
func serveHelmRequest(h *HelmHandler, target string) *httptest.ResponseRecorder {
w := httptest.NewRecorder()
h.Routes().ServeHTTP(w, httptest.NewRequest(http.MethodGet, target, nil))
return w
}
func helmSHA256Hex(data []byte) string {
digest := sha256.Sum256(data)
return hex.EncodeToString(digest[:])
}

View file

@ -1,16 +1,10 @@
package handler package handler
import ( import (
"bytes"
"compress/gzip"
"encoding/json"
"fmt" "fmt"
"io" "io"
"net/http" "net/http"
"strings" "strings"
"time"
"google.golang.org/protobuf/encoding/protowire"
) )
const ( const (
@ -40,10 +34,10 @@ func (h *HexHandler) Routes() http.Handler {
// Package tarballs (cache these) // Package tarballs (cache these)
mux.HandleFunc("GET /tarballs/{filename}", h.handleDownload) mux.HandleFunc("GET /tarballs/{filename}", h.handleDownload)
// Registry resources (cached for offline) // Registry resources (proxy without caching)
mux.HandleFunc("GET /names", h.proxyCached) mux.HandleFunc("GET /names", h.proxyUpstream)
mux.HandleFunc("GET /versions", h.proxyCached) mux.HandleFunc("GET /versions", h.proxyUpstream)
mux.HandleFunc("GET /packages/{name}", h.handlePackages) mux.HandleFunc("GET /packages/{name}", h.proxyUpstream)
// Public keys // Public keys
mux.HandleFunc("GET /public_key", h.proxyUpstream) mux.HandleFunc("GET /public_key", h.proxyUpstream)
@ -53,13 +47,30 @@ func (h *HexHandler) Routes() http.Handler {
// handleDownload serves a package tarball, fetching and caching from upstream if needed. // handleDownload serves a package tarball, fetching and caching from upstream if needed.
func (h *HexHandler) handleDownload(w http.ResponseWriter, r *http.Request) { func (h *HexHandler) handleDownload(w http.ResponseWriter, r *http.Request) {
h.proxy.handleFilenameDownload(w, r, filenameDownload{ filename := r.PathValue("filename")
ecosystem: "hex", if filename == "" || !strings.HasSuffix(filename, ".tar") {
suffix: ".tar", http.Error(w, "invalid filename", http.StatusBadRequest)
parseErr: "could not parse tarball filename", return
fetchErr: "failed to fetch package", }
parse: h.parseTarballFilename,
}) // Extract name and version from filename (e.g., "phoenix-1.7.10.tar")
name, version := h.parseTarballFilename(filename)
if name == "" || version == "" {
http.Error(w, "could not parse tarball filename", http.StatusBadRequest)
return
}
h.proxy.Logger.Info("hex download request",
"name", name, "version", version, "filename", filename)
result, err := h.proxy.GetOrFetchArtifact(r.Context(), "hex", name, version, filename)
if err != nil {
h.proxy.Logger.Error("failed to get artifact", "error", err)
http.Error(w, "failed to fetch package", http.StatusBadGateway)
return
}
ServeArtifact(w, result)
} }
// parseTarballFilename extracts name and version from a hex tarball filename. // parseTarballFilename extracts name and version from a hex tarball filename.
@ -76,336 +87,42 @@ func (h *HexHandler) parseTarballFilename(filename string) (name, version string
return "", "" return "", ""
} }
// hexAPIURL is the Hex HTTP API base URL for fetching package metadata with timestamps. // proxyUpstream forwards a request to hex.pm without caching.
const hexAPIURL = "https://hex.pm" func (h *HexHandler) proxyUpstream(w http.ResponseWriter, r *http.Request) {
upstreamURL := h.upstreamURL + r.URL.Path
// handlePackages proxies the /packages/{name} endpoint, applying cooldown filtering h.proxy.Logger.Debug("proxying to upstream", "url", upstreamURL)
// when enabled. Since the protobuf format has no timestamps, we fetch them from the
// Hex HTTP API concurrently. req, err := http.NewRequestWithContext(r.Context(), http.MethodGet, upstreamURL, nil)
func (h *HexHandler) handlePackages(w http.ResponseWriter, r *http.Request) { if err != nil {
if h.proxy.Cooldown == nil || !h.proxy.Cooldown.Enabled() { http.Error(w, "failed to create request", http.StatusInternalServerError)
h.proxyCached(w, r)
return return
} }
name := r.PathValue("name") // Copy accept header for content negotiation
if name == "" { if accept := r.Header.Get("Accept"); accept != "" {
h.proxyCached(w, r) req.Header.Set("Accept", accept)
return
} }
h.proxy.Logger.Info("hex package request with cooldown", "name", name) resp, err := http.DefaultClient.Do(req)
protoResp, filteredVersions, err := h.fetchPackageAndVersions(r, name)
if err != nil { if err != nil {
h.proxy.Logger.Error("upstream request failed", "error", err) h.proxy.Logger.Error("upstream request failed", "error", err)
http.Error(w, "upstream request failed", http.StatusBadGateway) http.Error(w, "upstream request failed", http.StatusBadGateway)
return return
} }
defer func() { _ = protoResp.Body.Close() }()
if protoResp.StatusCode != http.StatusOK {
for k, vv := range protoResp.Header {
for _, v := range vv {
w.Header().Add(k, v)
}
}
w.WriteHeader(protoResp.StatusCode)
_, _ = io.Copy(w, protoResp.Body)
return
}
body, err := io.ReadAll(protoResp.Body)
if err != nil {
http.Error(w, "failed to read response", http.StatusInternalServerError)
return
}
if len(filteredVersions) == 0 {
// No versions to filter or couldn't get timestamps, pass through
w.Header().Set("Content-Type", protoResp.Header.Get("Content-Type"))
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("Content-Type", protoResp.Header.Get("Content-Type"))
w.Header().Set("Content-Encoding", "gzip")
_, _ = w.Write(body)
return
}
w.Header().Set("Content-Type", "application/octet-stream")
w.Header().Set("Content-Encoding", "gzip")
_, _ = w.Write(filtered)
}
// 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
}
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)
if err != nil {
return nil, err
}
return h.proxy.HTTPClient.Do(req)
}
// hexRelease represents a version entry from the Hex API.
type hexRelease struct {
Version string `json:"version"`
InsertedAt string `json:"inserted_at"`
}
// hexPackageAPI represents the Hex API response for a package.
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", hexAPIURL, 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() }() defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != http.StatusOK { // Copy response headers
return nil, fmt.Errorf("hex API returned %d", resp.StatusCode) for k, vv := range resp.Header {
} for _, v := range vv {
w.Header().Add(k, v)
var pkg hexPackageAPI
if err := json.NewDecoder(resp.Body).Decode(&pkg); err != nil {
return nil, err
}
packagePURL := canonicalPackagePURL("hex", name)
filtered := make(map[string]bool)
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)
} }
} }
return filtered, nil w.WriteHeader(resp.StatusCode)
_, _ = io.Copy(w, resp.Body)
} }
// filterSignedPackage decompresses gzipped data, decodes the Signed protobuf wrapper, func init() {
// filters releases from the Package payload, and re-encodes as gzipped protobuf _ = fmt.Sprintf // silence import if unused
// (without the original signature since the payload has changed).
func (h *HexHandler) filterSignedPackage(gzippedData []byte, filteredVersions map[string]bool) ([]byte, error) {
// Decompress gzip
gr, err := gzip.NewReader(bytes.NewReader(gzippedData))
if err != nil {
return nil, err
}
signed, err := io.ReadAll(gr)
if err != nil {
return nil, err
}
_ = gr.Close()
// Parse Signed message: field 1 = payload (bytes), field 2 = signature (bytes)
payload, err := extractProtobufBytes(signed, 1)
if err != nil {
return nil, fmt.Errorf("extracting payload: %w", err)
}
// Filter releases from the Package message
filteredPayload, err := filterPackageReleases(payload, filteredVersions)
if err != nil {
return nil, fmt.Errorf("filtering releases: %w", err)
}
// Re-encode Signed message with modified payload and no signature
var newSigned []byte
newSigned = protowire.AppendTag(newSigned, 1, protowire.BytesType)
newSigned = protowire.AppendBytes(newSigned, filteredPayload)
// Gzip compress
var buf bytes.Buffer
gw := gzip.NewWriter(&buf)
if _, err := gw.Write(newSigned); err != nil {
return nil, err
}
if err := gw.Close(); err != nil {
return nil, err
}
return buf.Bytes(), nil
}
// filterPackageReleases filters releases from a Package protobuf message.
// Package: field 1 = releases (repeated), field 2 = name, field 3 = repository
func filterPackageReleases(payload []byte, filteredVersions map[string]bool) ([]byte, error) {
var result []byte
data := payload
for len(data) > 0 {
num, wtype, n := protowire.ConsumeTag(data)
if n < 0 {
return nil, fmt.Errorf("invalid protobuf tag")
}
tagBytes := data[:n]
data = data[n:]
var fieldBytes []byte
switch wtype {
case protowire.BytesType:
v, vn := protowire.ConsumeBytes(data)
if vn < 0 {
return nil, fmt.Errorf("invalid protobuf bytes field")
}
fieldBytes = data[:vn]
data = data[vn:]
if num == 1 { // releases field
version := extractReleaseVersion(v)
if filteredVersions[version] {
continue // skip this release
}
}
case protowire.VarintType:
_, vn := protowire.ConsumeVarint(data)
if vn < 0 {
return nil, fmt.Errorf("invalid protobuf varint")
}
fieldBytes = data[:vn]
data = data[vn:]
default:
return nil, fmt.Errorf("unexpected wire type %d", wtype)
}
result = append(result, tagBytes...)
result = append(result, fieldBytes...)
}
return result, nil
}
// extractReleaseVersion extracts the version string from a Release protobuf message.
// Release: field 1 = version (string)
func extractReleaseVersion(release []byte) string {
data := release
for len(data) > 0 {
num, wtype, n := protowire.ConsumeTag(data)
if n < 0 {
return ""
}
data = data[n:]
switch wtype {
case protowire.BytesType:
v, vn := protowire.ConsumeBytes(data)
if vn < 0 {
return ""
}
if num == 1 {
return string(v)
}
data = data[vn:]
case protowire.VarintType:
_, vn := protowire.ConsumeVarint(data)
if vn < 0 {
return ""
}
data = data[vn:]
default:
return ""
}
}
return ""
}
// extractProtobufBytes extracts a bytes field from a protobuf message by field number.
func extractProtobufBytes(data []byte, fieldNum protowire.Number) ([]byte, error) {
for len(data) > 0 {
num, wtype, n := protowire.ConsumeTag(data)
if n < 0 {
return nil, fmt.Errorf("invalid protobuf tag")
}
data = data[n:]
switch wtype {
case protowire.BytesType:
v, vn := protowire.ConsumeBytes(data)
if vn < 0 {
return nil, fmt.Errorf("invalid protobuf bytes")
}
if num == fieldNum {
return v, nil
}
data = data[vn:]
case protowire.VarintType:
_, vn := protowire.ConsumeVarint(data)
if vn < 0 {
return nil, fmt.Errorf("invalid protobuf varint")
}
data = data[vn:]
default:
return nil, fmt.Errorf("unexpected wire type %d", wtype)
}
}
return nil, fmt.Errorf("field %d not found", fieldNum)
}
// proxyCached forwards a request with metadata caching.
func (h *HexHandler) proxyCached(w http.ResponseWriter, r *http.Request) {
cacheKey := strings.TrimPrefix(r.URL.Path, "/")
h.proxy.ProxyCached(w, r, h.upstreamURL+r.URL.Path, "hex", cacheKey, "*/*")
}
// proxyUpstream forwards a request to hex.pm without caching.
func (h *HexHandler) proxyUpstream(w http.ResponseWriter, r *http.Request) {
h.proxy.ProxyUpstream(w, r, h.upstreamURL+r.URL.Path, []string{"Accept"})
} }

View file

@ -1,18 +1,8 @@
package handler package handler
import ( import (
"bytes"
"compress/gzip"
"encoding/json"
"io"
"log/slog" "log/slog"
"net/http"
"net/http/httptest"
"testing" "testing"
"time"
"github.com/git-pkgs/cooldown"
"google.golang.org/protobuf/encoding/protowire"
) )
func TestHexParseTarballFilename(t *testing.T) { func TestHexParseTarballFilename(t *testing.T) {
@ -37,290 +27,3 @@ func TestHexParseTarballFilename(t *testing.T) {
} }
} }
} }
// buildHexRelease encodes a Release protobuf message.
func buildHexRelease(version string) []byte {
var release []byte
// field 1 = version (string)
release = protowire.AppendTag(release, 1, protowire.BytesType)
release = protowire.AppendString(release, version)
// field 2 = inner_checksum (bytes) - required
release = protowire.AppendTag(release, 2, protowire.BytesType)
release = protowire.AppendBytes(release, []byte("fakechecksum1234567890123456789012"))
// field 5 = outer_checksum (bytes)
release = protowire.AppendTag(release, 5, protowire.BytesType)
release = protowire.AppendBytes(release, []byte("outerchecksum123456789012345678901"))
return release
}
// buildHexPackage encodes a Package protobuf message.
func buildHexPackage(name string, versions []string) []byte {
var pkg []byte
for _, v := range versions {
release := buildHexRelease(v)
pkg = protowire.AppendTag(pkg, 1, protowire.BytesType)
pkg = protowire.AppendBytes(pkg, release)
}
// field 2 = name
pkg = protowire.AppendTag(pkg, 2, protowire.BytesType)
pkg = protowire.AppendString(pkg, name)
// field 3 = repository
pkg = protowire.AppendTag(pkg, 3, protowire.BytesType)
pkg = protowire.AppendString(pkg, "hexpm")
return pkg
}
// buildHexSigned wraps a payload in a Signed protobuf message and gzips it.
func buildHexSigned(payload []byte) []byte {
var signed []byte
signed = protowire.AppendTag(signed, 1, protowire.BytesType)
signed = protowire.AppendBytes(signed, payload)
// field 2 = signature (optional, add a fake one)
signed = protowire.AppendTag(signed, 2, protowire.BytesType)
signed = protowire.AppendBytes(signed, []byte("fakesignature"))
var buf bytes.Buffer
gw := gzip.NewWriter(&buf)
_, _ = gw.Write(signed)
_ = gw.Close()
return buf.Bytes()
}
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})
if err != nil {
t.Fatal(err)
}
// Extract remaining versions
var versions []string
data := filtered
for len(data) > 0 {
num, wtype, n := protowire.ConsumeTag(data)
if n < 0 {
break
}
data = data[n:]
switch wtype {
case protowire.BytesType:
v, vn := protowire.ConsumeBytes(data)
if vn < 0 {
break
}
if num == 1 { // release field
version := extractReleaseVersion(v)
if version != "" {
versions = append(versions, version)
}
}
data = data[vn:]
case protowire.VarintType:
_, vn := protowire.ConsumeVarint(data)
if vn < 0 {
break
}
data = data[vn:]
}
}
if len(versions) != 2 {
t.Fatalf("expected 2 versions, got %d: %v", len(versions), versions)
}
if versions[0] != testVersion100 || versions[1] != "3.0.0" {
t.Errorf("expected [1.0.0, 3.0.0], got %v", versions)
}
}
func TestHexFilterSignedPackage(t *testing.T) {
pkg := buildHexPackage("phoenix", []string{testVersion100, "2.0.0"})
gzipped := buildHexSigned(pkg)
h := &HexHandler{
proxy: testProxy(),
proxyURL: "http://proxy.local",
}
filtered, err := h.filterSignedPackage(gzipped, map[string]bool{"2.0.0": true})
if err != nil {
t.Fatal(err)
}
// Decompress and check
gr, err := gzip.NewReader(bytes.NewReader(filtered))
if err != nil {
t.Fatal(err)
}
signed, err := io.ReadAll(gr)
if err != nil {
t.Fatal(err)
}
payload, err := extractProtobufBytes(signed, 1)
if err != nil {
t.Fatal(err)
}
// Check that only version 1.0.0 remains
version := extractReleaseVersion(mustExtractFirstRelease(t, payload))
if version != testVersion100 {
t.Errorf("expected version 1.0.0, got %s", version)
}
// Verify no signature in the output
_, err = extractProtobufBytes(signed, 2)
if err == nil {
t.Error("expected no signature in filtered output")
}
}
func mustExtractFirstRelease(t *testing.T, payload []byte) []byte {
t.Helper()
data := payload
for len(data) > 0 {
num, wtype, n := protowire.ConsumeTag(data)
if n < 0 {
t.Fatal("invalid protobuf")
}
data = data[n:]
if wtype == protowire.BytesType {
v, vn := protowire.ConsumeBytes(data)
if vn < 0 {
t.Fatal("invalid bytes")
}
if num == 1 {
return v
}
data = data[vn:]
}
}
t.Fatal("no release found")
return nil
}
func TestHexExtractReleaseVersion(t *testing.T) {
release := buildHexRelease("1.2.3")
version := extractReleaseVersion(release)
if version != "1.2.3" {
t.Errorf("expected 1.2.3, got %s", version)
}
}
func TestHexHandlePackagesWithCooldown(t *testing.T) {
now := time.Now()
oldTime := now.Add(-7 * 24 * time.Hour).Format(time.RFC3339Nano)
recentTime := now.Add(-1 * time.Hour).Format(time.RFC3339Nano)
pkg := buildHexPackage("testpkg", []string{testVersion100, "2.0.0"})
gzippedProto := buildHexSigned(pkg)
apiJSON, _ := json.Marshal(hexPackageAPI{
Releases: []hexRelease{
{Version: testVersion100, InsertedAt: oldTime},
{Version: "2.0.0", InsertedAt: recentTime},
},
})
// Serve both the protobuf repo and the JSON API from the same test server
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/packages/testpkg":
w.Header().Set("Content-Encoding", "gzip")
_, _ = w.Write(gzippedProto)
case "/api/packages/testpkg":
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write(apiJSON)
default:
w.WriteHeader(http.StatusNotFound)
}
}))
defer upstream.Close()
proxy := testProxy()
proxy.Cooldown = &cooldown.Config{
Default: "3d",
}
// Override hexAPIURL for testing by using the upstream URL
h := &HexHandler{
proxy: proxy,
upstreamURL: upstream.URL,
proxyURL: "http://proxy.local",
}
// We need to override the API URL - but it's a const. Let's test via the lower-level methods instead.
// Test fetchFilteredVersions by making a request to the API endpoint
// Actually, let me test the full flow through handlePackages
req := httptest.NewRequest(http.MethodGet, "/packages/testpkg", nil)
req.SetPathValue("name", "testpkg")
w := httptest.NewRecorder()
// Since hexAPIURL is a const pointing to hex.pm, we can't easily override it in tests.
// Instead test the protobuf filtering directly which is the core logic.
filtered, err := h.filterSignedPackage(gzippedProto, map[string]bool{"2.0.0": true})
if err != nil {
t.Fatal(err)
}
// Verify only version 1.0.0 survives
gr, _ := gzip.NewReader(bytes.NewReader(filtered))
signed, _ := io.ReadAll(gr)
payload, _ := extractProtobufBytes(signed, 1)
var versions []string
data := payload
for len(data) > 0 {
num, wtype, n := protowire.ConsumeTag(data)
if n < 0 {
break
}
data = data[n:]
if wtype == protowire.BytesType {
v, vn := protowire.ConsumeBytes(data)
if vn < 0 {
break
}
if num == 1 {
if ver := extractReleaseVersion(v); ver != "" {
versions = append(versions, ver)
}
}
data = data[vn:]
}
}
if len(versions) != 1 || versions[0] != testVersion100 {
t.Errorf("expected [1.0.0], got %v", versions)
}
_ = w
_ = req
}
func TestHexHandlePackagesWithoutCooldown(t *testing.T) {
pkg := buildHexPackage("testpkg", []string{testVersion100})
gzipped := buildHexSigned(pkg)
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Encoding", "gzip")
_, _ = w.Write(gzipped)
}))
defer upstream.Close()
h := &HexHandler{
proxy: testProxy(), // no cooldown
upstreamURL: upstream.URL,
proxyURL: "http://proxy.local",
}
req := httptest.NewRequest(http.MethodGet, "/packages/testpkg", nil)
req.SetPathValue("name", "testpkg")
w := httptest.NewRecorder()
h.handlePackages(w, req)
if w.Code != http.StatusOK {
t.Fatalf("status = %d, want %d", w.Code, http.StatusOK)
}
}

View file

@ -1,100 +0,0 @@
package handler
import (
"fmt"
"io"
"github.com/git-pkgs/integrity"
)
type integrityChecks struct {
contentHash integrity.SRI
native integrity.SRI
algorithms []integrity.Algorithm
}
func newIntegrityChecks(contentHash, native string) (integrityChecks, error) {
checks := integrityChecks{}
if contentHash != "" {
digest, err := integrity.ParseHex(integrity.SHA256, contentHash)
if err != nil {
return integrityChecks{}, fmt.Errorf("parse content_hash: %w", err)
}
checks.contentHash = integrity.SRI{digest}
checks.algorithms = append(checks.algorithms, integrity.SHA256)
}
if native != "" {
digests, err := integrity.ParseSRI(native)
if err != nil {
return integrityChecks{}, fmt.Errorf("parse integrity: %w", err)
}
checks.native = digests
for _, digest := range digests {
checks.algorithms = append(checks.algorithms, digest.Algorithm())
}
}
return checks, nil
}
func (c integrityChecks) wrap(source io.ReadCloser, onMismatch func(string)) (io.ReadCloser, error) {
if len(c.algorithms) == 0 {
return source, nil
}
reader, err := integrity.NewReader(source, c.algorithms...)
if err != nil {
return nil, fmt.Errorf("create integrity reader: %w", err)
}
return &verifyingReader{
source: source,
reader: reader,
checks: c,
onMismatch: onMismatch,
}, nil
}
// verifyingReader forwards Close to its source and reports completed digest
// mismatches after its shared integrity reader observes EOF.
type verifyingReader struct {
source io.ReadCloser
reader *integrity.Reader
checks integrityChecks
onMismatch func(reason string)
verified bool
}
func (r *verifyingReader) Read(p []byte) (int, error) {
n, err := r.reader.Read(p)
if err == io.EOF {
r.verify()
}
return n, err
}
func (r *verifyingReader) Close() error {
return r.source.Close()
}
func (r *verifyingReader) verify() {
if r.verified {
return
}
r.verified = true
result := r.reader.Result()
if !result.Complete {
return
}
if len(r.checks.contentHash) > 0 {
if err := result.Verify(r.checks.contentHash); err != nil {
r.onMismatch("content_hash: " + err.Error())
}
}
if len(r.checks.native) > 0 {
if err := result.Verify(r.checks.native); err != nil {
r.onMismatch("integrity: " + err.Error())
}
}
}

View file

@ -1,250 +0,0 @@
package handler
import (
"crypto/sha256"
"crypto/sha512"
"encoding/base64"
"encoding/hex"
"errors"
"io"
"strings"
"testing"
)
func sha256Hex(data string) string {
sum := sha256.Sum256([]byte(data))
return hex.EncodeToString(sum[:])
}
func sha256SRI(data string) string {
sum := sha256.Sum256([]byte(data))
return "sha256-" + base64.StdEncoding.EncodeToString(sum[:])
}
func sha384SRI(data string) string {
sum := sha512.Sum384([]byte(data))
return "sha384-" + base64.StdEncoding.EncodeToString(sum[:])
}
func sha512SRI(data string) string {
sum := sha512.Sum512([]byte(data))
return "sha512-" + base64.StdEncoding.EncodeToString(sum[:])
}
func wrapIntegrityReader(t *testing.T, source io.ReadCloser, contentHash, native string, onMismatch func(string)) io.ReadCloser {
t.Helper()
checks, err := newIntegrityChecks(contentHash, native)
if err != nil {
t.Fatalf("newIntegrityChecks: %v", err)
}
reader, err := checks.wrap(source, onMismatch)
if err != nil {
t.Fatalf("wrap: %v", err)
}
return reader
}
func TestNewIntegrityChecksCollectsAlgorithms(t *testing.T) {
checks, err := newIntegrityChecks(
sha256Hex("hello"),
strings.Join([]string{sha256SRI("first"), sha512SRI("second"), sha384SRI("third"), sha512SRI("alternative")}, " "),
)
if err != nil {
t.Fatal(err)
}
if len(checks.algorithms) != 5 {
t.Fatalf("algorithms = %v, want 5 entries", checks.algorithms)
}
if len(checks.native) != 4 {
t.Errorf("native digests = %d, want 4", len(checks.native))
}
}
func TestNewIntegrityChecksRejectsMalformedMetadata(t *testing.T) {
tests := []struct {
name string
contentHash string
native string
}{
{name: "short content hash", contentHash: "abc123"},
{name: "non-hex content hash", contentHash: strings.Repeat("z", sha256.Size*2)},
{name: "missing SRI separator", native: "sha512"},
{name: "malformed SRI base64", native: "sha512-not!base64"},
{name: "wrong SRI length", native: "sha512-" + base64.StdEncoding.EncodeToString([]byte("short"))},
{name: "unsupported SRI algorithm", native: "md5-1B2M2Y8AsgTpgAmY7PhCfg=="},
{name: "invalid SRI alternative", native: sha512SRI("valid") + " sha384-nope"},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
if _, err := newIntegrityChecks(test.contentHash, test.native); err == nil {
t.Fatal("newIntegrityChecks returned nil error")
}
})
}
}
func TestVerifyingReader(t *testing.T) {
const data = "hello world"
goodSHA := sha256Hex(data)
goodSRI := sha512SRI(data)
tests := []struct {
name string
hash string
sri string
wantCalls int
}{
{name: "both match", hash: goodSHA, sri: goodSRI},
{name: "SHA-256 only match", hash: goodSHA},
{name: "SRI only match", sri: goodSRI},
{name: "SHA-256 mismatch", hash: sha256Hex("other"), wantCalls: 1},
{name: "SRI mismatch", sri: sha512SRI("other"), wantCalls: 1},
{name: "both mismatch", hash: sha256Hex("other"), sri: sha512SRI("other"), wantCalls: 2},
{name: "no checks"},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
var calls []string
reader := wrapIntegrityReader(t, io.NopCloser(strings.NewReader(data)), test.hash, test.sri,
func(reason string) { calls = append(calls, reason) })
got, err := io.ReadAll(reader)
if err != nil {
t.Fatalf("ReadAll: %v", err)
}
if string(got) != data {
t.Errorf("data corrupted: got %q", got)
}
if err := reader.Close(); err != nil {
t.Fatalf("Close: %v", err)
}
if len(calls) != test.wantCalls {
t.Errorf("onMismatch called %d times, want %d: %v", len(calls), test.wantCalls, calls)
}
})
}
}
func TestVerifyingReaderUsesStrongestNativeAlgorithm(t *testing.T) {
const data = "artifact"
tests := []struct {
name string
native string
wantCalls int
}{
{
name: "weaker match does not override stronger mismatch",
native: sha256SRI(data) + " " + sha512SRI("other"),
wantCalls: 1,
},
{
name: "stronger match ignores weaker mismatch",
native: sha256SRI("other") + " " + sha512SRI(data),
},
{
name: "same algorithm alternative matches",
native: sha512SRI("other") + " " + sha512SRI(data),
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
var calls int
reader := wrapIntegrityReader(t, io.NopCloser(strings.NewReader(data)), "", test.native, func(string) { calls++ })
if _, err := io.Copy(io.Discard, reader); err != nil {
t.Fatal(err)
}
if calls != test.wantCalls {
t.Errorf("onMismatch called %d times, want %d", calls, test.wantCalls)
}
})
}
}
func TestVerifyingReaderMismatchMessages(t *testing.T) {
const data = "actual"
wantHash := sha256Hex("expected")
wantSRI := sha512SRI("expected")
var reasons []string
reader := wrapIntegrityReader(t, io.NopCloser(strings.NewReader(data)), wantHash, wantSRI,
func(reason string) { reasons = append(reasons, reason) })
if _, err := io.Copy(io.Discard, reader); err != nil {
t.Fatal(err)
}
if len(reasons) != 2 {
t.Fatalf("reasons = %v, want two", reasons)
}
wantContentReason := "content_hash: integrity mismatch: expected " + sha256SRI("expected") + ", calculated " + sha256SRI(data)
if reasons[0] != wantContentReason {
t.Errorf("content reason = %q, want %q", reasons[0], wantContentReason)
}
wantNativeReason := "integrity: integrity mismatch: expected " + wantSRI + ", calculated " + sha512SRI(data)
if reasons[1] != wantNativeReason {
t.Errorf("native reason = %q, want %q", reasons[1], wantNativeReason)
}
}
func TestVerifyingReaderPassthrough(t *testing.T) {
source := io.NopCloser(strings.NewReader("x"))
reader := wrapIntegrityReader(t, source, "", "", func(string) { t.Fatal("should not be called") })
if reader != source {
t.Error("expected passthrough when no hashes were provided")
}
}
type closeTrackingReader struct {
io.Reader
closed bool
}
func (r *closeTrackingReader) Close() error {
r.closed = true
return nil
}
func TestVerifyingReaderPartialRead(t *testing.T) {
source := &closeTrackingReader{Reader: strings.NewReader("hello world")}
var calls int
reader := wrapIntegrityReader(t, source, sha256Hex("other"), "", func(string) { calls++ })
buffer := make([]byte, 5)
_, _ = reader.Read(buffer)
_ = reader.Close()
if calls != 0 {
t.Errorf("onMismatch called %d times for partial read, want 0", calls)
}
if !source.closed {
t.Error("Close was not forwarded to the source")
}
}
func TestVerifyingReaderNonEOFError(t *testing.T) {
var calls int
reader := wrapIntegrityReader(t, io.NopCloser(errorFixtureReader{}), sha256Hex("data"), "", func(string) { calls++ })
if _, err := io.ReadAll(reader); !errors.Is(err, errIntegrityReadFixture) {
t.Fatalf("ReadAll error = %v", err)
}
if calls != 0 {
t.Errorf("onMismatch called %d times after non-EOF error", calls)
}
}
var errIntegrityReadFixture = errors.New("integrity read fixture")
type errorFixtureReader struct{}
func (errorFixtureReader) Read(p []byte) (int, error) {
return copy(p, "data"), errIntegrityReadFixture
}
func TestVerifyingReaderVerifyOnce(t *testing.T) {
var calls int
reader := wrapIntegrityReader(t, io.NopCloser(strings.NewReader("x")), sha256Hex("y"), "", func(string) { calls++ })
_, _ = io.ReadAll(reader)
_ = reader.Close()
_ = reader.Close()
if calls != 1 {
t.Errorf("onMismatch called %d times, want 1", calls)
}
}

View file

@ -1,344 +0,0 @@
package handler
import (
"archive/tar"
"bufio"
"bytes"
"compress/gzip"
"context"
"fmt"
"io"
"net/http"
"regexp"
"strings"
"sync"
"github.com/BurntSushi/toml"
)
const (
juliaUpstream = "https://pkg.julialang.org"
juliaGeneralRegistryUUID = "23338594-aafe-5451-b93e-139f81909106"
juliaArtifactName = "_artifact"
juliaRegistryName = "_registry"
)
var (
juliaHexPattern = regexp.MustCompile(`^[0-9a-f]{40,64}$`)
juliaUUIDPattern = regexp.MustCompile(`^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$`)
)
// JuliaHandler handles Julia Pkg server protocol requests.
//
// See https://pkgdocs.julialang.org/v1/registries/ and the PkgServer.jl
// reference implementation. The protocol is content-addressed: registry,
// package and artifact resources are all identified by git tree hashes
// and are immutable once published.
type JuliaHandler struct {
proxy *Proxy
upstreamURL string
mu sync.RWMutex
names map[string]string
namesHash string
loadMu sync.Mutex
}
// NewJuliaHandler creates a new Julia Pkg server handler.
func NewJuliaHandler(proxy *Proxy, _ string) *JuliaHandler {
return &JuliaHandler{
proxy: proxy,
upstreamURL: juliaUpstream,
names: make(map[string]string),
}
}
// Routes returns the HTTP handler for Julia requests.
func (h *JuliaHandler) Routes() http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("GET /registries", h.handleRegistries)
mux.HandleFunc("GET /registries.eager", h.handleRegistries)
mux.HandleFunc("GET /registries.conservative", h.handleRegistries)
mux.HandleFunc("GET /registry/{uuid}/{hash}", h.handleRegistry)
mux.HandleFunc("GET /package/{uuid}/{hash}", h.handlePackage)
mux.HandleFunc("GET /artifact/{hash}", h.handleArtifact)
mux.HandleFunc("GET /meta", h.proxyUpstream)
return mux
}
// handleRegistries serves the list of available registries. This is the only
// mutable endpoint in the protocol so it goes through the metadata cache.
func (h *JuliaHandler) handleRegistries(w http.ResponseWriter, r *http.Request) {
cacheKey := strings.TrimPrefix(r.URL.Path, "/")
h.proxy.ProxyCached(w, r, h.upstreamURL+r.URL.Path, "julia", cacheKey, "*/*")
}
// handleRegistry serves an immutable registry tarball and refreshes the
// UUID→name map from its Registry.toml.
func (h *JuliaHandler) handleRegistry(w http.ResponseWriter, r *http.Request) {
uuid := r.PathValue("uuid")
hash := r.PathValue("hash")
if !validJuliaUUID(uuid) || !juliaHexPattern.MatchString(hash) {
http.Error(w, "invalid registry reference", http.StatusBadRequest)
return
}
h.proxy.Logger.Info("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)
if err != nil {
h.proxy.serveArtifactError(w, err, "failed to fetch registry")
return
}
go h.refreshNamesFromRegistry(uuid, hash)
ServeArtifact(w, result)
}
// handlePackage serves an immutable package source tarball.
func (h *JuliaHandler) handlePackage(w http.ResponseWriter, r *http.Request) {
uuid := r.PathValue("uuid")
hash := r.PathValue("hash")
if !validJuliaUUID(uuid) || !juliaHexPattern.MatchString(hash) {
http.Error(w, "invalid package reference", http.StatusBadRequest)
return
}
if err := h.ensureNames(r.Context()); err != nil {
h.proxy.Logger.Warn("julia name map unavailable, using uuid", "error", err)
}
name := h.resolveName(uuid)
h.proxy.Logger.Info("julia package request", "name", name, "uuid", uuid, "hash", hash)
upstreamURL := h.upstreamURL + r.URL.Path
result, err := h.proxy.GetOrFetchArtifactFromURL(r.Context(), "julia", name, hash, hash+".tar.gz", upstreamURL)
if err != nil {
h.proxy.serveArtifactError(w, err, "failed to fetch package")
return
}
ServeArtifact(w, result)
}
// 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) {
hash := r.PathValue("hash")
if !juliaHexPattern.MatchString(hash) {
http.Error(w, "invalid artifact hash", http.StatusBadRequest)
return
}
h.proxy.Logger.Info("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)
if err != nil {
h.proxy.serveArtifactError(w, err, "failed to fetch artifact")
return
}
ServeArtifact(w, result)
}
// proxyUpstream forwards a request to the upstream Pkg server without caching.
func (h *JuliaHandler) proxyUpstream(w http.ResponseWriter, r *http.Request) {
h.proxy.ProxyUpstream(w, r, h.upstreamURL+r.URL.Path, nil)
}
// resolveName returns the human-readable package name for a UUID, falling
// back to the UUID itself if it is not present in the loaded registry.
func (h *JuliaHandler) resolveName(uuid string) string {
h.mu.RLock()
defer h.mu.RUnlock()
if name, ok := h.names[uuid]; ok {
return name
}
return uuid
}
// ensureNames lazily populates the UUID→name map from the General registry.
// Returns immediately if the map is already populated; otherwise blocks until
// a single in-flight load completes. Failed loads are retried on the next call.
func (h *JuliaHandler) ensureNames(ctx context.Context) error {
if h.namesLoaded() {
return nil
}
h.loadMu.Lock()
defer h.loadMu.Unlock()
if h.namesLoaded() {
return nil
}
return h.loadNamesFromUpstream(ctx)
}
func (h *JuliaHandler) namesLoaded() bool {
h.mu.RLock()
defer h.mu.RUnlock()
return len(h.names) > 0
}
// loadNamesFromUpstream fetches the current /registries listing, downloads the
// General registry tarball at its current hash, and parses Registry.toml.
func (h *JuliaHandler) loadNamesFromUpstream(ctx context.Context) error {
hash, err := h.fetchGeneralRegistryHash(ctx)
if err != nil {
return err
}
return h.loadRegistryTarball(ctx, juliaGeneralRegistryUUID, hash)
}
// fetchGeneralRegistryHash reads /registries 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)
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)
}
scanner := bufio.NewScanner(resp.Body)
for scanner.Scan() {
uuid, hash, ok := parseRegistryLine(scanner.Text())
if ok && uuid == juliaGeneralRegistryUUID {
return hash, nil
}
}
if err := scanner.Err(); err != nil {
return "", err
}
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 {
return
}
h.mu.RLock()
current := h.namesHash
h.mu.RUnlock()
if current == hash {
return
}
if err := h.loadRegistryTarball(context.Background(), uuid, hash); err != nil {
h.proxy.Logger.Warn("failed to refresh julia name map", "error", err)
}
}
// 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 {
url := fmt.Sprintf("%s/registry/%s/%s", h.upstreamURL, uuid, hash)
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
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 registry returned %d", resp.StatusCode)
}
names, err := extractRegistryNames(resp.Body)
if err != nil {
return err
}
h.mu.Lock()
h.names = names
h.namesHash = hash
h.mu.Unlock()
h.proxy.Logger.Info("loaded julia registry name map", "packages", len(names), "hash", hash)
return nil
}
// extractRegistryNames reads a gzipped registry tarball, finds Registry.toml
// at the root, and returns its [packages] table as a UUID→name map.
func extractRegistryNames(r io.Reader) (map[string]string, error) {
gz, err := gzip.NewReader(r)
if err != nil {
return nil, fmt.Errorf("opening gzip stream: %w", err)
}
defer func() { _ = gz.Close() }()
tr := tar.NewReader(gz)
for {
hdr, err := tr.Next()
if err == io.EOF {
return nil, fmt.Errorf("no Registry.toml in tarball")
}
if err != nil {
return nil, err
}
if strings.TrimPrefix(hdr.Name, "./") != "Registry.toml" {
continue
}
data, err := io.ReadAll(tr)
if err != nil {
return nil, err
}
return parseRegistryToml(data)
}
}
type juliaRegistryFile struct {
Packages map[string]struct {
Name string `toml:"name"`
} `toml:"packages"`
}
// parseRegistryToml decodes the [packages] table of a Registry.toml file.
func parseRegistryToml(data []byte) (map[string]string, error) {
var reg juliaRegistryFile
if _, err := toml.NewDecoder(bytes.NewReader(data)).Decode(&reg); err != nil {
return nil, fmt.Errorf("parsing Registry.toml: %w", err)
}
names := make(map[string]string, len(reg.Packages))
for uuid, pkg := range reg.Packages {
if pkg.Name != "" {
names[uuid] = pkg.Name
}
}
return names, nil
}
// parseRegistryLine parses a single line from /registries of the form
// "/registry/{uuid}/{hash}" and returns the uuid and hash.
func parseRegistryLine(line string) (uuid, hash string, ok bool) {
line = strings.TrimSpace(line)
line = strings.TrimPrefix(line, "/registry/")
uuid, hash, found := strings.Cut(line, "/")
if !found || !validJuliaUUID(uuid) || !juliaHexPattern.MatchString(hash) {
return "", "", false
}
return uuid, hash, true
}
// validJuliaUUID reports whether s looks like a lowercase RFC 4122 UUID.
func validJuliaUUID(s string) bool {
return juliaUUIDPattern.MatchString(s)
}

View file

@ -1,167 +0,0 @@
package handler
import (
"archive/tar"
"bytes"
"compress/gzip"
"log/slog"
"net/http"
"net/http/httptest"
"testing"
)
func TestJuliaParseRegistryLine(t *testing.T) {
tests := []struct {
line string
wantUUID string
wantHash string
wantOK bool
}{
{
"/registry/23338594-aafe-5451-b93e-139f81909106/342327538ed6c1ec54c69fa145e7b6bf5934201e",
"23338594-aafe-5451-b93e-139f81909106",
"342327538ed6c1ec54c69fa145e7b6bf5934201e",
true,
},
{
" /registry/23338594-aafe-5451-b93e-139f81909106/342327538ed6c1ec54c69fa145e7b6bf5934201e\n",
"23338594-aafe-5451-b93e-139f81909106",
"342327538ed6c1ec54c69fa145e7b6bf5934201e",
true,
},
{"/registry/not-a-uuid/0000", "", "", false},
{"junk", "", "", false},
{"", "", "", false},
}
for _, tt := range tests {
uuid, hash, ok := parseRegistryLine(tt.line)
if uuid != tt.wantUUID || hash != tt.wantHash || ok != tt.wantOK {
t.Errorf("parseRegistryLine(%q) = (%q, %q, %v), want (%q, %q, %v)",
tt.line, uuid, hash, ok, tt.wantUUID, tt.wantHash, tt.wantOK)
}
}
}
func TestJuliaValidUUID(t *testing.T) {
tests := []struct {
s string
want bool
}{
{"23338594-aafe-5451-b93e-139f81909106", true},
{"295af30f-e4ad-537b-8983-00126c2a3abe", true},
{"23338594-AAFE-5451-b93e-139f81909106", false},
{"23338594aafe5451b93e139f81909106", false},
{"23338594-aafe-5451-b93e-139f8190910", false},
{"23338594-aafe-5451-b93e-139f81909106-", false},
{"23338594-gafe-5451-b93e-139f81909106", false},
{"", false},
}
for _, tt := range tests {
if got := validJuliaUUID(tt.s); got != tt.want {
t.Errorf("validJuliaUUID(%q) = %v, want %v", tt.s, got, tt.want)
}
}
}
func TestJuliaParseRegistryToml(t *testing.T) {
data := []byte(`name = "General"
uuid = "23338594-aafe-5451-b93e-139f81909106"
[packages]
295af30f-e4ad-537b-8983-00126c2a3abe = { name = "Revise", path = "R/Revise" }
91a5bcdd-55d7-5caf-9e0b-520d859cae80 = { name = "Plots", path = "P/Plots" }
`)
names, err := parseRegistryToml(data)
if err != nil {
t.Fatalf("parseRegistryToml: %v", err)
}
if got := names["295af30f-e4ad-537b-8983-00126c2a3abe"]; got != "Revise" {
t.Errorf("names[Revise uuid] = %q, want Revise", got)
}
if got := names["91a5bcdd-55d7-5caf-9e0b-520d859cae80"]; got != "Plots" {
t.Errorf("names[Plots uuid] = %q, want Plots", got)
}
if len(names) != 2 {
t.Errorf("len(names) = %d, want 2", len(names))
}
}
func TestJuliaExtractRegistryNames(t *testing.T) {
registryToml := `name = "General"
[packages]
295af30f-e4ad-537b-8983-00126c2a3abe = { name = "Revise", path = "R/Revise" }
`
var buf bytes.Buffer
gw := gzip.NewWriter(&buf)
tw := tar.NewWriter(gw)
for _, f := range []struct{ name, body string }{
{"R/Revise/Package.toml", "name = \"Revise\"\n"},
{"Registry.toml", registryToml},
} {
if err := tw.WriteHeader(&tar.Header{Name: f.name, Mode: 0o644, Size: int64(len(f.body))}); err != nil {
t.Fatalf("WriteHeader: %v", err)
}
if _, err := tw.Write([]byte(f.body)); err != nil {
t.Fatalf("Write: %v", err)
}
}
if err := tw.Close(); err != nil {
t.Fatalf("tar Close: %v", err)
}
if err := gw.Close(); err != nil {
t.Fatalf("gzip Close: %v", err)
}
names, err := extractRegistryNames(bytes.NewReader(buf.Bytes()))
if err != nil {
t.Fatalf("extractRegistryNames: %v", err)
}
if got := names["295af30f-e4ad-537b-8983-00126c2a3abe"]; got != "Revise" {
t.Errorf("names[Revise uuid] = %q, want Revise", got)
}
}
func TestJuliaResolveName(t *testing.T) {
h := &JuliaHandler{
proxy: &Proxy{Logger: slog.Default()},
names: map[string]string{
"295af30f-e4ad-537b-8983-00126c2a3abe": "Revise",
},
}
if got := h.resolveName("295af30f-e4ad-537b-8983-00126c2a3abe"); got != "Revise" {
t.Errorf("resolveName(known) = %q, want Revise", got)
}
if got := h.resolveName("00000000-0000-0000-0000-000000000000"); got != "00000000-0000-0000-0000-000000000000" {
t.Errorf("resolveName(unknown) = %q, want uuid fallback", got)
}
}
func TestJuliaRoutesValidation(t *testing.T) {
h := NewJuliaHandler(&Proxy{Logger: slog.Default()}, "")
routes := h.Routes()
tests := []struct {
path string
want int
}{
{"/package/not-a-uuid/342327538ed6c1ec54c69fa145e7b6bf5934201e", http.StatusBadRequest},
{"/package/295af30f-e4ad-537b-8983-00126c2a3abe/short", http.StatusBadRequest},
{"/registry/295af30f-e4ad-537b-8983-00126c2a3abe/zzzz", http.StatusBadRequest},
{"/artifact/nothex", http.StatusBadRequest},
{"/nope", http.StatusNotFound},
}
for _, tt := range tests {
req := httptest.NewRequest(http.MethodGet, tt.path, nil)
rr := httptest.NewRecorder()
routes.ServeHTTP(rr, req)
if rr.Code != tt.want {
t.Errorf("GET %s = %d, want %d", tt.path, rr.Code, tt.want)
}
}
}

View file

@ -1,41 +1,30 @@
package handler package handler
import ( import (
"errors"
"fmt" "fmt"
"io"
"net/http" "net/http"
"path" "path"
"strings" "strings"
) )
const ( const (
mavenCentralUpstream = "https://repo1.maven.org/maven2" mavenUpstream = "https://repo1.maven.org/maven2"
gradlePluginPortalUpstream = "https://plugins.gradle.org/m2"
minMavenParts = 4 // group path segments + artifact + version + filename
) )
// MavenHandler handles Maven repository protocol requests. // MavenHandler handles Maven repository protocol requests.
type MavenHandler struct { type MavenHandler struct {
proxy *Proxy proxy *Proxy
upstreamURL string upstreamURL string
pluginPortalUpstreamURL string proxyURL string
proxyURL string
} }
// NewMavenHandler creates a new Maven repository handler. // NewMavenHandler creates a new Maven repository handler.
func NewMavenHandler(proxy *Proxy, proxyURL, upstreamURL, pluginPortalUpstreamURL string) *MavenHandler { func NewMavenHandler(proxy *Proxy, proxyURL string) *MavenHandler {
if strings.TrimSpace(upstreamURL) == "" {
upstreamURL = mavenCentralUpstream
}
if strings.TrimSpace(pluginPortalUpstreamURL) == "" {
pluginPortalUpstreamURL = gradlePluginPortalUpstream
}
return &MavenHandler{ return &MavenHandler{
proxy: proxy, proxy: proxy,
upstreamURL: strings.TrimSuffix(upstreamURL, "/"), upstreamURL: mavenUpstream,
pluginPortalUpstreamURL: strings.TrimSuffix(pluginPortalUpstreamURL, "/"), proxyURL: strings.TrimSuffix(proxyURL, "/"),
proxyURL: strings.TrimSuffix(proxyURL, "/"),
} }
} }
@ -62,7 +51,8 @@ func (h *MavenHandler) handleRequest(w http.ResponseWriter, r *http.Request) {
filename := path.Base(urlPath) filename := path.Base(urlPath)
if h.isMetadataFile(filename) { if h.isMetadataFile(filename) {
h.handleMetadata(w, r, urlPath) // Proxy metadata without caching
h.proxyUpstream(w, r)
return return
} }
@ -76,32 +66,6 @@ func (h *MavenHandler) handleRequest(w http.ResponseWriter, r *http.Request) {
h.proxyUpstream(w, r) h.proxyUpstream(w, r)
} }
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, "*/*")
}
}
if err != nil {
if errors.Is(err, ErrUpstreamNotFound) {
http.Error(w, "not found", http.StatusNotFound)
return
}
h.proxy.Logger.Error("metadata fetch failed", "error", err)
http.Error(w, "failed to fetch from upstream", http.StatusBadGateway)
return
}
h.proxy.writeMetadataCachedResponse(w, r, "maven", cacheKey, body, contentType)
}
// handleDownload serves an artifact file, fetching and caching from upstream if needed. // 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, urlPath string) {
// Parse Maven path: group/artifact/version/filename // Parse Maven path: group/artifact/version/filename
@ -122,15 +86,8 @@ func (h *MavenHandler) handleDownload(w http.ResponseWriter, r *http.Request, ur
result, err := h.proxy.GetOrFetchArtifactFromURL(r.Context(), "maven", name, version, filename, upstreamURL) result, err := h.proxy.GetOrFetchArtifactFromURL(r.Context(), "maven", name, version, filename, upstreamURL)
if err != nil { if err != nil {
if errors.Is(err, ErrUpstreamNotFound) { h.proxy.Logger.Error("failed to get artifact", "error", err)
pluginPortalURL := fmt.Sprintf("%s/%s", h.pluginPortalUpstreamURL, urlPath) http.Error(w, "failed to fetch artifact", http.StatusBadGateway)
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)
}
}
if err != nil {
h.proxy.serveArtifactError(w, err, "failed to fetch artifact")
return return
} }
@ -142,7 +99,7 @@ func (h *MavenHandler) handleDownload(w http.ResponseWriter, r *http.Request, ur
// -> ("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")
func (h *MavenHandler) parsePath(urlPath string) (group, artifact, version, filename string) { func (h *MavenHandler) parsePath(urlPath string) (group, artifact, version, filename string) {
parts := strings.Split(urlPath, "/") parts := strings.Split(urlPath, "/")
if len(parts) < minMavenParts { if len(parts) < 4 {
return "", "", "", "" return "", "", "", ""
} }
@ -158,7 +115,7 @@ func (h *MavenHandler) parsePath(urlPath string) (group, artifact, version, file
// isArtifactFile returns true if the filename looks like a Maven artifact. // isArtifactFile returns true if the filename looks like a Maven artifact.
func (h *MavenHandler) isArtifactFile(filename string) bool { func (h *MavenHandler) isArtifactFile(filename string) bool {
// Common artifact extensions // Common artifact extensions
extensions := []string{".jar", ".war", ".ear", ".pom", ".aar", ".klib", ".module"} extensions := []string{".jar", ".war", ".ear", ".pom", ".aar", ".klib"}
for _, ext := range extensions { for _, ext := range extensions {
if strings.HasSuffix(filename, ext) { if strings.HasSuffix(filename, ext) {
return true return true
@ -179,5 +136,30 @@ func (h *MavenHandler) isMetadataFile(filename string) bool {
// proxyUpstream forwards a request to Maven Central without caching. // proxyUpstream forwards a request to Maven Central without caching.
func (h *MavenHandler) proxyUpstream(w http.ResponseWriter, r *http.Request) { func (h *MavenHandler) proxyUpstream(w http.ResponseWriter, r *http.Request) {
h.proxy.ProxyUpstream(w, r, h.upstreamURL+r.URL.Path, nil) upstreamURL := h.upstreamURL + r.URL.Path
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
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
h.proxy.Logger.Error("upstream request failed", "error", err)
http.Error(w, "upstream request failed", http.StatusBadGateway)
return
}
defer func() { _ = resp.Body.Close() }()
for k, vv := range resp.Header {
for _, v := range vv {
w.Header().Add(k, v)
}
}
w.WriteHeader(resp.StatusCode)
_, _ = io.Copy(w, resp.Body)
} }

View file

@ -52,7 +52,6 @@ func TestMavenIsArtifactFile(t *testing.T) {
}{ }{
{"guava-32.1.3-jre.jar", true}, {"guava-32.1.3-jre.jar", true},
{"guava-32.1.3-jre.pom", true}, {"guava-32.1.3-jre.pom", true},
{"guava-32.1.3-jre.module", true},
{"app-1.0.war", true}, {"app-1.0.war", true},
{"lib-1.0.aar", true}, {"lib-1.0.aar", true},
{"maven-metadata.xml", false}, {"maven-metadata.xml", false},
@ -66,63 +65,3 @@ func TestMavenIsArtifactFile(t *testing.T) {
} }
} }
} }
func TestMavenIsMetadataFile(t *testing.T) {
h := &MavenHandler{}
tests := []struct {
name string
filename string
want bool
}{
{
name: "pom is artifact, not metadata",
filename: "com.diffplug.spotless.gradle.plugin-8.4.0.pom",
want: false,
},
{
name: "pom checksum is metadata",
filename: "com.diffplug.spotless.gradle.plugin-8.4.0.pom.sha1",
want: true,
},
{
name: "metadata file",
filename: "maven-metadata.xml",
want: true,
},
{
name: "metadata checksum",
filename: "maven-metadata.xml.sha256",
want: true,
},
{
name: "jar checksum is metadata",
filename: "guava-32.1.3-jre.jar.sha1",
want: true,
},
{
name: "asc signature is metadata",
filename: "guava-32.1.3-jre.jar.asc",
want: true,
},
{
name: "regular jar is not metadata",
filename: "guava-32.1.3-jre.jar",
want: false,
},
{
name: "pom checksum is metadata",
filename: "guava-32.1.3-jre.pom.sha1",
want: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := h.isMetadataFile(tt.filename)
if got != tt.want {
t.Errorf("isMetadataFile(%q) = %v, want %v", tt.filename, got, tt.want)
}
})
}
}

View file

@ -1,139 +0,0 @@
package handler
import (
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/git-pkgs/registries/fetch"
)
func TestArtifactDownloadUpstreamNotFoundReturns404(t *testing.T) {
tests := []struct {
name string
path string
handler func(p *Proxy) http.Handler
}{
{"debian", "/pool/main/n/nginx/nginx_1.18.0-6_amd64.deb",
func(p *Proxy) http.Handler { return NewDebianHandler(p, "http://localhost", "").Routes() }},
{"rpm", "/releases/39/Everything/x86_64/os/Packages/n/nginx-1.24.0-1.fc39.x86_64.rpm",
func(p *Proxy) http.Handler { return NewRPMHandler(p, "http://localhost").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",
func(p *Proxy) http.Handler { return NewPyPIHandler(p, "http://localhost").Routes() }},
{"cran", "/src/contrib/ggplot2_3.4.4.tar.gz",
func(p *Proxy) http.Handler { return NewCRANHandler(p, "http://localhost").Routes() }},
{"conda", "/conda-forge/linux-64/numpy-1.26.0-py311_0.tar.bz2",
func(p *Proxy) http.Handler { return NewCondaHandler(p, "http://localhost").Routes() }},
{"conan", "/v1/files/zlib/1.3.1/_/_/0/recipe/conan_sources.tgz",
func(p *Proxy) http.Handler { return NewConanHandler(p, "http://localhost").Routes() }},
{"gem", "/gems/rails-7.1.0.gem",
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() }},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
proxy, _, _, fetcher := setupTestProxy(t)
fetcher.fetchErr = fetch.ErrNotFound
srv := httptest.NewServer(tt.handler(proxy))
defer srv.Close()
resp, err := http.Get(srv.URL + tt.path)
if err != nil {
t.Fatalf("request failed: %v", err)
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != http.StatusNotFound {
t.Errorf("want 404 for missing upstream artifact, got %d", resp.StatusCode)
}
})
}
}
func TestJuliaPackageUpstreamNotFoundReturns404(t *testing.T) {
proxy, _, _, fetcher := setupTestProxy(t)
fetcher.fetchErr = fetch.ErrNotFound
dead := httptest.NewServer(http.NotFoundHandler())
defer dead.Close()
h := NewJuliaHandler(proxy, "http://localhost")
h.upstreamURL = dead.URL
srv := httptest.NewServer(h.Routes())
defer srv.Close()
resp, err := http.Get(srv.URL +
"/package/7876af07-990d-54b4-ab0e-23690620f79a/0123456789abcdef0123456789abcdef01234567")
if err != nil {
t.Fatalf("request failed: %v", err)
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != http.StatusNotFound {
t.Errorf("want 404 for missing upstream package, got %d", resp.StatusCode)
}
}
func TestComposerDownloadUpstreamNotFoundReturns404(t *testing.T) {
proxy, _, _, fetcher := setupTestProxy(t)
fetcher.fetchErr = fetch.ErrNotFound
meta := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/p2/monolog/monolog.json" {
_, _ = w.Write([]byte(`{
"packages": {
"monolog/monolog": [
{"version": "2.9.1", "dist": {"url": "https://example.com/monolog-2.9.1.zip", "type": "zip"}}
]
}
}`))
return
}
http.NotFound(w, r)
}))
defer meta.Close()
h := &ComposerHandler{proxy: proxy, repoURL: meta.URL, proxyURL: "http://localhost"}
srv := httptest.NewServer(h.Routes())
defer srv.Close()
resp, err := http.Get(srv.URL + "/files/monolog/monolog/2.9.1/monolog-2.9.1.zip")
if err != nil {
t.Fatalf("request failed: %v", err)
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != http.StatusNotFound {
t.Errorf("want 404 for missing upstream dist, got %d", resp.StatusCode)
}
}
func TestContainerBlobUpstreamNotFoundReturns404(t *testing.T) {
proxy, _, _, fetcher := setupTestProxy(t)
fetcher.fetchErr = fetch.ErrNotFound
h := &ContainerHandler{
proxy: proxy,
registryURL: "https://registry-1.docker.io",
proxyURL: "http://localhost:8080",
}
req := httptest.NewRequest(http.MethodGet,
"/library/nginx/blobs/sha256:abc123def456abc123def456abc123def456abc123def456abc123def456abcd", nil)
w := httptest.NewRecorder()
h.Routes().ServeHTTP(w, req)
if w.Code != http.StatusNotFound {
t.Errorf("want 404 for missing upstream blob, got %d; body: %s", w.Code, w.Body.String())
}
if !strings.Contains(w.Body.String(), "BLOB_UNKNOWN") {
t.Errorf("want BLOB_UNKNOWN error code in body, got: %s", w.Body.String())
}
}

View file

@ -1,83 +0,0 @@
package handler
import (
"context"
"errors"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/git-pkgs/registries/fetch"
)
func TestErrUpstreamNotFoundWrapsFetchErrNotFound(t *testing.T) {
if !errors.Is(ErrUpstreamNotFound, fetch.ErrNotFound) {
t.Fatal("ErrUpstreamNotFound does not wrap fetch.ErrNotFound")
}
}
func TestGetOrFetchArtifactFromURL_NotFound(t *testing.T) {
proxy, _, _, fetcher := setupTestProxy(t)
fetcher.fetchErr = fetch.ErrNotFound
_, err := proxy.GetOrFetchArtifactFromURL(context.Background(),
"maven", "org.example:missing", "1.0", "missing-1.0.jar",
"http://upstream.test/org/example/missing/1.0/missing-1.0.jar")
if !errors.Is(err, ErrUpstreamNotFound) {
t.Fatalf("want ErrUpstreamNotFound, got %v", err)
}
}
func TestMavenHandler_UpstreamNotFoundReturns404(t *testing.T) {
proxy, _, _, fetcher := setupTestProxy(t)
fetcher.fetchErr = fetch.ErrNotFound
h := NewMavenHandler(proxy, "http://localhost", "http://upstream.test", "http://portal.test")
srv := httptest.NewServer(h.Routes())
defer srv.Close()
resp, err := http.Get(srv.URL + "/org/example/missing/1.0/missing-1.0.jar")
if err != nil {
t.Fatalf("request failed: %v", err)
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != http.StatusNotFound {
t.Errorf("want 404 for missing upstream artifact, got %d", resp.StatusCode)
}
}
func TestMavenHandler_PluginPortalFallback(t *testing.T) {
proxy, _, _, fetcher := setupTestProxy(t)
fetcher.fetchErrByURL = map[string]error{
"http://upstream.test/org/example/plugin/1.0/plugin-1.0.jar": fetch.ErrNotFound,
}
fetcher.artifact = &fetch.Artifact{
Body: io.NopCloser(strings.NewReader("portal artifact")),
ContentType: "application/java-archive",
}
h := NewMavenHandler(proxy, "http://localhost", "http://upstream.test", "http://portal.test")
srv := httptest.NewServer(h.Routes())
defer srv.Close()
resp, err := http.Get(srv.URL + "/org/example/plugin/1.0/plugin-1.0.jar")
if err != nil {
t.Fatalf("request failed: %v", err)
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != http.StatusOK {
t.Fatalf("want 200 via plugin portal fallback, got %d", resp.StatusCode)
}
body, _ := io.ReadAll(resp.Body)
if string(body) != "portal artifact" {
t.Errorf("want portal artifact body, got %q", body)
}
if fetcher.fetchedURL != "http://portal.test/org/example/plugin/1.0/plugin-1.0.jar" {
t.Errorf("fallback did not hit plugin portal, last URL: %s", fetcher.fetchedURL)
}
}

View file

@ -2,19 +2,15 @@ package handler
import ( import (
"encoding/json" "encoding/json"
"errors"
"fmt" "fmt"
"io"
"net/http" "net/http"
"net/url" "net/url"
"sort"
"strings" "strings"
"time"
) )
const ( const (
npmUpstream = "https://registry.npmjs.org" npmUpstream = "https://registry.npmjs.org"
npmAcceptDefault = "application/vnd.npm.install-v1+json;q=1.0, application/json;q=0.8"
scopedParts = 2 // scope + name in scoped packages
) )
// NPMHandler handles npm registry protocol requests. // NPMHandler handles npm registry protocol requests.
@ -25,14 +21,10 @@ type NPMHandler struct {
} }
// NewNPMHandler creates a new npm protocol handler. // NewNPMHandler creates a new npm protocol handler.
func NewNPMHandler(proxy *Proxy, proxyURL, upstreamURL string) *NPMHandler { func NewNPMHandler(proxy *Proxy, proxyURL string) *NPMHandler {
if strings.TrimSpace(upstreamURL) == "" {
upstreamURL = npmUpstream
}
return &NPMHandler{ return &NPMHandler{
proxy: proxy, proxy: proxy,
upstreamURL: strings.TrimSuffix(upstreamURL, "/"), upstreamURL: npmUpstream,
proxyURL: strings.TrimSuffix(proxyURL, "/"), proxyURL: strings.TrimSuffix(proxyURL, "/"),
} }
} }
@ -69,26 +61,37 @@ func (h *NPMHandler) handlePackageMetadata(w http.ResponseWriter, r *http.Reques
h.proxy.Logger.Info("npm metadata request", "package", packageName) h.proxy.Logger.Info("npm metadata request", "package", packageName)
// Fetch metadata from upstream
upstreamURL := fmt.Sprintf("%s/%s", h.upstreamURL, url.PathEscape(packageName)) upstreamURL := fmt.Sprintf("%s/%s", h.upstreamURL, url.PathEscape(packageName))
// Prefer the smaller abbreviated packument format but include application/json req, err := http.NewRequestWithContext(r.Context(), http.MethodGet, upstreamURL, nil)
// as a fallback so upstreams that reject the abbreviated type (e.g. JFrog if err != nil {
// Artifactory, which returns 406) can still respond with full metadata. JSONError(w, http.StatusInternalServerError, "failed to create request")
// When cooldown is enabled we must use full metadata exclusively because the return
// abbreviated format omits the "time" map required for version age filtering. }
accept := npmAcceptDefault req.Header.Set("Accept", "application/json")
if h.proxy.Cooldown != nil && h.proxy.Cooldown.Enabled() {
accept = contentTypeJSON resp, err := http.DefaultClient.Do(req)
if err != nil {
h.proxy.Logger.Error("failed to fetch upstream metadata", "error", err)
JSONError(w, http.StatusBadGateway, "failed to fetch from upstream")
return
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode == http.StatusNotFound {
JSONError(w, http.StatusNotFound, "package not found")
return
}
if resp.StatusCode != http.StatusOK {
JSONError(w, http.StatusBadGateway, fmt.Sprintf("upstream returned %d", resp.StatusCode))
return
} }
body, _, err := h.proxy.FetchOrCacheMetadata(r.Context(), "npm", packageName, upstreamURL, accept) // Parse and rewrite tarball URLs
body, err := io.ReadAll(resp.Body)
if err != nil { if err != nil {
if errors.Is(err, ErrUpstreamNotFound) { JSONError(w, http.StatusInternalServerError, "failed to read response")
JSONError(w, http.StatusNotFound, "package not found")
return
}
h.proxy.Logger.Error("failed to fetch npm metadata", "error", err)
JSONError(w, http.StatusBadGateway, "failed to fetch from upstream")
return return
} }
@ -96,19 +99,18 @@ func (h *NPMHandler) handlePackageMetadata(w http.ResponseWriter, r *http.Reques
if err != nil { if err != nil {
// If rewriting fails, just proxy the original // If rewriting fails, just proxy the original
h.proxy.Logger.Warn("failed to rewrite metadata, proxying original", "error", err) h.proxy.Logger.Warn("failed to rewrite metadata, proxying original", "error", err)
w.Header().Set("Content-Type", contentTypeJSON) w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK) w.WriteHeader(http.StatusOK)
_, _ = w.Write(body) _, _ = w.Write(body)
return return
} }
w.Header().Set("Content-Type", contentTypeJSON) w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK) w.WriteHeader(http.StatusOK)
_, _ = w.Write(rewritten) _, _ = w.Write(rewritten)
} }
// rewriteMetadata rewrites tarball URLs in npm package metadata to point at this proxy. // rewriteMetadata rewrites tarball URLs in npm package metadata to point at this proxy.
// If cooldown is enabled, versions published too recently are filtered out.
func (h *NPMHandler) rewriteMetadata(packageName string, body []byte) ([]byte, error) { func (h *NPMHandler) rewriteMetadata(packageName string, body []byte) ([]byte, error) {
var metadata map[string]any var metadata map[string]any
if err := json.Unmarshal(body, &metadata); err != nil { if err := json.Unmarshal(body, &metadata); err != nil {
@ -121,71 +123,6 @@ func (h *NPMHandler) rewriteMetadata(packageName string, body []byte) ([]byte, e
return body, nil // No versions to rewrite return body, nil // No versions to rewrite
} }
h.applyCooldownFiltering(metadata, versions, packageName)
h.rewriteTarballURLs(versions, packageName)
return json.Marshal(metadata)
}
// applyCooldownFiltering removes versions that are too recently published,
// and updates dist-tags.latest if the current latest was filtered out.
func (h *NPMHandler) applyCooldownFiltering(metadata map[string]any, versions map[string]any, packageName string) {
if h.proxy.Cooldown == nil || !h.proxy.Cooldown.Enabled() {
return
}
timeMap, _ := metadata["time"].(map[string]any)
if timeMap == nil {
return
}
packagePURL := canonicalPackagePURL("npm", packageName)
for version := range versions {
publishedStr, ok := timeMap[version].(string)
if !ok {
continue
}
publishedAt, err := time.Parse(time.RFC3339, publishedStr)
if err != nil {
continue
}
if !h.proxy.Cooldown.IsAllowed("npm", packagePURL, publishedAt) {
h.proxy.Logger.Info("cooldown: filtering npm version",
"package", packageName, "version", version,
"published", publishedStr)
delete(versions, version)
delete(timeMap, version)
}
}
h.updateDistTagsLatest(metadata, versions, timeMap)
}
// updateDistTagsLatest updates the dist-tags.latest field if the current latest
// version was removed by cooldown filtering.
func (h *NPMHandler) updateDistTagsLatest(metadata, versions, timeMap map[string]any) {
distTags, ok := metadata["dist-tags"].(map[string]any)
if !ok {
return
}
latest, ok := distTags["latest"].(string)
if !ok {
return
}
if _, exists := versions[latest]; exists {
return
}
if newLatest := h.findNewestVersion(versions, timeMap); newLatest != "" {
distTags["latest"] = newLatest
}
}
// rewriteTarballURLs rewrites all tarball URLs in version entries to point at this proxy.
func (h *NPMHandler) rewriteTarballURLs(versions map[string]any, packageName string) {
for version, vdata := range versions { for version, vdata := range versions {
vmap, ok := vdata.(map[string]any) vmap, ok := vdata.(map[string]any)
if !ok { if !ok {
@ -197,56 +134,25 @@ func (h *NPMHandler) rewriteTarballURLs(versions map[string]any, packageName str
continue continue
} }
tarball, ok := dist["tarball"].(string) if tarball, ok := dist["tarball"].(string); ok {
if !ok { // Extract filename from tarball URL
continue filename := tarball
} if idx := strings.LastIndex(tarball, "/"); idx >= 0 {
filename = tarball[idx+1:]
filename := tarball
if idx := strings.LastIndex(tarball, "/"); idx >= 0 {
filename = tarball[idx+1:]
}
escapedName := url.PathEscape(packageName)
newTarball := fmt.Sprintf("%s/npm/%s/-/%s", h.proxyURL, escapedName, filename)
dist["tarball"] = newTarball
h.proxy.Logger.Debug("rewrote tarball URL",
"package", packageName, "version", version,
"old", tarball, "new", newTarball)
}
}
// findNewestVersion returns the version string with the most recent timestamp
// from the remaining versions, using the time map.
func (h *NPMHandler) findNewestVersion(versions map[string]any, timeMap map[string]any) string {
if timeMap == nil {
return ""
}
type versionTime struct {
version string
t time.Time
}
var vts []versionTime
for v := range versions {
if ts, ok := timeMap[v].(string); ok {
if t, err := time.Parse(time.RFC3339, ts); err == nil {
vts = append(vts, versionTime{v, t})
} }
// Rewrite to our proxy URL
escapedName := url.PathEscape(packageName)
newTarball := fmt.Sprintf("%s/npm/%s/-/%s", h.proxyURL, escapedName, filename)
dist["tarball"] = newTarball
h.proxy.Logger.Debug("rewrote tarball URL",
"package", packageName, "version", version,
"old", tarball, "new", newTarball)
} }
} }
if len(vts) == 0 { return json.Marshal(metadata)
return ""
}
sort.Slice(vts, func(i, j int) bool {
return vts[i].t.After(vts[j].t)
})
return vts[0].version
} }
// handleDownload serves a package tarball, fetching and caching from upstream if needed. // handleDownload serves a package tarball, fetching and caching from upstream if needed.
@ -268,27 +174,8 @@ func (h *NPMHandler) handleDownload(w http.ResponseWriter, r *http.Request) {
h.proxy.Logger.Info("npm download request", h.proxy.Logger.Info("npm download request",
"package", packageName, "version", version, "filename", filename) "package", packageName, "version", version, "filename", filename)
if h.versionInCooldown(r, packageName, version) { result, err := h.proxy.GetOrFetchArtifact(r.Context(), "npm", packageName, version, filename)
h.proxy.Logger.Info("cooldown: withholding npm tarball",
"package", packageName, "version", version)
JSONError(w, http.StatusNotFound, "version not found")
return
}
downloadURL := fmt.Sprintf(
"%s/%s/-/%s",
h.upstreamURL,
escapeNPMDownloadPackage(packageName),
url.PathEscape(filename),
)
result, err := h.proxy.GetOrFetchArtifactFromURL(
r.Context(), "npm", packageName, version, filename, downloadURL,
)
if err != nil { if err != nil {
if errors.Is(err, ErrUpstreamNotFound) {
JSONError(w, http.StatusNotFound, "package not found")
return
}
h.proxy.Logger.Error("failed to get artifact", "error", err) h.proxy.Logger.Error("failed to get artifact", "error", err)
JSONError(w, http.StatusBadGateway, "failed to fetch package") JSONError(w, http.StatusBadGateway, "failed to fetch package")
return return
@ -297,58 +184,6 @@ func (h *NPMHandler) handleDownload(w http.ResponseWriter, r *http.Request) {
ServeArtifact(w, result) ServeArtifact(w, result)
} }
// versionInCooldown reports whether a version is still inside the cooldown
// window. Filtering the packument is not enough on its own: tarball URLs are
// predictable and lockfiles record them directly, so `npm ci` reaches the
// download path without ever requesting metadata.
//
// The packument is served from the metadata cache, so this normally costs no
// extra upstream request. A version with no usable publish time is allowed
// through, matching how applyCooldownFiltering treats it.
func (h *NPMHandler) versionInCooldown(r *http.Request, packageName, version string) bool {
if h.proxy.Cooldown == nil || !h.proxy.Cooldown.Enabled() {
return false
}
upstreamURL := fmt.Sprintf("%s/%s", h.upstreamURL, url.PathEscape(packageName))
body, _, err := h.proxy.FetchOrCacheMetadata(r.Context(), "npm", packageName, upstreamURL, contentTypeJSON)
if err != nil {
h.proxy.Logger.Warn("cooldown: could not fetch npm metadata for download check",
"package", packageName, "version", version, "error", err)
return false
}
var metadata struct {
Time map[string]string `json:"time"`
}
if err := json.Unmarshal(body, &metadata); err != nil {
h.proxy.Logger.Warn("cooldown: could not parse npm metadata for download check",
"package", packageName, "version", version, "error", err)
return false
}
published, ok := metadata.Time[version]
if !ok {
return false
}
publishedAt, err := time.Parse(time.RFC3339, published)
if err != nil {
return false
}
return !h.proxy.Cooldown.IsAllowed("npm", canonicalPackagePURL("npm", packageName), publishedAt)
}
func escapeNPMDownloadPackage(packageName string) string {
scope, name, scoped := strings.Cut(packageName, "/")
if scoped && strings.HasPrefix(scope, "@") && len(scope) > 1 && name != "" && !strings.Contains(name, "/") {
return url.PathEscape(scope) + "/" + url.PathEscape(name)
}
return url.PathEscape(packageName)
}
// extractPackageName extracts the package name from the request path. // extractPackageName extracts the package name from the request path.
// Handles both scoped (@scope/name) and unscoped (name) packages. // Handles both scoped (@scope/name) and unscoped (name) packages.
func (h *NPMHandler) extractPackageName(r *http.Request) string { func (h *NPMHandler) extractPackageName(r *http.Request) string {
@ -402,7 +237,7 @@ func (h *NPMHandler) extractVersionFromFilename(packageName, filename string) st
// For scoped packages, the filename uses the short name // For scoped packages, the filename uses the short name
shortName := packageName shortName := packageName
if strings.Contains(packageName, "/") { if strings.Contains(packageName, "/") {
parts := strings.SplitN(packageName, "/", scopedParts) parts := strings.SplitN(packageName, "/", 2)
shortName = parts[1] shortName = parts[1]
} }

View file

@ -2,24 +2,15 @@ package handler
import ( import (
"encoding/json" "encoding/json"
"io"
"log/slog" "log/slog"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
"strings"
"testing" "testing"
"time"
"github.com/git-pkgs/cooldown"
"github.com/git-pkgs/registries/fetch"
) )
const testVersion100 = "1.0.0"
func testProxy() *Proxy { func testProxy() *Proxy {
return &Proxy{ return &Proxy{
Logger: slog.Default(), Logger: slog.Default(),
HTTPClient: http.DefaultClient,
} }
} }
@ -35,9 +26,9 @@ func TestNPMExtractVersionFromFilename(t *testing.T) {
{"@babel/core", "core-7.23.0.tgz", "7.23.0"}, {"@babel/core", "core-7.23.0.tgz", "7.23.0"},
{"@types/node", "node-20.10.0.tgz", "20.10.0"}, {"@types/node", "node-20.10.0.tgz", "20.10.0"},
{"express", "express-4.18.2.tgz", "4.18.2"}, {"express", "express-4.18.2.tgz", "4.18.2"},
{"lodash", "lodash.tgz", ""}, // no version {"lodash", "lodash.tgz", ""}, // no version
{"lodash", "lodash-4.17.21.zip", ""}, // wrong extension {"lodash", "lodash-4.17.21.zip", ""}, // wrong extension
{"lodash", "other-4.17.21.tgz", ""}, // wrong package name {"lodash", "other-4.17.21.tgz", ""}, // wrong package name
} }
for _, tt := range tests { for _, tt := range tests {
@ -49,86 +40,6 @@ func TestNPMExtractVersionFromFilename(t *testing.T) {
} }
} }
func TestNPMHandlerUsesConfiguredUpstream(t *testing.T) {
t.Run("metadata", func(t *testing.T) {
var requestPath, authHeader string
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
requestPath = r.URL.Path
authHeader = r.Header.Get("Authorization")
if authHeader != "Bearer npm-token" {
w.WriteHeader(http.StatusUnauthorized)
return
}
w.Header().Set("Content-Type", "application/json")
_, _ = io.WriteString(w, `{"versions":{}}`)
}))
defer upstream.Close()
proxy, _, _, _ := setupTestProxy(t)
proxy.HTTPClient = upstream.Client()
proxy.AuthForURL = func(string) (string, string) {
return "Authorization", "Bearer npm-token"
}
h := NewNPMHandler(proxy, "http://proxy.test", upstream.URL+"/root/")
req := httptest.NewRequest(http.MethodGet, "/testpkg", nil)
w := httptest.NewRecorder()
h.Routes().ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("status = %d, want %d; body: %s", w.Code, http.StatusOK, w.Body.String())
}
if requestPath != "/root/testpkg" {
t.Errorf("upstream path = %q, want %q", requestPath, "/root/testpkg")
}
if authHeader != "Bearer npm-token" {
t.Errorf("Authorization = %q, want %q", authHeader, "Bearer npm-token")
}
})
t.Run("download", func(t *testing.T) {
proxy, _, _, artifactFetcher := setupTestProxy(t)
artifactFetcher.artifact = &fetch.Artifact{
Body: io.NopCloser(strings.NewReader("package")),
ContentType: "application/gzip",
}
h := NewNPMHandler(proxy, "http://proxy.test", "https://npm.example.test/root/")
req := httptest.NewRequest(http.MethodGet, "/testpkg/-/testpkg-1.0.0.tgz", nil)
w := httptest.NewRecorder()
h.Routes().ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("status = %d, want %d; body: %s", w.Code, http.StatusOK, w.Body.String())
}
want := "https://npm.example.test/root/testpkg/-/testpkg-1.0.0.tgz"
if artifactFetcher.fetchedURL != want {
t.Errorf("fetched URL = %q, want %q", artifactFetcher.fetchedURL, want)
}
})
t.Run("scoped download", func(t *testing.T) {
proxy, _, _, artifactFetcher := setupTestProxy(t)
artifactFetcher.artifact = &fetch.Artifact{
Body: io.NopCloser(strings.NewReader("package")),
ContentType: "application/gzip",
}
h := NewNPMHandler(proxy, "http://proxy.test", "https://npm.example.test/root/")
req := httptest.NewRequest(http.MethodGet, "/@scope/name/-/name-1.0.0.tgz", nil)
w := httptest.NewRecorder()
h.Routes().ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("status = %d, want %d; body: %s", w.Code, http.StatusOK, w.Body.String())
}
want := "https://npm.example.test/root/@scope/name/-/name-1.0.0.tgz"
if artifactFetcher.fetchedURL != want {
t.Errorf("fetched URL = %q, want %q", artifactFetcher.fetchedURL, want)
}
})
}
func TestNPMRewriteMetadata(t *testing.T) { func TestNPMRewriteMetadata(t *testing.T) {
h := &NPMHandler{ h := &NPMHandler{
proxy: testProxy(), proxy: testProxy(),
@ -257,7 +168,7 @@ func TestNPMHandlerMetadataProxy(t *testing.T) {
// Check that tarball URL was rewritten // Check that tarball URL was rewritten
versions := result["versions"].(map[string]any) versions := result["versions"].(map[string]any)
v := versions[testVersion100].(map[string]any) v := versions["1.0.0"].(map[string]any)
dist := v["dist"].(map[string]any) dist := v["dist"].(map[string]any)
tarball := dist["tarball"].(string) tarball := dist["tarball"].(string)
@ -266,172 +177,6 @@ func TestNPMHandlerMetadataProxy(t *testing.T) {
} }
} }
func TestNPMRewriteMetadataCooldown(t *testing.T) {
now := time.Now()
old := now.Add(-10 * 24 * time.Hour).Format(time.RFC3339)
recent := now.Add(-1 * time.Hour).Format(time.RFC3339)
proxy := testProxy()
proxy.Cooldown = &cooldown.Config{Default: "3d"}
h := &NPMHandler{
proxy: proxy,
proxyURL: "http://localhost:8080",
}
input := `{
"name": "testpkg",
"dist-tags": {"latest": "2.0.0"},
"time": {
"1.0.0": "` + old + `",
"2.0.0": "` + recent + `"
},
"versions": {
"1.0.0": {
"name": "testpkg",
"version": "1.0.0",
"dist": {
"tarball": "https://registry.npmjs.org/testpkg/-/testpkg-1.0.0.tgz"
}
},
"2.0.0": {
"name": "testpkg",
"version": "2.0.0",
"dist": {
"tarball": "https://registry.npmjs.org/testpkg/-/testpkg-2.0.0.tgz"
}
}
}
}`
output, err := h.rewriteMetadata("testpkg", []byte(input))
if err != nil {
t.Fatalf("rewriteMetadata failed: %v", err)
}
var result map[string]any
if err := json.Unmarshal(output, &result); err != nil {
t.Fatalf("failed to parse output: %v", err)
}
versions := result["versions"].(map[string]any)
// Old version should remain
if _, ok := versions[testVersion100]; !ok {
t.Error("version 1.0.0 should not be filtered")
}
// Recent version should be filtered
if _, ok := versions["2.0.0"]; ok {
t.Error("version 2.0.0 should be filtered by cooldown")
}
// dist-tags.latest should be updated to 1.0.0
distTags := result["dist-tags"].(map[string]any)
if distTags["latest"] != testVersion100 {
t.Errorf("dist-tags.latest = %q, want %q", distTags["latest"], testVersion100)
}
}
func TestNPMRewriteMetadataCooldownExemptPackage(t *testing.T) {
now := time.Now()
recent := now.Add(-1 * time.Hour).Format(time.RFC3339)
proxy := testProxy()
proxy.Cooldown = &cooldown.Config{
Default: "3d",
Packages: map[string]string{"pkg:npm/testpkg": "0"},
}
h := &NPMHandler{
proxy: proxy,
proxyURL: "http://localhost:8080",
}
input := `{
"name": "testpkg",
"time": {"1.0.0": "` + recent + `"},
"versions": {
"1.0.0": {
"name": "testpkg",
"version": "1.0.0",
"dist": {"tarball": "https://registry.npmjs.org/testpkg/-/testpkg-1.0.0.tgz"}
}
}
}`
output, err := h.rewriteMetadata("testpkg", []byte(input))
if err != nil {
t.Fatalf("rewriteMetadata failed: %v", err)
}
var result map[string]any
if err := json.Unmarshal(output, &result); err != nil {
t.Fatalf("failed to parse output: %v", err)
}
versions := result["versions"].(map[string]any)
if _, ok := versions[testVersion100]; !ok {
t.Error("exempt package version should not be filtered")
}
}
func TestNPMHandlerUsesAbbreviatedMetadata(t *testing.T) {
var gotAccept string
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
gotAccept = r.Header.Get("Accept")
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()
t.Run("no cooldown uses combined accept header", func(t *testing.T) {
h := &NPMHandler{
proxy: testProxy(),
upstreamURL: upstream.URL,
proxyURL: "http://proxy.local",
}
req := httptest.NewRequest(http.MethodGet, "/testpkg", nil)
w := httptest.NewRecorder()
h.handlePackageMetadata(w, req)
if gotAccept != npmAcceptDefault {
t.Errorf("Accept = %q, want %q", gotAccept, npmAcceptDefault)
}
})
t.Run("cooldown enabled uses full metadata only", func(t *testing.T) {
proxy := testProxy()
proxy.Cooldown = &cooldown.Config{Default: "3d"}
h := &NPMHandler{
proxy: proxy,
upstreamURL: upstream.URL,
proxyURL: "http://proxy.local",
}
req := httptest.NewRequest(http.MethodGet, "/testpkg", nil)
w := httptest.NewRecorder()
h.handlePackageMetadata(w, req)
if gotAccept != contentTypeJSON {
t.Errorf("Accept = %q, want %q (cooldown requires full metadata)", gotAccept, contentTypeJSON)
}
})
}
func TestNPMHandlerMetadataNotFound(t *testing.T) { func TestNPMHandlerMetadataNotFound(t *testing.T) {
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNotFound) w.WriteHeader(http.StatusNotFound)
@ -454,81 +199,3 @@ func TestNPMHandlerMetadataNotFound(t *testing.T) {
t.Errorf("status = %d, want %d", w.Code, http.StatusNotFound) t.Errorf("status = %d, want %d", w.Code, http.StatusNotFound)
} }
} }
func TestNPMDownloadCooldown(t *testing.T) {
now := time.Now()
packument := `{
"name": "leftpad",
"dist-tags": {"latest": "2.0.0"},
"time": {
"1.0.0": "` + now.Add(-30*24*time.Hour).Format(time.RFC3339) + `",
"2.0.0": "` + now.Add(-1*time.Hour).Format(time.RFC3339) + `"
},
"versions": {"1.0.0": {}, "2.0.0": {}}
}`
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", contentTypeJSON)
_, _ = io.WriteString(w, packument)
}))
defer upstream.Close()
tests := []struct {
name string
version string
wantStatus int
}{
{"published before the window serves the tarball", testVersion100, http.StatusOK},
{"published inside the window is withheld", "2.0.0", http.StatusNotFound},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
proxy, _, _, fetcher := setupTestProxy(t)
proxy.HTTPClient = upstream.Client()
proxy.Cooldown = &cooldown.Config{Default: "7d"}
fetcher.artifact = &fetch.Artifact{
Body: io.NopCloser(strings.NewReader("tarball data")),
ContentType: "application/octet-stream",
}
h := NewNPMHandler(proxy, "http://proxy.test", upstream.URL)
srv := httptest.NewServer(h.Routes())
defer srv.Close()
resp, err := http.Get(srv.URL + "/leftpad/-/leftpad-" + tt.version + ".tgz")
if err != nil {
t.Fatalf("request failed: %v", err)
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != tt.wantStatus {
t.Errorf("status = %d, want %d", resp.StatusCode, tt.wantStatus)
}
if tt.wantStatus == http.StatusNotFound && fetcher.fetchCalled {
t.Error("fetched a version that is still inside the cooldown window")
}
})
}
}
func TestNPMDownloadCooldownDisabled(t *testing.T) {
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
t.Error("metadata must not be fetched when cooldown is disabled")
w.WriteHeader(http.StatusInternalServerError)
}))
defer upstream.Close()
proxy, _, _, fetcher := setupTestProxy(t)
proxy.HTTPClient = upstream.Client()
fetcher.artifact = &fetch.Artifact{
Body: io.NopCloser(strings.NewReader("tarball data")),
ContentType: "application/octet-stream",
}
h := NewNPMHandler(proxy, "http://proxy.test", upstream.URL)
if h.versionInCooldown(httptest.NewRequest(http.MethodGet, "/", nil), "leftpad", testVersion100) {
t.Error("versionInCooldown = true, want false when cooldown is not configured")
}
}

View file

@ -2,12 +2,10 @@ package handler
import ( import (
"encoding/json" "encoding/json"
"errors"
"fmt" "fmt"
"io" "io"
"net/http" "net/http"
"strings" "strings"
"time"
) )
const ( const (
@ -42,7 +40,7 @@ func (h *NuGetHandler) Routes() http.Handler {
mux.HandleFunc("GET /v3-flatcontainer/{id}/index.json", h.proxyUpstream) mux.HandleFunc("GET /v3-flatcontainer/{id}/index.json", h.proxyUpstream)
// Registration (package metadata) - use prefix matching since {version}.json isn't allowed // Registration (package metadata) - use prefix matching since {version}.json isn't allowed
mux.HandleFunc("GET /v3/registration5-gz-semver2/", h.handleRegistration) mux.HandleFunc("GET /v3/registration5-gz-semver2/", h.proxyUpstream)
// Search // Search
mux.HandleFunc("GET /query", h.proxyUpstream) mux.HandleFunc("GET /query", h.proxyUpstream)
@ -59,16 +57,31 @@ func (h *NuGetHandler) handleServiceIndex(w http.ResponseWriter, r *http.Request
upstreamURL := h.upstreamURL + "/v3/index.json" upstreamURL := h.upstreamURL + "/v3/index.json"
body, _, err := h.proxy.FetchOrCacheMetadata(r.Context(), "nuget", "_service_index", upstreamURL) req, err := http.NewRequestWithContext(r.Context(), http.MethodGet, upstreamURL, nil)
if err != nil {
http.Error(w, "failed to create request", http.StatusInternalServerError)
return
}
resp, err := http.DefaultClient.Do(req)
if err != nil { if err != nil {
if errors.Is(err, ErrUpstreamNotFound) {
http.Error(w, "not found", http.StatusNotFound)
return
}
h.proxy.Logger.Error("upstream request failed", "error", err) h.proxy.Logger.Error("upstream request failed", "error", err)
http.Error(w, "upstream request failed", http.StatusBadGateway) http.Error(w, "upstream request failed", http.StatusBadGateway)
return return
} }
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != http.StatusOK {
w.WriteHeader(resp.StatusCode)
_, _ = io.Copy(w, resp.Body)
return
}
body, err := io.ReadAll(resp.Body)
if err != nil {
http.Error(w, "failed to read response", http.StatusInternalServerError)
return
}
rewritten, err := h.rewriteServiceIndex(body) rewritten, err := h.rewriteServiceIndex(body)
if err != nil { if err != nil {
@ -139,10 +152,10 @@ func (h *NuGetHandler) shouldRewriteService(serviceType string) bool {
func (h *NuGetHandler) rewriteNuGetURL(origURL string) string { func (h *NuGetHandler) rewriteNuGetURL(origURL string) string {
// Map known NuGet API endpoints to our proxy paths // Map known NuGet API endpoints to our proxy paths
replacements := map[string]string{ replacements := map[string]string{
"https://api.nuget.org/v3-flatcontainer/": h.proxyURL + "/nuget/v3-flatcontainer/", "https://api.nuget.org/v3-flatcontainer/": h.proxyURL + "/nuget/v3-flatcontainer/",
"https://api.nuget.org/v3/registration5-gz-semver2/": h.proxyURL + "/nuget/v3/registration5-gz-semver2/", "https://api.nuget.org/v3/registration5-gz-semver2/": h.proxyURL + "/nuget/v3/registration5-gz-semver2/",
"https://azuresearch-usnc.nuget.org/query": h.proxyURL + "/nuget/query", "https://azuresearch-usnc.nuget.org/query": h.proxyURL + "/nuget/query",
"https://azuresearch-usnc.nuget.org/autocomplete": h.proxyURL + "/nuget/autocomplete", "https://azuresearch-usnc.nuget.org/autocomplete": h.proxyURL + "/nuget/autocomplete",
} }
for old, new := range replacements { for old, new := range replacements {
@ -154,140 +167,6 @@ func (h *NuGetHandler) rewriteNuGetURL(origURL string) string {
return origURL return origURL
} }
// handleRegistration proxies NuGet registration pages, applying cooldown filtering.
func (h *NuGetHandler) handleRegistration(w http.ResponseWriter, r *http.Request) {
if h.proxy.Cooldown == nil || !h.proxy.Cooldown.Enabled() {
h.proxyUpstream(w, r)
return
}
upstreamURL := h.buildUpstreamURL(r)
h.proxy.Logger.Debug("fetching registration for cooldown filtering", "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
}
req.Header.Set(headerAcceptEncoding, "gzip")
resp, err := h.proxy.HTTPClient.Do(req)
if err != nil {
h.proxy.Logger.Error("upstream request failed", "error", err)
http.Error(w, "upstream request failed", http.StatusBadGateway)
return
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != http.StatusOK {
for k, vv := range resp.Header {
for _, v := range vv {
w.Header().Add(k, v)
}
}
w.WriteHeader(resp.StatusCode)
_, _ = io.Copy(w, resp.Body)
return
}
body, err := h.proxy.ReadMetadata(resp.Body)
if err != nil {
http.Error(w, "failed to read response", http.StatusInternalServerError)
return
}
filtered, err := h.applyCooldownFiltering(body)
if err != nil {
h.proxy.Logger.Warn("failed to filter registration, proxying original", "error", err)
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write(body)
return
}
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write(filtered)
}
// applyCooldownFiltering filters versions from NuGet registration pages
// that are too recently published.
func (h *NuGetHandler) applyCooldownFiltering(body []byte) ([]byte, error) {
if h.proxy.Cooldown == nil || !h.proxy.Cooldown.Enabled() {
return body, nil
}
var registration map[string]any
if err := json.Unmarshal(body, &registration); err != nil {
return nil, err
}
pages, ok := registration["items"].([]any)
if !ok {
return body, nil
}
for _, page := range pages {
pageMap, ok := page.(map[string]any)
if !ok {
continue
}
items, ok := pageMap["items"].([]any)
if !ok {
continue
}
filtered := items[:0]
for _, item := range items {
itemMap, ok := item.(map[string]any)
if !ok {
continue
}
catalogEntry, ok := itemMap["catalogEntry"].(map[string]any)
if !ok {
filtered = append(filtered, item)
continue
}
version, _ := catalogEntry["version"].(string)
id, _ := catalogEntry["id"].(string)
publishedStr, _ := catalogEntry["published"].(string)
if publishedStr == "" {
filtered = append(filtered, item)
continue
}
publishedAt, err := time.Parse(time.RFC3339, publishedStr)
if err != nil {
// NuGet uses a slightly non-standard format, try parsing with fractional seconds
publishedAt, err = time.Parse("2006-01-02T15:04:05.999-07:00", publishedStr)
if err != nil {
filtered = append(filtered, item)
continue
}
}
packagePURL := canonicalPackagePURL("nuget", strings.ToLower(id))
if !h.proxy.Cooldown.IsAllowed("nuget", packagePURL, publishedAt) {
h.proxy.Logger.Info("cooldown: filtering nuget version",
"package", id, "version", version,
"published", publishedStr)
continue
}
filtered = append(filtered, item)
}
pageMap["items"] = filtered
pageMap["count"] = len(filtered)
}
return json.Marshal(registration)
}
// handleDownload serves a package file, fetching and caching from upstream if needed. // handleDownload serves a package file, fetching and caching from upstream if needed.
func (h *NuGetHandler) handleDownload(w http.ResponseWriter, r *http.Request) { func (h *NuGetHandler) handleDownload(w http.ResponseWriter, r *http.Request) {
id := r.PathValue("id") id := r.PathValue("id")
@ -314,7 +193,8 @@ func (h *NuGetHandler) handleDownload(w http.ResponseWriter, r *http.Request) {
result, err := h.proxy.GetOrFetchArtifactFromURL(r.Context(), "nuget", name, version, filename, upstreamURL) result, err := h.proxy.GetOrFetchArtifactFromURL(r.Context(), "nuget", name, version, filename, upstreamURL)
if err != nil { if err != nil {
h.proxy.serveArtifactError(w, err, "failed to fetch package") h.proxy.Logger.Error("failed to get artifact", "error", err)
http.Error(w, "failed to fetch package", http.StatusBadGateway)
return return
} }
@ -335,11 +215,11 @@ func (h *NuGetHandler) proxyUpstream(w http.ResponseWriter, r *http.Request) {
} }
// Copy accept-encoding for compression // Copy accept-encoding for compression
if ae := r.Header.Get(headerAcceptEncoding); ae != "" { if ae := r.Header.Get("Accept-Encoding"); ae != "" {
req.Header.Set(headerAcceptEncoding, ae) req.Header.Set("Accept-Encoding", ae)
} }
resp, err := h.proxy.HTTPClient.Do(req) resp, err := http.DefaultClient.Do(req)
if err != nil { if err != nil {
h.proxy.Logger.Error("upstream request failed", "error", err) h.proxy.Logger.Error("upstream request failed", "error", err)
http.Error(w, "upstream request failed", http.StatusBadGateway) http.Error(w, "upstream request failed", http.StatusBadGateway)

File diff suppressed because it is too large Load diff

View file

@ -1,36 +0,0 @@
package handler
import "testing"
func TestContainsPathTraversal(t *testing.T) {
tests := []struct {
path string
want bool
}{
{"pool/main/n/nginx/nginx_1.0.deb", false},
{"releases/39/Packages/test.rpm", false},
{"../etc/passwd", true},
{"pool/../../etc/passwd", true},
{"pool/main/../../../etc/shadow", true},
{"pool/..hidden/file", false}, // ".." as a segment, not "..hidden"
{"", false},
{"%2e%2e/etc/passwd", true},
{"%2e%2e%2fetc%2fpasswd", true},
{"pool/%2e%2e/%2e%2e/etc/shadow", true},
{"%2E%2E%2Fetc", true},
{`..\\etc\\passwd`, true},
{`pool\\..\\..\\etc`, true},
{"%2e%2e%5cetc%5cpasswd", true},
{"pool/%2e%2ehidden/file", false},
{"pool/%zz/bad-encoding", false},
}
for _, tt := range tests {
t.Run(tt.path, func(t *testing.T) {
got := containsPathTraversal(tt.path)
if got != tt.want {
t.Errorf("containsPathTraversal(%q) = %v, want %v", tt.path, got, tt.want)
}
})
}
}

View file

@ -2,16 +2,14 @@ package handler
import ( import (
"encoding/json" "encoding/json"
"errors"
"fmt" "fmt"
"io"
"net/http" "net/http"
"strings" "strings"
"time"
) )
const ( const (
pubUpstream = "https://pub.dev" pubUpstream = "https://pub.dev"
pubPathParts = 2 // name + version in path split by /versions/
) )
// PubHandler handles pub.dev registry protocol requests. // PubHandler handles pub.dev registry protocol requests.
@ -48,7 +46,7 @@ func (h *PubHandler) handleDownload(w http.ResponseWriter, r *http.Request) {
// Parse path: /packages/{name}/versions/{version}.tar.gz // Parse path: /packages/{name}/versions/{version}.tar.gz
path := strings.TrimPrefix(r.URL.Path, "/packages/") path := strings.TrimPrefix(r.URL.Path, "/packages/")
parts := strings.Split(path, "/versions/") parts := strings.Split(path, "/versions/")
if len(parts) != pubPathParts { if len(parts) != 2 {
http.Error(w, "invalid request", http.StatusBadRequest) http.Error(w, "invalid request", http.StatusBadRequest)
return return
} }
@ -67,7 +65,8 @@ func (h *PubHandler) handleDownload(w http.ResponseWriter, r *http.Request) {
result, err := h.proxy.GetOrFetchArtifact(r.Context(), "pub", name, version, filename) result, err := h.proxy.GetOrFetchArtifact(r.Context(), "pub", name, version, filename)
if err != nil { if err != nil {
h.proxy.serveArtifactError(w, err, "failed to fetch package") h.proxy.Logger.Error("failed to get artifact", "error", err)
http.Error(w, "failed to fetch package", http.StatusBadGateway)
return return
} }
@ -86,16 +85,32 @@ func (h *PubHandler) handlePackageMetadata(w http.ResponseWriter, r *http.Reques
upstreamURL := fmt.Sprintf("%s/api/packages/%s", h.upstreamURL, name) upstreamURL := fmt.Sprintf("%s/api/packages/%s", h.upstreamURL, name)
body, _, err := h.proxy.FetchOrCacheMetadata(r.Context(), "pub", name, upstreamURL) req, err := http.NewRequestWithContext(r.Context(), http.MethodGet, upstreamURL, nil)
if err != nil {
http.Error(w, "failed to create request", http.StatusInternalServerError)
return
}
req.Header.Set("Accept", "application/json")
resp, err := http.DefaultClient.Do(req)
if err != nil { if err != nil {
if errors.Is(err, ErrUpstreamNotFound) {
http.Error(w, "not found", http.StatusNotFound)
return
}
h.proxy.Logger.Error("upstream request failed", "error", err) h.proxy.Logger.Error("upstream request failed", "error", err)
http.Error(w, "upstream request failed", http.StatusBadGateway) http.Error(w, "upstream request failed", http.StatusBadGateway)
return return
} }
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != http.StatusOK {
w.WriteHeader(resp.StatusCode)
_, _ = io.Copy(w, resp.Body)
return
}
body, err := io.ReadAll(resp.Body)
if err != nil {
http.Error(w, "failed to read response", http.StatusInternalServerError)
return
}
rewritten, err := h.rewriteMetadata(name, body) rewritten, err := h.rewriteMetadata(name, body)
if err != nil { if err != nil {
@ -112,31 +127,18 @@ func (h *PubHandler) handlePackageMetadata(w http.ResponseWriter, r *http.Reques
} }
// rewriteMetadata rewrites archive_url fields to point at this proxy. // rewriteMetadata rewrites archive_url fields to point at this proxy.
// If cooldown is enabled, versions published too recently are filtered out.
func (h *PubHandler) rewriteMetadata(name string, body []byte) ([]byte, error) { func (h *PubHandler) rewriteMetadata(name string, body []byte) ([]byte, error) {
var metadata map[string]any var metadata map[string]any
if err := json.Unmarshal(body, &metadata); err != nil { if err := json.Unmarshal(body, &metadata); err != nil {
return nil, err return nil, err
} }
// Rewrite archive URLs in versions
versions, ok := metadata["versions"].([]any) versions, ok := metadata["versions"].([]any)
if !ok { if !ok {
return body, nil return body, nil
} }
packagePURL := canonicalPackagePURL("pub", name)
filtered := h.filterAndRewriteVersions(name, packagePURL, versions)
metadata["versions"] = filtered
h.updateLatestVersion(metadata, filtered)
return json.Marshal(metadata)
}
// filterAndRewriteVersions applies cooldown filtering and rewrites archive URLs
// for a package's version list.
func (h *PubHandler) filterAndRewriteVersions(name, packagePURL string, versions []any) []any {
filtered := versions[:0]
for _, vdata := range versions { for _, vdata := range versions {
vmap, ok := vdata.(map[string]any) vmap, ok := vdata.(map[string]any)
if !ok { if !ok {
@ -148,72 +150,13 @@ func (h *PubHandler) filterAndRewriteVersions(name, packagePURL string, versions
continue continue
} }
if h.shouldFilterVersion(packagePURL, name, version, vmap) { // Rewrite archive_url
continue
}
newURL := fmt.Sprintf("%s/pub/packages/%s/versions/%s.tar.gz", h.proxyURL, name, version) newURL := fmt.Sprintf("%s/pub/packages/%s/versions/%s.tar.gz", h.proxyURL, name, version)
vmap["archive_url"] = newURL vmap["archive_url"] = newURL
filtered = append(filtered, vdata)
h.proxy.Logger.Debug("rewrote archive URL", h.proxy.Logger.Debug("rewrote archive URL",
"package", name, "version", version, "new", newURL) "package", name, "version", version, "new", newURL)
} }
return filtered return json.Marshal(metadata)
}
// shouldFilterVersion returns true if the version should be excluded due to cooldown.
func (h *PubHandler) shouldFilterVersion(packagePURL, name, version string, vmap map[string]any) bool {
if h.proxy.Cooldown == nil || !h.proxy.Cooldown.Enabled() {
return false
}
publishedStr, ok := vmap["published"].(string)
if !ok {
return false
}
publishedAt, err := time.Parse(time.RFC3339, publishedStr)
if err != nil {
return false
}
if !h.proxy.Cooldown.IsAllowed("pub", packagePURL, publishedAt) {
h.proxy.Logger.Info("cooldown: filtering pub version",
"package", name, "version", version)
return true
}
return false
}
// updateLatestVersion updates the latest field if the current latest version
// was removed by cooldown filtering.
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, ok := latest["version"].(string)
if !ok {
return
}
for _, vdata := range filtered {
if vmap, ok := vdata.(map[string]any); ok {
if vmap["version"] == latestVer {
return
}
}
}
if len(filtered) > 0 {
metadata["latest"] = filtered[len(filtered)-1]
}
} }

View file

@ -1,94 +0,0 @@
package handler
import (
"encoding/json"
"log/slog"
"testing"
"time"
"github.com/git-pkgs/cooldown"
)
func TestPubRewriteMetadata(t *testing.T) {
h := &PubHandler{
proxy: testProxy(),
proxyURL: "http://localhost:8080",
}
input := `{
"name": "flutter_bloc",
"versions": [
{"version": "1.0.0", "archive_url": "https://pub.dev/packages/flutter_bloc/versions/1.0.0.tar.gz"},
{"version": "2.0.0", "archive_url": "https://pub.dev/packages/flutter_bloc/versions/2.0.0.tar.gz"}
]
}`
output, err := h.rewriteMetadata("flutter_bloc", []byte(input))
if err != nil {
t.Fatalf("rewriteMetadata failed: %v", err)
}
var result map[string]any
if err := json.Unmarshal(output, &result); err != nil {
t.Fatalf("failed to parse output: %v", err)
}
versions := result["versions"].([]any)
if len(versions) != 2 {
t.Fatalf("expected 2 versions, got %d", len(versions))
}
v1 := versions[0].(map[string]any)
if v1["archive_url"] != "http://localhost:8080/pub/packages/flutter_bloc/versions/1.0.0.tar.gz" {
t.Errorf("unexpected archive_url: %s", v1["archive_url"])
}
}
func TestPubRewriteMetadataCooldown(t *testing.T) {
now := time.Now()
old := now.Add(-10 * 24 * time.Hour).Format(time.RFC3339)
recent := now.Add(-1 * time.Hour).Format(time.RFC3339)
proxy := &Proxy{Logger: slog.Default()}
proxy.Cooldown = &cooldown.Config{Default: "3d"}
h := &PubHandler{
proxy: proxy,
proxyURL: "http://localhost:8080",
}
input := `{
"name": "flutter_bloc",
"latest": {"version": "2.0.0"},
"versions": [
{"version": "1.0.0", "published": "` + old + `", "archive_url": "https://pub.dev/1.0.0.tar.gz"},
{"version": "2.0.0", "published": "` + recent + `", "archive_url": "https://pub.dev/2.0.0.tar.gz"}
]
}`
output, err := h.rewriteMetadata("flutter_bloc", []byte(input))
if err != nil {
t.Fatalf("rewriteMetadata failed: %v", err)
}
var result map[string]any
if err := json.Unmarshal(output, &result); err != nil {
t.Fatalf("failed to parse output: %v", err)
}
versions := result["versions"].([]any)
if len(versions) != 1 {
t.Fatalf("expected 1 version after cooldown, got %d", len(versions))
}
v := versions[0].(map[string]any)
if v["version"] != "1.0.0" {
t.Errorf("expected version 1.0.0, got %v", v["version"])
}
// latest should be updated
latest := result["latest"].(map[string]any)
if latest["version"] != "1.0.0" {
t.Errorf("latest version = %v, want 1.0.0", latest["version"])
}
}

View file

@ -4,29 +4,16 @@ import (
"crypto/sha256" "crypto/sha256"
"encoding/hex" "encoding/hex"
"encoding/json" "encoding/json"
"errors"
"fmt" "fmt"
"io" "io"
"net/http" "net/http"
"net/url" "net/url"
"regexp" "regexp"
"strings" "strings"
"time"
) )
const ( const (
pypiUpstream = "https://pypi.org" pypiUpstream = "https://pypi.org"
minWheelParts = 5 // name + version + python + abi + platform
minSubmatchParts = 2 // full match + first capture group
minPyPIPathParts = 3 // hash_prefix + hash + filename
minEggParts = 3 // name + version + python tag
// PyPIMetadataSuffix is the PEP 658 core-metadata sidecar suffix that pip
// appends to a distribution URL when the index advertises core metadata.
// A sidecar resolves to the same name and version as the distribution it
// describes, so it is cached alongside it; consumers that expect an openable
// archive must skip these.
PyPIMetadataSuffix = ".metadata"
) )
// PyPIHandler handles PyPI registry protocol requests. // PyPIHandler handles PyPI registry protocol requests.
@ -80,112 +67,63 @@ func (h *PyPIHandler) handleSimplePackage(w http.ResponseWriter, r *http.Request
h.proxy.Logger.Info("pypi simple request", "package", name) h.proxy.Logger.Info("pypi simple request", "package", name)
upstreamURL := fmt.Sprintf("%s/simple/%s/", h.upstreamURL, name) upstreamURL := fmt.Sprintf("%s/simple/%s/", h.upstreamURL, name)
cacheKey := name + "/simple"
body, _, err := h.proxy.FetchOrCacheMetadata(r.Context(), "pypi", cacheKey, upstreamURL, "text/html") req, err := http.NewRequestWithContext(r.Context(), http.MethodGet, upstreamURL, nil)
if err != nil {
http.Error(w, "failed to create request", http.StatusInternalServerError)
return
}
req.Header.Set("Accept", "text/html")
resp, err := http.DefaultClient.Do(req)
if err != nil { if err != nil {
if errors.Is(err, ErrUpstreamNotFound) {
http.Error(w, "not found", http.StatusNotFound)
return
}
h.proxy.Logger.Error("upstream request failed", "error", err) h.proxy.Logger.Error("upstream request failed", "error", err)
http.Error(w, "upstream request failed", http.StatusBadGateway) http.Error(w, "upstream request failed", http.StatusBadGateway)
return return
} }
defer func() { _ = resp.Body.Close() }()
// When cooldown is enabled, fetch JSON metadata to get version timestamps if resp.StatusCode != http.StatusOK {
var filteredVersions map[string]bool w.WriteHeader(resp.StatusCode)
if h.proxy.Cooldown != nil && h.proxy.Cooldown.Enabled() { _, _ = io.Copy(w, resp.Body)
filteredVersions = h.fetchFilteredVersions(r, name) return
} }
rewritten := h.rewriteSimpleHTML(body, filteredVersions) body, err := io.ReadAll(resp.Body)
if err != nil {
http.Error(w, "failed to read response", http.StatusInternalServerError)
return
}
rewritten := h.rewriteSimpleHTML(body)
w.Header().Set("Content-Type", "text/html") w.Header().Set("Content-Type", "text/html")
w.WriteHeader(http.StatusOK) w.WriteHeader(http.StatusOK)
_, _ = w.Write(rewritten) _, _ = w.Write(rewritten)
} }
// 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)
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
}
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) {
filtered[version] = true
}
}
if len(filtered) == 0 {
return nil
}
return filtered
}
// rewriteSimpleHTML rewrites package URLs in simple API HTML to point at this proxy. // 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) []byte {
func (h *PyPIHandler) rewriteSimpleHTML(body []byte, filteredVersions map[string]bool) []byte {
// If cooldown filtering is active, remove entire <a> tags for filtered versions
if len(filteredVersions) > 0 {
// Match full anchor tags: <a ...href="...">filename</a>
linkRe := regexp.MustCompile(`<a[^>]+href="[^"]*"[^>]*>[^<]+</a>`)
body = linkRe.ReplaceAllFunc(body, func(match []byte) []byte {
// Extract filename from between tags
innerRe := regexp.MustCompile(`>([^<]+)</a>`)
innerMatch := innerRe.FindSubmatch(match)
if len(innerMatch) < minSubmatchParts {
return match
}
filename := string(innerMatch[1])
_, version := h.parseFilename(strings.TrimSpace(filename))
if version != "" && filteredVersions[version] {
return nil
}
return match
})
}
// Match href attributes pointing to packages // Match href attributes pointing to packages
// PyPI URLs look like: https://files.pythonhosted.org/packages/... // PyPI URLs look like: https://files.pythonhosted.org/packages/...
re := regexp.MustCompile(`href="(https://files\.pythonhosted\.org/packages/[^"]+)"`) re := regexp.MustCompile(`href="(https://files\.pythonhosted\.org/packages/[^"]+)"`)
return re.ReplaceAllFunc(body, func(match []byte) []byte { return re.ReplaceAllFunc(body, func(match []byte) []byte {
// Extract the URL
submatch := re.FindSubmatch(match) submatch := re.FindSubmatch(match)
if len(submatch) < minSubmatchParts { if len(submatch) < 2 {
return match return match
} }
origURL := string(submatch[1]) origURL := string(submatch[1])
// Parse the URL to get the path
u, err := url.Parse(origURL) u, err := url.Parse(origURL)
if err != nil { if err != nil {
return match return match
} }
// Rewrite to our proxy
newURL := fmt.Sprintf("%s/pypi/packages%s", h.proxyURL, u.Path) newURL := fmt.Sprintf("%s/pypi/packages%s", h.proxyURL, u.Path)
return []byte(fmt.Sprintf(`href="%s"`, newURL)) return []byte(fmt.Sprintf(`href="%s"`, newURL))
}) })
@ -202,7 +140,7 @@ func (h *PyPIHandler) handleJSON(w http.ResponseWriter, r *http.Request) {
h.proxy.Logger.Info("pypi json request", "package", name) h.proxy.Logger.Info("pypi json request", "package", name)
upstreamURL := fmt.Sprintf("%s/pypi/%s/json", h.upstreamURL, name) upstreamURL := fmt.Sprintf("%s/pypi/%s/json", h.upstreamURL, name)
h.proxyAndRewriteJSON(w, r, upstreamURL, name+"/json") h.proxyAndRewriteJSON(w, r, upstreamURL)
} }
// handleVersionJSON serves the JSON API version metadata. // handleVersionJSON serves the JSON API version metadata.
@ -218,21 +156,37 @@ func (h *PyPIHandler) handleVersionJSON(w http.ResponseWriter, r *http.Request)
h.proxy.Logger.Info("pypi version json request", "package", name, "version", version) h.proxy.Logger.Info("pypi version json request", "package", name, "version", version)
upstreamURL := fmt.Sprintf("%s/pypi/%s/%s/json", h.upstreamURL, name, version) upstreamURL := fmt.Sprintf("%s/pypi/%s/%s/json", h.upstreamURL, name, version)
h.proxyAndRewriteJSON(w, r, upstreamURL, name+"/"+version) h.proxyAndRewriteJSON(w, r, upstreamURL)
} }
// proxyAndRewriteJSON fetches JSON metadata and rewrites download URLs. // proxyAndRewriteJSON fetches JSON metadata and rewrites download URLs.
func (h *PyPIHandler) proxyAndRewriteJSON(w http.ResponseWriter, r *http.Request, upstreamURL, cacheKey string) { func (h *PyPIHandler) proxyAndRewriteJSON(w http.ResponseWriter, r *http.Request, upstreamURL string) {
body, _, err := h.proxy.FetchOrCacheMetadata(r.Context(), "pypi", cacheKey, upstreamURL) req, err := http.NewRequestWithContext(r.Context(), http.MethodGet, upstreamURL, nil)
if err != nil {
http.Error(w, "failed to create request", http.StatusInternalServerError)
return
}
req.Header.Set("Accept", "application/json")
resp, err := http.DefaultClient.Do(req)
if err != nil { if err != nil {
if errors.Is(err, ErrUpstreamNotFound) {
http.Error(w, "not found", http.StatusNotFound)
return
}
h.proxy.Logger.Error("upstream request failed", "error", err) h.proxy.Logger.Error("upstream request failed", "error", err)
http.Error(w, "upstream request failed", http.StatusBadGateway) http.Error(w, "upstream request failed", http.StatusBadGateway)
return return
} }
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != http.StatusOK {
w.WriteHeader(resp.StatusCode)
_, _ = io.Copy(w, resp.Body)
return
}
body, err := io.ReadAll(resp.Body)
if err != nil {
http.Error(w, "failed to read response", http.StatusInternalServerError)
return
}
rewritten, err := h.rewriteJSONMetadata(body) rewritten, err := h.rewriteJSONMetadata(body)
if err != nil { if err != nil {
@ -247,101 +201,13 @@ func (h *PyPIHandler) proxyAndRewriteJSON(w http.ResponseWriter, r *http.Request
} }
// rewriteJSONMetadata rewrites download URLs in PyPI JSON metadata. // 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) { func (h *PyPIHandler) rewriteJSONMetadata(body []byte) ([]byte, error) {
var metadata map[string]any var metadata map[string]any
if err := json.Unmarshal(body, &metadata); err != nil { if err := json.Unmarshal(body, &metadata); err != nil {
return nil, err return nil, err
} }
packageName, _ := extractPyPIName(metadata) // Rewrite URLs in urls array
packagePURL := ""
if packageName != "" {
packagePURL = canonicalPackagePURL("pypi", packageName)
}
h.filterAndRewriteReleases(metadata, packageName, packagePURL)
h.filterAndRewriteURLs(metadata, packagePURL)
return json.Marshal(metadata)
}
// filterAndRewriteReleases applies cooldown filtering and URL rewriting to the
// releases map in PyPI metadata.
func (h *PyPIHandler) filterAndRewriteReleases(metadata map[string]any, packageName, packagePURL string) {
releases, ok := metadata["releases"].(map[string]any)
if !ok {
return
}
for version, files := range releases {
if h.shouldFilterRelease(packagePURL, files) {
h.proxy.Logger.Info("cooldown: filtering pypi version",
"package", packageName, "version", version)
delete(releases, version)
continue
}
h.rewriteFileEntries(files)
}
}
// shouldFilterRelease returns true if a release should be excluded due to cooldown.
func (h *PyPIHandler) shouldFilterRelease(packagePURL string, files any) bool {
if h.proxy.Cooldown == nil || !h.proxy.Cooldown.Enabled() || packagePURL == "" {
return false
}
filesArr, ok := files.([]any)
if !ok {
return false
}
publishedAt := h.newestUploadTime(filesArr)
return !publishedAt.IsZero() && !h.proxy.Cooldown.IsAllowed("pypi", packagePURL, publishedAt)
}
// versionInCooldown reports whether a version is still inside the cooldown
// window. Filtering the simple index is not enough on its own: file URLs are
// recorded in lockfiles and requirements pins, so pip can reach the download
// 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
}
return h.fetchFilteredVersions(r, name)[version]
}
// rewriteFileEntries rewrites URLs in a list of file entries.
func (h *PyPIHandler) rewriteFileEntries(files any) {
filesArr, ok := files.([]any)
if !ok {
return
}
for _, f := range filesArr {
if fmap, ok := f.(map[string]any); ok {
h.rewriteURLEntry(fmap)
}
}
}
// filterAndRewriteURLs applies cooldown filtering and URL rewriting to the
// urls array (current version files) in PyPI metadata.
func (h *PyPIHandler) filterAndRewriteURLs(metadata map[string]any, packagePURL string) {
urls, ok := metadata["urls"].([]any)
if !ok {
return
}
if h.shouldFilterRelease(packagePURL, urls) {
metadata["urls"] = []any{}
}
if urls, ok := metadata["urls"].([]any); ok { if urls, ok := metadata["urls"].([]any); ok {
for _, u := range urls { for _, u := range urls {
if umap, ok := u.(map[string]any); ok { if umap, ok := u.(map[string]any); ok {
@ -349,39 +215,21 @@ func (h *PyPIHandler) filterAndRewriteURLs(metadata map[string]any, packagePURL
} }
} }
} }
}
// extractPyPIName extracts the package name from PyPI JSON metadata. // Rewrite URLs in releases map
func extractPyPIName(metadata map[string]any) (string, bool) { if releases, ok := metadata["releases"].(map[string]any); ok {
info, ok := metadata["info"].(map[string]any) for _, files := range releases {
if !ok { if filesArr, ok := files.([]any); ok {
return "", false for _, f := range filesArr {
} if fmap, ok := f.(map[string]any); ok {
name, ok := info["name"].(string) h.rewriteURLEntry(fmap)
return name, ok }
} }
}
// newestUploadTime returns the most recent upload_time_iso_8601 from a list of file entries.
func (h *PyPIHandler) newestUploadTime(files []any) time.Time {
var newest time.Time
for _, f := range files {
fmap, ok := f.(map[string]any)
if !ok {
continue
}
ts, ok := fmap["upload_time_iso_8601"].(string)
if !ok {
continue
}
t, err := time.Parse(time.RFC3339, ts)
if err != nil {
continue
}
if t.After(newest) {
newest = t
} }
} }
return newest
return json.Marshal(metadata)
} }
// rewriteURLEntry rewrites a single URL entry in PyPI metadata. // rewriteURLEntry rewrites a single URL entry in PyPI metadata.
@ -414,7 +262,7 @@ func (h *PyPIHandler) handleDownload(w http.ResponseWriter, r *http.Request) {
// Path format: /packages/{hash_prefix}/{hash}/{filename} // Path format: /packages/{hash_prefix}/{hash}/{filename}
// e.g., /packages/ab/cd/abc123.../requests-2.31.0.tar.gz // e.g., /packages/ab/cd/abc123.../requests-2.31.0.tar.gz
parts := strings.Split(path, "/") parts := strings.Split(path, "/")
if len(parts) < minPyPIPathParts { if len(parts) < 3 {
http.Error(w, "invalid path", http.StatusBadRequest) http.Error(w, "invalid path", http.StatusBadRequest)
return return
} }
@ -422,13 +270,6 @@ func (h *PyPIHandler) handleDownload(w http.ResponseWriter, r *http.Request) {
filename := parts[len(parts)-1] filename := parts[len(parts)-1]
name, version := h.parseFilename(filename) 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 == "" { if name == "" {
// Can't determine name/version, use hash as identifier // Can't determine name/version, use hash as identifier
name = fmt.Sprintf("_hash_%s", hashPath(path)) name = fmt.Sprintf("_hash_%s", hashPath(path))
@ -438,177 +279,69 @@ func (h *PyPIHandler) handleDownload(w http.ResponseWriter, r *http.Request) {
h.proxy.Logger.Info("pypi download request", h.proxy.Logger.Info("pypi download request",
"name", name, "version", version, "filename", filename) "name", name, "version", version, "filename", filename)
// Construct upstream URL; the incoming path starts with // Construct upstream URL
// '/packages' so there is no need to include it in the format upstreamURL := fmt.Sprintf("https://files.pythonhosted.org/packages/%s", path)
// string
upstreamURL := fmt.Sprintf("https://files.pythonhosted.org/%s", path)
result, err := h.proxy.GetOrFetchArtifactFromURL(r.Context(), "pypi", name, version, filename, upstreamURL) result, err := h.proxy.GetOrFetchArtifactFromURL(r.Context(), "pypi", name, version, filename, upstreamURL)
if err != nil { if err != nil {
h.proxy.serveArtifactError(w, err, "failed to fetch package") h.proxy.Logger.Error("failed to get artifact", "error", err)
http.Error(w, "failed to fetch package", http.StatusBadGateway)
return return
} }
ServeArtifact(w, result) ServeArtifact(w, result)
} }
// archiveExtensions are sdist formats of the form {name}-{version}{ext}. They
// carry no trailing tags, but legacy sdist names may contain hyphens.
var archiveExtensions = []string{".tar.gz", ".tar.bz2", ".tar.xz", ".tar.Z", ".tgz", ".tar", ".zip"}
// windowsInstallerExtensions are the legacy distutils bdist_wininst and
// bdist_msi formats, which share a filename layout.
var windowsInstallerExtensions = []string{".exe", ".msi"}
// parseFilename extracts package name and version from a PyPI filename. // parseFilename extracts package name and version from a PyPI filename.
// Handles wheels, sdists and legacy bdist formats: // Handles both wheels and sdists:
// - requests-2.31.0-py3-none-any.whl // - requests-2.31.0-py3-none-any.whl
// - requests-2.31.0.tar.gz // - 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 (h *PyPIHandler) parseFilename(filename string) (name, version string) {
// PEP 658/714 core-metadata sidecars are the distribution filename plus // Try wheel format first: {name}-{version}(-{build})?-{python}-{abi}-{platform}.whl
// ".metadata"; they describe the same name and version. Without this, pip's if strings.HasSuffix(filename, ".whl") {
// metadata-only fetches fall back to a hash-derived package identifier. base := strings.TrimSuffix(filename, ".whl")
filename = strings.TrimSuffix(filename, PyPIMetadataSuffix) parts := strings.Split(base, "-")
if len(parts) >= 5 {
switch { // Find where version ends (version followed by python tag)
case strings.HasSuffix(filename, ".whl"): for i := 1; i < len(parts)-2; i++ {
return parseWheelFilename(strings.TrimSuffix(filename, ".whl")) // Check if this looks like a python tag (py2, py3, cp39, etc)
case strings.HasSuffix(filename, ".egg"): if isPythonTag(parts[i]) {
return parseEggFilename(strings.TrimSuffix(filename, ".egg")) name = strings.Join(parts[:i-1], "-")
} version = parts[i-1]
return
for _, ext := range windowsInstallerExtensions { }
if strings.HasSuffix(filename, ext) { }
return parseWindowsInstallerFilename(strings.TrimSuffix(filename, ext))
} }
} }
for _, ext := range archiveExtensions { // Try sdist formats: {name}-{version}.tar.gz, {name}-{version}.zip
for _, ext := range []string{".tar.gz", ".tar.bz2", ".zip", ".tar"} {
if strings.HasSuffix(filename, ext) { if strings.HasSuffix(filename, ext) {
return splitNameVersion(strings.TrimSuffix(filename, ext)) base := strings.TrimSuffix(filename, ext)
// Find last hyphen followed by version
for i := len(base) - 1; i >= 0; i-- {
if base[i] == '-' && i+1 < len(base) && isVersionStart(base[i+1]) {
return base[:i], base[i+1:]
}
}
} }
} }
return "", "" return "", ""
} }
// parseWheelFilename parses the PEP 427 layout func isPythonTag(s string) bool {
// {name}-{version}(-{build})?-{python}-{abi}-{platform}, base being the if len(s) < 2 {
// filename without its ".whl" suffix. The spec escapes every hyphen in the name
// and version to '_', so the first two fields are authoritative even when the
// optional build tag is present.
func parseWheelFilename(base string) (name, version string) {
parts := strings.Split(base, "-")
if len(parts) < minWheelParts {
return "", ""
}
return parts[0], parts[1]
}
// parseEggFilename parses the setuptools bdist_egg layout
// {name}-{version}-py{X.Y}(-{platform})?, base being the filename without its
// ".egg" suffix. setuptools escapes hyphens in the name and version to '_', but
// eggs built by other tooling do not always, so the version is located relative
// to the interpreter field rather than assumed to be the second field.
func parseEggFilename(base string) (name, version string) {
parts := strings.Split(base, "-")
// Scan from the end: the trailing platform fields never look like an
// interpreter tag, so the last match is the real one even when the package
// name itself carries a "py{N}" component. Stop before index 1, since a tag
// any earlier would leave no room for both a name and a version.
for i := len(parts) - 1; i >= minEggParts-1; i-- {
if !isEggPythonTag(parts[i]) || !isVersionField(parts[i-1]) {
continue
}
return strings.Join(parts[:i-1], "-"), parts[i-1]
}
// No interpreter field: {name}-{version}.
return splitNameVersion(base)
}
// parseWindowsInstallerFilename parses the distutils bdist_wininst and
// bdist_msi layout {name}-{version}.{platform}(-py{X.Y})?, base being the
// filename without its ".exe" or ".msi" suffix. The platform is joined to the
// version with a '.' rather than a '-' and may itself contain a hyphen
// ("win-amd64"), so both trailing fields are stripped before the name and
// version are split apart.
func parseWindowsInstallerFilename(base string) (name, version string) {
if i := strings.LastIndex(base, "-py"); i >= 0 && isDottedNumber(base[i+len("-py"):]) {
base = base[:i]
}
// The platform is the final '.'-separated field. Requiring it to start with
// a non-digit keeps a dotted version from being truncated when a filename
// carries no platform tag.
i := strings.LastIndex(base, ".")
if i < 0 || i+1 >= len(base) || isVersionStart(base[i+1]) {
return "", ""
}
return splitFullname(base[:i])
}
// splitFullname splits the distutils fullname {name}-{version} that precedes a
// Windows installer's platform field. Unlike an sdist, a wininst fullname may
// carry a trailing build variant ("cx_Oracle-5.1.2-11g"), which belongs to
// neither the name nor the version, so the first purely numeric field wins and
// anything after it is discarded.
func splitFullname(fullname string) (name, version string) {
parts := strings.Split(fullname, "-")
for i := 1; i < len(parts); i++ {
if isDottedNumber(parts[i]) {
return strings.Join(parts[:i], "-"), parts[i]
}
}
// No purely numeric field, e.g. a prerelease version like "1.0b1".
return splitNameVersion(fullname)
}
// splitNameVersion splits a {name}-{version} pair at the last hyphen that
// starts a version, leaving hyphens inside the name intact.
func splitNameVersion(base string) (name, version string) {
for i := len(base) - 1; i >= 0; i-- {
if base[i] == '-' && i+1 < len(base) && isVersionStart(base[i+1]) {
return base[:i], base[i+1:]
}
}
return "", ""
}
// isEggPythonTag reports whether field is the py{X.Y} interpreter field that
// setuptools places directly after the version in an egg filename.
func isEggPythonTag(field string) bool {
const prefix = "py"
return len(field) > len(prefix) && strings.HasPrefix(field, prefix) && isVersionStart(field[len(prefix)])
}
// isVersionField reports whether field can be a version, i.e. it is non-empty
// and starts with a digit as every PEP 440 release segment does.
func isVersionField(field string) bool {
return field != "" && isVersionStart(field[0])
}
// isDottedNumber reports whether s is a dotted numeric version such as "2.7".
func isDottedNumber(s string) bool {
if s == "" || !isVersionStart(s[0]) {
return false return false
} }
// Python tags start with py, cp, pp, ip, jy
for i := range len(s) { prefixes := []string{"py", "cp", "pp", "ip", "jy"}
if !isVersionStart(s[i]) && s[i] != '.' { for _, p := range prefixes {
return false if strings.HasPrefix(s, p) {
return true
} }
} }
return false
return true
} }
func isVersionStart(c byte) bool { func isVersionStart(c byte) bool {
@ -631,7 +364,7 @@ func (h *PyPIHandler) proxySimple(w http.ResponseWriter, r *http.Request, path s
} }
req.Header.Set("Accept", "text/html") req.Header.Set("Accept", "text/html")
resp, err := h.proxy.HTTPClient.Do(req) resp, err := http.DefaultClient.Do(req)
if err != nil { if err != nil {
h.proxy.Logger.Error("upstream request failed", "error", err) h.proxy.Logger.Error("upstream request failed", "error", err)
http.Error(w, "upstream request failed", http.StatusBadGateway) http.Error(w, "upstream request failed", http.StatusBadGateway)

View file

@ -1,18 +1,8 @@
package handler package handler
import ( import (
"encoding/json"
"io"
"log/slog" "log/slog"
"net/http"
"net/http/httptest"
"strings"
"sync/atomic"
"testing" "testing"
"time"
"github.com/git-pkgs/cooldown"
"github.com/git-pkgs/registries/fetch"
) )
func TestPyPIParseFilename(t *testing.T) { func TestPyPIParseFilename(t *testing.T) {
@ -29,58 +19,13 @@ func TestPyPIParseFilename(t *testing.T) {
{"aws-sdk-1.0.0.tar.gz", "aws-sdk", "1.0.0"}, {"aws-sdk-1.0.0.tar.gz", "aws-sdk", "1.0.0"},
{"zipp-3.17.0.zip", "zipp", "3.17.0"}, {"zipp-3.17.0.zip", "zipp", "3.17.0"},
// Additional sdist archive formats
{"lxml-4.9.3.tar.xz", "lxml", "4.9.3"},
{"docutils-0.20.1.tgz", "docutils", "0.20.1"},
{"psycopg2-2.9.9.tar.bz2", "psycopg2", "2.9.9"},
// Wheel formats // Wheel formats
{"requests-2.31.0-py3-none-any.whl", "requests", "2.31.0"}, {"requests-2.31.0-py3-none-any.whl", "requests", "2.31.0"},
{"numpy-1.26.2-cp311-cp311-manylinux_2_17_x86_64.whl", "numpy", "1.26.2"}, {"numpy-1.26.2-cp311-cp311-manylinux_2_17_x86_64.whl", "numpy", "1.26.2"},
{"cryptography-41.0.5-cp37-abi3-manylinux_2_28_x86_64.whl", "cryptography", "41.0.5"}, {"cryptography-41.0.5-cp37-abi3-manylinux_2_28_x86_64.whl", "cryptography", "41.0.5"},
// Wheels with a build tag must not fold the tag into the version
{"foo-1.0-1-py3-none-any.whl", "foo", "1.0"},
{"tensorflow-2.15.0-2-cp311-cp311-manylinux_2_17_x86_64.whl", "tensorflow", "2.15.0"},
// PEP 658 core-metadata sidecars resolve to the distribution they describe
{"backports_asyncio_runner-1.2.0-py3-none-any.whl.metadata", "backports_asyncio_runner", "1.2.0"},
{"requests-2.31.0-py3-none-any.whl.metadata", "requests", "2.31.0"},
{"requests-2.31.0.tar.gz.metadata", "requests", "2.31.0"},
// Eggs: {name}-{version}-py{X.Y}(-{platform})?.egg. Unescaped hyphens in
// the name must not be mistaken for the field separator before the version.
{"numpy-1.8.0-py2.7-macosx-10.9-x86_64.egg", "numpy", "1.8.0"},
{"aws-sdk-1.0.0-py3.11.egg", "aws-sdk", "1.0.0"},
{"aws-sdk-1.0.0-py2.7-macosx-10.9-x86_64.egg", "aws-sdk", "1.0.0"},
{"aws-sdk-1.0.0.egg", "aws-sdk", "1.0.0"},
// A "py{N}" component inside the name is not the interpreter field, so
// the interpreter must be located from the end of the filename.
{"django-rest-py3-1.0-py3.6.egg", "django-rest-py3", "1.0"},
// Windows installers: {name}-{version}.{platform}(-py{X.Y})?.{exe,msi}.
// The platform is not part of the version, and may contain a hyphen.
{"foo-1.0.win32-py2.0.exe", "foo", "1.0"},
{"pywin32-223.win32-py2.7.exe", "pywin32", "223"},
{"numpy-1.8.0.win-amd64-py2.7.exe", "numpy", "1.8.0"},
{"aws-sdk-1.0.0.win32-py2.7.exe", "aws-sdk", "1.0.0"},
{"pywin32-223.win32.exe", "pywin32", "223"},
{"cx_Oracle-5.1.2.win32-py2.7.msi", "cx_Oracle", "5.1.2"},
{"numpy-1.8.0.win-amd64.msi", "numpy", "1.8.0"},
// A trailing build variant belongs to neither the name nor the version.
{"cx_Oracle-5.1.2-11g.win32-py2.7.exe", "cx_Oracle", "5.1.2"},
// A prerelease version has no purely numeric field to anchor on.
{"foo-1.0b1.win32-py2.7.exe", "foo", "1.0b1"},
// Invalid // Invalid
{"invalid", "", ""}, {"invalid", "", ""},
{"invalid.metadata", "", ""},
{"backports.ssl_match_hostname-3.4.0.2-py2.7.whl", "", ""},
{"invalid.exe", "", ""},
{"foo-1.0.exe", "", ""},
// An egg with an interpreter field but no version must not promote the
// trailing component of a hyphenated name to the version.
{"aws-sdk-py2.7.egg", "", ""},
} }
for _, tt := range tests { for _, tt := range tests {
@ -92,261 +37,25 @@ func TestPyPIParseFilename(t *testing.T) {
} }
} }
func TestPyPIRewriteJSONMetadataCooldown(t *testing.T) { func TestIsPythonTag(t *testing.T) {
now := time.Now()
old := now.Add(-10 * 24 * time.Hour).Format(time.RFC3339)
recent := now.Add(-1 * time.Hour).Format(time.RFC3339)
proxy := &Proxy{Logger: slog.Default()}
proxy.Cooldown = &cooldown.Config{Default: "3d"}
h := &PyPIHandler{
proxy: proxy,
proxyURL: "http://localhost:8080",
}
input := `{
"info": {"name": "requests"},
"releases": {
"2.30.0": [{"url": "https://files.pythonhosted.org/packages/ab/cd/requests-2.30.0.tar.gz", "upload_time_iso_8601": "` + old + `"}],
"2.31.0": [{"url": "https://files.pythonhosted.org/packages/ab/cd/requests-2.31.0.tar.gz", "upload_time_iso_8601": "` + recent + `"}]
},
"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))
if err != nil {
t.Fatalf("rewriteJSONMetadata failed: %v", err)
}
var result map[string]any
if err := json.Unmarshal(output, &result); err != nil {
t.Fatalf("failed to parse output: %v", err)
}
releases := result["releases"].(map[string]any)
if _, ok := releases["2.30.0"]; !ok {
t.Error("version 2.30.0 should not be filtered")
}
if _, ok := releases["2.31.0"]; ok {
t.Error("version 2.31.0 should be filtered by cooldown")
}
// urls array should be empty since the current version is filtered
urls := result["urls"].([]any)
if len(urls) != 0 {
t.Errorf("urls should be empty, got %d entries", len(urls))
}
}
// TestPyPIParseFilenameNoHashFallback guards the identifier used for caching:
// a filename that parses to an empty name makes handleDownload fall back to a
// "_hash_<digest>" package name, which surfaces as a bogus PURL in the package
// overview.
func TestPyPIParseFilenameNoHashFallback(t *testing.T) {
h := &PyPIHandler{proxy: &Proxy{Logger: slog.Default()}}
filenames := []string{
"backports_asyncio_runner-1.2.0-py3-none-any.whl",
"backports_asyncio_runner-1.2.0-py3-none-any.whl.metadata",
"backports_asyncio_runner-1.2.0.tar.gz",
}
for _, filename := range filenames {
name, version := h.parseFilename(filename)
if name != "backports_asyncio_runner" || version != "1.2.0" {
t.Errorf("parseFilename(%q) = (%q, %q), want (%q, %q)",
filename, name, version, "backports_asyncio_runner", "1.2.0")
}
}
}
func TestPyPIHandler_DownloadUpstreamURL(t *testing.T) {
proxy, _, _, fetcher := setupTestProxy(t)
fetcher.artifact = &fetch.Artifact{
Body: io.NopCloser(strings.NewReader("wheel data")),
ContentType: "application/octet-stream",
}
h := NewPyPIHandler(proxy, "http://localhost")
srv := httptest.NewServer(h.Routes())
defer srv.Close()
// The path wildcard {path...} captures everything after /packages/,
// which includes "packages/" from the rewritten URL. The upstream URL
// must not double the "packages" segment.
resp, err := http.Get(srv.URL + "/packages/packages/ab/cd/ef0123456789/requests-2.31.0-py3-none-any.whl")
if err != nil {
t.Fatalf("request failed: %v", err)
}
defer func() { _ = resp.Body.Close() }()
if !fetcher.fetchCalled {
t.Fatal("expected fetcher to be called on cache miss")
}
want := "https://files.pythonhosted.org/packages/ab/cd/ef0123456789/requests-2.31.0-py3-none-any.whl"
if fetcher.fetchedURL != want {
t.Errorf("upstream URL = %q, want %q", fetcher.fetchedURL, want)
}
}
func TestPyPIHandler_DownloadCacheHit(t *testing.T) {
proxy, db, store, _ := setupTestProxy(t)
seedPackage(t, db, store, "pypi", "requests", "2.31.0",
"requests-2.31.0-py3-none-any.whl", "wheel binary data")
h := NewPyPIHandler(proxy, "http://localhost")
srv := httptest.NewServer(h.Routes())
defer srv.Close()
resp, err := http.Get(srv.URL + "/packages/packages/ab/cd/ef0123456789/requests-2.31.0-py3-none-any.whl")
if err != nil {
t.Fatalf("request failed: %v", err)
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != http.StatusOK {
t.Errorf("status = %d, want %d", resp.StatusCode, http.StatusOK)
}
body, _ := io.ReadAll(resp.Body)
if string(body) != "wheel binary data" {
t.Errorf("body = %q, want %q", body, "wheel binary data")
}
}
func TestPyPIHandler_DownloadCacheMiss(t *testing.T) {
proxy, _, _, fetcher := setupTestProxy(t)
fetcher.artifact = &fetch.Artifact{
Body: io.NopCloser(strings.NewReader("fetched wheel")),
ContentType: "application/octet-stream",
}
h := NewPyPIHandler(proxy, "http://localhost")
srv := httptest.NewServer(h.Routes())
defer srv.Close()
resp, err := http.Get(srv.URL + "/packages/packages/ab/cd/ef0123456789/newpkg-1.0.0.tar.gz")
if err != nil {
t.Fatalf("request failed: %v", err)
}
defer func() { _ = resp.Body.Close() }()
if !fetcher.fetchCalled {
t.Error("expected fetcher to be called on cache miss")
}
}
func TestPyPIDownloadCooldown(t *testing.T) {
now := time.Now()
releases := `{"releases": {
"1.0.0": [{"upload_time_iso_8601": "` + now.Add(-30*24*time.Hour).Format(time.RFC3339) + `"}],
"2.0.0": [{"upload_time_iso_8601": "` + now.Add(-1*time.Hour).Format(time.RFC3339) + `"}]
}}`
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", contentTypeJSON)
_, _ = io.WriteString(w, releases)
}))
defer upstream.Close()
tests := []struct { tests := []struct {
name string tag string
filename string want bool
wantStatus int
}{ }{
{"published before the window serves the file", "newpkg-1.0.0.tar.gz", http.StatusOK}, {"py3", true},
{"published inside the window is withheld", "newpkg-2.0.0.tar.gz", http.StatusNotFound}, {"py2", true},
{"cp311", true},
{"cp37", true},
{"pp39", true},
{"none", false},
{"any", false},
{"manylinux", false},
} }
for _, tt := range tests { for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) { got := isPythonTag(tt.tag)
proxy, _, _, fetcher := setupTestProxy(t) if got != tt.want {
proxy.HTTPClient = upstream.Client() t.Errorf("isPythonTag(%q) = %v, want %v", tt.tag, got, tt.want)
proxy.Cooldown = &cooldown.Config{Default: "7d"} }
fetcher.artifact = &fetch.Artifact{
Body: io.NopCloser(strings.NewReader("sdist data")),
ContentType: "application/octet-stream",
}
h := &PyPIHandler{
proxy: proxy,
upstreamURL: upstream.URL,
proxyURL: "http://localhost",
}
srv := httptest.NewServer(h.Routes())
defer srv.Close()
resp, err := http.Get(srv.URL + "/packages/packages/ab/cd/ef0123456789/" + tt.filename)
if err != nil {
t.Fatalf("request failed: %v", err)
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != tt.wantStatus {
t.Errorf("status = %d, want %d", resp.StatusCode, tt.wantStatus)
}
if tt.wantStatus == http.StatusNotFound && fetcher.fetchCalled {
t.Error("fetched a version that is still inside the cooldown window")
}
})
}
}
// TestPyPIDownloadCooldownMetadataCache ensures that repeated downloads that
// trigger cooldown filtering reuse the cached PyPI JSON metadata instead of
// fetching it from upstream once per download.
func TestPyPIDownloadCooldownMetadataCache(t *testing.T) {
now := time.Now()
releases := `{"releases": {
"1.0.0": [{"upload_time_iso_8601": "` + now.Add(-30*24*time.Hour).Format(time.RFC3339) + `"}],
"2.0.0": [{"upload_time_iso_8601": "` + now.Add(-1*time.Hour).Format(time.RFC3339) + `"}]
}}`
var metadataRequests atomic.Int64
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/pypi/newpkg/json" {
metadataRequests.Add(1)
w.Header().Set("Content-Type", "application/json")
_, _ = io.WriteString(w, releases)
return
}
w.Header().Set("Content-Type", "application/octet-stream")
_, _ = io.WriteString(w, "package data")
}))
defer upstream.Close()
proxy, _, _, fetcher := setupTestProxy(t)
proxy.HTTPClient = upstream.Client()
proxy.CacheMetadata = true
proxy.MetadataTTL = time.Hour
proxy.Cooldown = &cooldown.Config{Default: "7d"}
fetcher.artifact = &fetch.Artifact{
Body: io.NopCloser(strings.NewReader("package data")),
ContentType: "application/octet-stream",
}
h := &PyPIHandler{
proxy: proxy,
upstreamURL: upstream.URL,
proxyURL: "http://localhost",
}
srv := httptest.NewServer(h.Routes())
defer srv.Close()
// Two downloads of the same package: one outside the cooldown window
// (served) and one inside (withheld). Both go through the download path
// that resolves filtered versions.
for _, filename := range []string{"newpkg-1.0.0.tar.gz", "newpkg-2.0.0.tar.gz"} {
resp, err := http.Get(srv.URL + "/packages/packages/ab/cd/ef0123456789/" + filename)
if err != nil {
t.Fatalf("request failed: %v", err)
}
_ = resp.Body.Close()
}
if got := metadataRequests.Load(); got != 1 {
t.Errorf("upstream metadata JSON requests = %d, want 1 (repeated downloads should reuse the cached metadata)", got)
} }
} }

View file

@ -1,60 +0,0 @@
package handler
import (
"bytes"
"errors"
"testing"
)
func TestReadMetadata(t *testing.T) {
const limit = 1024
p := &Proxy{MetadataMaxSize: limit}
t.Run("small body", func(t *testing.T) {
data := []byte("hello world")
got, err := p.ReadMetadata(bytes.NewReader(data))
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if !bytes.Equal(got, data) {
t.Errorf("got %q, want %q", got, data)
}
})
t.Run("exactly at limit", func(t *testing.T) {
data := make([]byte, limit)
for i := range data {
data[i] = 'x'
}
got, err := p.ReadMetadata(bytes.NewReader(data))
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if len(got) != limit {
t.Errorf("got length %d, want %d", len(got), limit)
}
})
t.Run("over limit returns error", func(t *testing.T) {
data := make([]byte, limit+100)
for i := range data {
data[i] = 'x'
}
_, err := p.ReadMetadata(bytes.NewReader(data))
if !errors.Is(err, ErrMetadataTooLarge) {
t.Errorf("got error %v, want ErrMetadataTooLarge", err)
}
})
t.Run("zero limit uses default", func(t *testing.T) {
p := &Proxy{}
data := make([]byte, 1<<20)
got, err := p.ReadMetadata(bytes.NewReader(data))
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if len(got) != len(data) {
t.Errorf("got length %d, want %d", len(got), len(data))
}
})
}

View file

@ -2,6 +2,7 @@ package handler
import ( import (
"fmt" "fmt"
"io"
"net/http" "net/http"
"regexp" "regexp"
"strings" "strings"
@ -10,7 +11,6 @@ import (
const ( const (
// Default upstream for Fedora packages // Default upstream for Fedora packages
defaultRPMUpstream = "https://dl.fedoraproject.org/pub/fedora/linux" defaultRPMUpstream = "https://dl.fedoraproject.org/pub/fedora/linux"
rpmMatchCount = 5 // full match + name + version + release + arch
) )
// RPMHandler handles RPM/Yum repository protocol requests. // RPMHandler handles RPM/Yum repository protocol requests.
@ -41,11 +41,6 @@ func (h *RPMHandler) Routes() http.Handler {
path := strings.TrimPrefix(r.URL.Path, "/") path := strings.TrimPrefix(r.URL.Path, "/")
if containsPathTraversal(path) {
http.Error(w, "invalid path", http.StatusBadRequest)
return
}
// Route based on path type // Route based on path type
switch { switch {
case strings.HasSuffix(path, ".rpm"): case strings.HasSuffix(path, ".rpm"):
@ -83,7 +78,8 @@ func (h *RPMHandler) handlePackageDownload(w http.ResponseWriter, r *http.Reques
result, err := h.proxy.GetOrFetchArtifactFromURL( result, err := h.proxy.GetOrFetchArtifactFromURL(
r.Context(), "rpm", name, version, filename, downloadURL) r.Context(), "rpm", name, version, filename, downloadURL)
if err != nil { if err != nil {
h.proxy.serveArtifactError(w, err, "failed to fetch package") h.proxy.Logger.Error("failed to get rpm package", "error", err)
http.Error(w, "failed to fetch package", http.StatusBadGateway)
return return
} }
@ -94,13 +90,67 @@ func (h *RPMHandler) handlePackageDownload(w http.ResponseWriter, r *http.Reques
// handleMetadata proxies repository metadata files (repomd.xml, primary.xml.gz, etc.). // handleMetadata proxies repository metadata files (repomd.xml, primary.xml.gz, etc.).
// These change frequently so we don't cache them. // These change frequently so we don't cache them.
func (h *RPMHandler) handleMetadata(w http.ResponseWriter, r *http.Request, path string) { func (h *RPMHandler) handleMetadata(w http.ResponseWriter, r *http.Request, path string) {
cacheKey := strings.ReplaceAll(path, "/", "_") upstreamURL := fmt.Sprintf("%s/%s", h.upstreamURL, path)
h.proxy.ProxyCached(w, r, fmt.Sprintf("%s/%s", h.upstreamURL, path), "rpm", cacheKey, "*/*")
h.proxy.Logger.Debug("rpm metadata request", "path", path)
req, err := http.NewRequestWithContext(r.Context(), r.Method, upstreamURL, nil)
if err != nil {
http.Error(w, "failed to create request", http.StatusInternalServerError)
return
}
// Forward relevant headers
for _, header := range []string{"Accept", "Accept-Encoding", "If-Modified-Since", "If-None-Match"} {
if v := r.Header.Get(header); v != "" {
req.Header.Set(header, v)
}
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
h.proxy.Logger.Error("failed to fetch upstream metadata", "error", err)
http.Error(w, "failed to fetch from upstream", http.StatusBadGateway)
return
}
defer func() { _ = resp.Body.Close() }()
// Copy response headers
for _, header := range []string{"Content-Type", "Content-Length", "Last-Modified", "ETag"} {
if v := resp.Header.Get(header); v != "" {
w.Header().Set(header, v)
}
}
w.WriteHeader(resp.StatusCode)
_, _ = io.Copy(w, resp.Body)
} }
// proxyFile proxies any file directly without caching. // proxyFile proxies any file directly without caching.
func (h *RPMHandler) proxyFile(w http.ResponseWriter, r *http.Request, path string) { func (h *RPMHandler) proxyFile(w http.ResponseWriter, r *http.Request, path string) {
h.proxy.ProxyFile(w, r, fmt.Sprintf("%s/%s", h.upstreamURL, path)) upstreamURL := fmt.Sprintf("%s/%s", h.upstreamURL, path)
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 := http.DefaultClient.Do(req)
if err != nil {
http.Error(w, "failed to fetch from upstream", http.StatusBadGateway)
return
}
defer func() { _ = resp.Body.Close() }()
for key, values := range resp.Header {
for _, v := range values {
w.Header().Add(key, v)
}
}
w.WriteHeader(resp.StatusCode)
_, _ = io.Copy(w, resp.Body)
} }
// rpmPackagePattern matches .rpm filenames to extract name, version, release, and arch. // rpmPackagePattern matches .rpm filenames to extract name, version, release, and arch.
@ -121,7 +171,7 @@ func (h *RPMHandler) parseRPMPath(path string) (name, version, arch string) {
// Parse the filename // Parse the filename
matches := rpmPackagePattern.FindStringSubmatch(filename) matches := rpmPackagePattern.FindStringSubmatch(filename)
if len(matches) != rpmMatchCount { if len(matches) != 5 {
return "", "", "" return "", "", ""
} }

View file

@ -1,23 +1,89 @@
package handler package handler
import ( import (
"net/http"
"net/http/httptest"
"testing" "testing"
) )
func TestRPMHandler_parseRPMPath(t *testing.T) { func TestRPMHandler_parseRPMPath(t *testing.T) {
h := &RPMHandler{} h := &RPMHandler{}
assertPathParser(t, "parseRPMPath", h.parseRPMPath, []pathParseCase{ tests := []struct {
{"releases/39/Everything/x86_64/os/Packages/n/nginx-1.24.0-1.fc39.x86_64.rpm", "nginx", "1.24.0-1.fc39", "x86_64"}, path string
{"Packages/kernel-core-6.5.5-200.fc38.x86_64.rpm", "kernel-core", "6.5.5-200.fc38", "x86_64"}, wantName string
{"updates/39/Everything/aarch64/Packages/g/git-2.42.0-1.fc39.aarch64.rpm", "git", "2.42.0-1.fc39", "aarch64"}, wantVersion string
{"vim-enhanced-9.0.1000-1.fc38.noarch.rpm", "vim-enhanced", "9.0.1000-1.fc38", "noarch"}, wantArch string
{"invalid.rpm", "", "", ""}, }{
{"not-an-rpm-file", "", "", ""}, {
}) path: "releases/39/Everything/x86_64/os/Packages/n/nginx-1.24.0-1.fc39.x86_64.rpm",
wantName: "nginx",
wantVersion: "1.24.0-1.fc39",
wantArch: "x86_64",
},
{
path: "Packages/kernel-core-6.5.5-200.fc38.x86_64.rpm",
wantName: "kernel-core",
wantVersion: "6.5.5-200.fc38",
wantArch: "x86_64",
},
{
path: "updates/39/Everything/aarch64/Packages/g/git-2.42.0-1.fc39.aarch64.rpm",
wantName: "git",
wantVersion: "2.42.0-1.fc39",
wantArch: "aarch64",
},
{
path: "vim-enhanced-9.0.1000-1.fc38.noarch.rpm",
wantName: "vim-enhanced",
wantVersion: "9.0.1000-1.fc38",
wantArch: "noarch",
},
{
path: "invalid.rpm",
wantName: "",
wantVersion: "",
wantArch: "",
},
{
path: "not-an-rpm-file",
wantName: "",
wantVersion: "",
wantArch: "",
},
}
for _, tt := range tests {
t.Run(tt.path, func(t *testing.T) {
name, version, arch := h.parseRPMPath(tt.path)
if name != tt.wantName {
t.Errorf("parseRPMPath() name = %q, want %q", name, tt.wantName)
}
if version != tt.wantVersion {
t.Errorf("parseRPMPath() version = %q, want %q", version, tt.wantVersion)
}
if arch != tt.wantArch {
t.Errorf("parseRPMPath() arch = %q, want %q", arch, tt.wantArch)
}
})
}
} }
func TestRPMHandler_Routes(t *testing.T) { func TestRPMHandler_Routes(t *testing.T) {
h := NewRPMHandler(nil, "http://localhost:8080") h := NewRPMHandler(nil, "http://localhost:8080")
assertRoutesBasics(t, h.Routes(), "/repodata/repomd.xml", "/releases/../../../etc/passwd")
// Test that handler doesn't panic on initialization
handler := h.Routes()
if handler == nil {
t.Fatal("Routes() returned nil")
}
// Test method not allowed
req := httptest.NewRequest(http.MethodPost, "/repodata/repomd.xml", nil)
w := httptest.NewRecorder()
handler.ServeHTTP(w, req)
if w.Code != http.StatusMethodNotAllowed {
t.Errorf("POST request: got status %d, want %d", w.Code, http.StatusMethodNotAllowed)
}
} }

View file

@ -1,74 +0,0 @@
package httpclient
import (
"log/slog"
"net/http"
"net/url"
"strings"
"time"
"github.com/git-pkgs/proxy/internal/accesslog"
)
type accessLogTransport struct {
base http.RoundTripper
accessLog *accesslog.Logger
logger *slog.Logger
}
// NewAccessLogTransport records each upstream HTTP exchange around base.
func NewAccessLogTransport(base http.RoundTripper, log *accesslog.Logger, logger *slog.Logger) http.RoundTripper {
if base == nil {
base = http.DefaultTransport
}
if logger == nil {
logger = slog.Default()
}
if log == nil {
return base
}
return &accessLogTransport{
base: base,
accessLog: log,
logger: logger,
}
}
func (t *accessLogTransport) RoundTrip(req *http.Request) (*http.Response, error) {
start := time.Now()
resp, err := t.base.RoundTrip(req)
entry := accesslog.Entry{
Event: accesslog.EventUpstream,
RequestID: accesslog.RequestID(req.Context()),
Method: req.Method,
URL: accesslog.URLWithoutSecrets(req.URL),
DurationMS: time.Since(start).Milliseconds(),
}
if resp != nil {
entry.StatusCode = resp.StatusCode
}
if err != nil {
entry.Error = errorWithoutSecrets(err, req.URL)
}
if writeErr := t.accessLog.Write(entry); writeErr != nil {
t.logger.Error("failed to write access log", "error", writeErr)
}
return resp, err
}
func errorWithoutSecrets(err error, requestURL *url.URL) string {
message := err.Error()
if requestURL == nil {
return message
}
cleanURL := accesslog.URLWithoutSecrets(requestURL)
for _, value := range []string{requestURL.String(), requestURL.Redacted()} {
if value != "" {
message = strings.ReplaceAll(message, value, cleanURL)
}
}
return message
}

View file

@ -1,121 +0,0 @@
package httpclient
import (
"bufio"
"encoding/json"
"errors"
"io"
"log/slog"
"net/http"
"os"
"path/filepath"
"strings"
"testing"
"github.com/git-pkgs/proxy/internal/accesslog"
)
type roundTripFunc func(*http.Request) (*http.Response, error)
func (f roundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) {
return f(req)
}
func TestAccessLogTransportRecordsUpstreamStatus(t *testing.T) {
path := filepath.Join(t.TempDir(), "access.jsonl")
accessLogger, err := accesslog.Open(path)
if err != nil {
t.Fatal(err)
}
base := roundTripFunc(func(req *http.Request) (*http.Response, error) {
return &http.Response{
StatusCode: http.StatusTooManyRequests,
Body: io.NopCloser(strings.NewReader("rate limited")),
Request: req,
}, nil
})
client := &http.Client{Transport: NewAccessLogTransport(base, accessLogger, slog.Default())}
req, err := http.NewRequest(http.MethodGet, "https://user:password@registry.example/package.tgz?token=secret", nil)
if err != nil {
t.Fatal(err)
}
req = req.WithContext(accesslog.WithRequestID(req.Context(), "request-123"))
resp, err := client.Do(req)
if err != nil {
t.Fatal(err)
}
_ = resp.Body.Close()
if err := accessLogger.Close(); err != nil {
t.Fatal(err)
}
entry := readAccessLogEntry(t, path)
if entry.Event != accesslog.EventUpstream {
t.Errorf("event = %q, want %q", entry.Event, accesslog.EventUpstream)
}
if entry.RequestID != "request-123" {
t.Errorf("request_id = %q, want %q", entry.RequestID, "request-123")
}
if entry.StatusCode != http.StatusTooManyRequests {
t.Errorf("status_code = %d, want %d", entry.StatusCode, http.StatusTooManyRequests)
}
if entry.URL != "https://registry.example/package.tgz" {
t.Errorf("url = %q, want URL without credentials or query", entry.URL)
}
}
func TestAccessLogTransportRecordsUpstreamError(t *testing.T) {
path := filepath.Join(t.TempDir(), "access.jsonl")
accessLogger, err := accesslog.Open(path)
if err != nil {
t.Fatal(err)
}
wantErr := errors.New("GET https://user:password@registry.example/package.tgz?token=secret: connection refused")
base := roundTripFunc(func(*http.Request) (*http.Response, error) {
return nil, wantErr
})
client := &http.Client{Transport: NewAccessLogTransport(base, accessLogger, slog.Default())}
_, err = client.Get("https://user:password@registry.example/package.tgz?token=secret")
if !errors.Is(err, wantErr) {
t.Fatalf("GET error = %v, want %v", err, wantErr)
}
if err := accessLogger.Close(); err != nil {
t.Fatal(err)
}
entry := readAccessLogEntry(t, path)
if entry.StatusCode != 0 {
t.Errorf("status_code = %d, want 0", entry.StatusCode)
}
if strings.Contains(entry.Error, "password") || strings.Contains(entry.Error, "secret") {
t.Errorf("error contains URL credentials or query: %q", entry.Error)
}
if !strings.Contains(entry.Error, "connection refused") {
t.Errorf("error = %q, want connection failure", entry.Error)
}
}
func readAccessLogEntry(t *testing.T, path string) accesslog.Entry {
t.Helper()
file, err := os.Open(path)
if err != nil {
t.Fatal(err)
}
defer func() { _ = file.Close() }()
scanner := bufio.NewScanner(file)
if !scanner.Scan() {
t.Fatalf("access log is empty: %v", scanner.Err())
}
var entry accesslog.Entry
if err := json.Unmarshal(scanner.Bytes(), &entry); err != nil {
t.Fatalf("decoding access log: %v", err)
}
return entry
}

View file

@ -1,433 +0,0 @@
// Package httpclient provides authentication-aware HTTP transports for upstream requests.
package httpclient
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"sync"
"time"
)
const (
defaultTokenLifetime = 60 * time.Second
tokenExpirySkew = 5 * time.Second
maxTokenResponseSize = 1 << 20
shortTokenSkewDivisor = 10
)
// AuthFunc returns a configured authentication header for a URL.
type AuthFunc func(url string) (headerName, headerValue string)
// Transport adds configured authentication and follows OCI Bearer challenges.
type Transport struct {
base http.RoundTripper
authForURL AuthFunc
mu sync.Mutex
tokens map[string]cachedToken
challenges map[string]bearerChallenge
}
type cachedToken struct {
value string
expiresAt time.Time
}
type bearerChallenge struct {
realm string
service string
scopes []string
}
type tokenResponse struct {
Token string `json:"token"`
AccessToken string `json:"access_token"`
ExpiresIn int64 `json:"expires_in"`
IssuedAt string `json:"issued_at"`
}
// NewTransport creates an authentication-aware transport around base.
func NewTransport(base http.RoundTripper, authForURL AuthFunc) *Transport {
if base == nil {
base = http.DefaultTransport
}
return &Transport{
base: base,
authForURL: authForURL,
tokens: make(map[string]cachedToken),
challenges: make(map[string]bearerChallenge),
}
}
// RoundTrip implements http.RoundTripper.
func (t *Transport) RoundTrip(req *http.Request) (*http.Response, error) {
hasExplicitAuthorization := req.Header.Get("Authorization") != ""
outbound := cloneRequest(req)
t.applyAuthentication(outbound, hasExplicitAuthorization)
resp, err := t.base.RoundTrip(outbound)
if err != nil || resp.StatusCode != http.StatusUnauthorized {
return resp, err
}
if hasExplicitAuthorization {
return resp, nil
}
if registryProtectionSpace(req.URL) == "" {
return resp, nil
}
challenge, ok := parseBearerChallenge(resp.Header.Values("WWW-Authenticate"))
if !ok || !canReplay(req) {
return resp, nil
}
drainAndClose(resp.Body)
token, err := t.token(req.Context(), challenge)
if err != nil {
return nil, fmt.Errorf("registry authentication: %w", err)
}
t.rememberChallenge(req.URL, challenge)
retry, err := cloneRequestForRetry(req)
if err != nil {
return nil, err
}
t.applyConfiguredAuthentication(retry)
retry.Header.Set("Authorization", "Bearer "+token)
return t.base.RoundTrip(retry)
}
func (t *Transport) applyAuthentication(req *http.Request, hasExplicitAuthorization bool) {
t.applyConfiguredAuthentication(req)
if hasExplicitAuthorization {
return
}
if token := t.cachedTokenForRequest(req.URL); token != "" {
req.Header.Set("Authorization", "Bearer "+token)
}
}
func (t *Transport) applyConfiguredAuthentication(req *http.Request) {
if t.authForURL == nil {
return
}
name, value := t.authForURL(req.URL.String())
if name != "" && value != "" && req.Header.Get(name) == "" {
req.Header.Set(name, value)
}
}
func (t *Transport) token(ctx context.Context, challenge bearerChallenge) (string, error) {
key := challenge.key()
if token := t.cachedToken(key); token != "" {
return token, nil
}
token, expiresAt, err := t.fetchToken(ctx, challenge)
if err != nil {
return "", err
}
t.cacheToken(key, cachedToken{value: token, expiresAt: expiresAt})
return token, nil
}
func (t *Transport) cacheToken(key string, token cachedToken) {
now := time.Now()
t.mu.Lock()
defer t.mu.Unlock()
for cachedKey, cached := range t.tokens {
if !now.Before(cached.expiresAt) {
delete(t.tokens, cachedKey)
}
}
t.tokens[key] = token
}
func (t *Transport) fetchToken(ctx context.Context, challenge bearerChallenge) (string, time.Time, error) {
tokenURL, err := url.Parse(challenge.realm)
if err != nil || !tokenURL.IsAbs() || (tokenURL.Scheme != "https" && tokenURL.Scheme != "http") {
return "", time.Time{}, fmt.Errorf("invalid token realm %q", challenge.realm)
}
query := tokenURL.Query()
if challenge.service != "" {
query.Set("service", challenge.service)
}
for _, scope := range challenge.scopes {
query.Add("scope", scope)
}
query.Set("client_id", "git-pkgs-proxy")
tokenURL.RawQuery = query.Encode()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, tokenURL.String(), nil)
if err != nil {
return "", time.Time{}, err
}
client := &http.Client{Transport: configuredTransport{parent: t}}
resp, err := client.Do(req)
if err != nil {
return "", time.Time{}, fmt.Errorf("requesting token: %w", err)
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusMultipleChoices {
body, _ := io.ReadAll(io.LimitReader(resp.Body, maxTokenResponseSize))
return "", time.Time{}, fmt.Errorf("token service returned %d: %s", resp.StatusCode, strings.TrimSpace(string(body)))
}
var payload tokenResponse
if err := json.NewDecoder(io.LimitReader(resp.Body, maxTokenResponseSize)).Decode(&payload); err != nil {
return "", time.Time{}, fmt.Errorf("decoding token response: %w", err)
}
token := payload.Token
if token == "" {
token = payload.AccessToken
}
if token == "" {
return "", time.Time{}, fmt.Errorf("token response did not contain a token")
}
issuedAt := time.Now()
if payload.IssuedAt != "" {
if parsed, parseErr := time.Parse(time.RFC3339, payload.IssuedAt); parseErr == nil {
issuedAt = parsed
}
}
lifetime := time.Duration(payload.ExpiresIn) * time.Second
if lifetime <= 0 {
lifetime = defaultTokenLifetime
}
expiresAt := issuedAt.Add(lifetime).Add(-expirySkew(lifetime))
return token, expiresAt, nil
}
type configuredTransport struct {
parent *Transport
}
func (t configuredTransport) RoundTrip(req *http.Request) (*http.Response, error) {
outbound := cloneRequest(req)
t.parent.applyConfiguredAuthentication(outbound)
return t.parent.base.RoundTrip(outbound)
}
func (t *Transport) cachedTokenForRequest(requestURL *url.URL) string {
space := registryProtectionSpace(requestURL)
if space == "" {
return ""
}
t.mu.Lock()
challenge, ok := t.challenges[space]
t.mu.Unlock()
if !ok {
return ""
}
return t.cachedToken(challenge.key())
}
func (t *Transport) cachedToken(key string) string {
now := time.Now()
t.mu.Lock()
defer t.mu.Unlock()
token, ok := t.tokens[key]
if !ok {
return ""
}
if !now.Before(token.expiresAt) {
delete(t.tokens, key)
return ""
}
return token.value
}
func (t *Transport) rememberChallenge(requestURL *url.URL, challenge bearerChallenge) {
space := registryProtectionSpace(requestURL)
if space == "" {
return
}
t.mu.Lock()
t.challenges[space] = challenge
t.mu.Unlock()
}
func (c bearerChallenge) key() string {
return c.realm + "\x00" + c.service + "\x00" + strings.Join(c.scopes, "\x00")
}
func registryProtectionSpace(u *url.URL) string {
const registryPrefix = "/v2/"
if u == nil || !strings.HasPrefix(u.Path, registryPrefix) {
return ""
}
rest := strings.TrimPrefix(u.Path, registryPrefix)
end := len(rest)
for _, marker := range []string{"/blobs/", "/manifests/", "/tags/", "/referrers/"} {
if index := strings.Index(rest, marker); index >= 0 && index < end {
end = index
}
}
if end == len(rest) || end == 0 {
return ""
}
return u.Scheme + "://" + u.Host + registryPrefix + rest[:end]
}
func parseBearerChallenge(values []string) (bearerChallenge, bool) {
for _, value := range values {
params, ok := bearerParameters(value)
if !ok || params["realm"] == "" {
continue
}
challenge := bearerChallenge{
realm: params["realm"],
service: params["service"],
}
if scope := params["scope"]; scope != "" {
challenge.scopes = append(challenge.scopes, scope)
}
return challenge, true
}
return bearerChallenge{}, false
}
func bearerParameters(value string) (map[string]string, bool) {
start := findAuthScheme(value, "Bearer")
if start < 0 {
return nil, false
}
rest := value[start+len("Bearer"):]
params := make(map[string]string)
for {
rest = strings.TrimLeft(rest, " \t,")
if rest == "" {
break
}
keyEnd := strings.IndexAny(rest, "= \t,")
if keyEnd <= 0 {
break
}
key := strings.ToLower(rest[:keyEnd])
rest = strings.TrimLeft(rest[keyEnd:], " \t")
if rest == "" || rest[0] != '=' {
break
}
rest = strings.TrimLeft(rest[1:], " \t")
parsed, remaining, ok := parseAuthValue(rest)
if !ok {
return nil, false
}
params[key] = parsed
rest = remaining
}
return params, true
}
func findAuthScheme(value, scheme string) int {
inQuote := false
escaped := false
for index := 0; index+len(scheme) <= len(value); index++ {
char := value[index]
if escaped {
escaped = false
continue
}
if char == '\\' && inQuote {
escaped = true
continue
}
if char == '"' {
inQuote = !inQuote
continue
}
if inQuote || !strings.EqualFold(value[index:index+len(scheme)], scheme) {
continue
}
beforeOK := index == 0 || value[index-1] == ',' || value[index-1] == ' ' || value[index-1] == '\t'
after := index + len(scheme)
afterOK := after < len(value) && (value[after] == ' ' || value[after] == '\t')
if beforeOK && afterOK {
return index
}
}
return -1
}
func parseAuthValue(value string) (parsed, remaining string, ok bool) {
if value == "" {
return "", "", false
}
if value[0] != '"' {
end := strings.IndexAny(value, " \t,")
if end < 0 {
return value, "", true
}
return value[:end], value[end:], end > 0
}
var builder strings.Builder
escaped := false
for index := 1; index < len(value); index++ {
char := value[index]
if escaped {
builder.WriteByte(char)
escaped = false
continue
}
if char == '\\' {
escaped = true
continue
}
if char == '"' {
return builder.String(), value[index+1:], true
}
builder.WriteByte(char)
}
return "", "", false
}
func cloneRequest(req *http.Request) *http.Request {
clone := req.Clone(req.Context())
clone.Header = req.Header.Clone()
return clone
}
func canReplay(req *http.Request) bool {
return req.Body == nil || req.GetBody != nil
}
func cloneRequestForRetry(req *http.Request) (*http.Request, error) {
clone := cloneRequest(req)
if req.Body == nil {
return clone, nil
}
body, err := req.GetBody()
if err != nil {
return nil, fmt.Errorf("replaying authenticated request: %w", err)
}
clone.Body = body
return clone, nil
}
func expirySkew(lifetime time.Duration) time.Duration {
if lifetime < tokenExpirySkew*2 {
return lifetime / shortTokenSkewDivisor
}
return tokenExpirySkew
}
func drainAndClose(body io.ReadCloser) {
_, _ = io.Copy(io.Discard, io.LimitReader(body, maxTokenResponseSize))
_ = body.Close()
}

View file

@ -1,251 +0,0 @@
package httpclient
import (
"context"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
)
func TestTransportFollowsBearerChallengeAndCachesToken(t *testing.T) {
var registryRequests int
var tokenRequests int
var server *httptest.Server
server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/token":
tokenRequests++
if got := r.URL.Query().Get("service"); got != "registry.test" {
t.Errorf("service = %q, want %q", got, "registry.test")
}
if got := r.URL.Query().Get("scope"); got != "repository:library/test:pull" {
t.Errorf("scope = %q, want %q", got, "repository:library/test:pull")
}
w.Header().Set("Content-Type", "application/json")
_, _ = io.WriteString(w, `{"token":"registry-token","expires_in":3600}`)
case "/v2/library/test/blobs/sha256:first", "/v2/library/test/blobs/sha256:second":
registryRequests++
if r.Header.Get("Authorization") != "Bearer registry-token" {
w.Header().Set("WWW-Authenticate", `Bearer realm="`+server.URL+`/token",service="registry.test",scope="repository:library/test:pull"`)
http.Error(w, "authentication required", http.StatusUnauthorized)
return
}
_, _ = io.WriteString(w, "blob")
default:
http.NotFound(w, r)
}
}))
defer server.Close()
client := &http.Client{Transport: NewTransport(http.DefaultTransport, nil)}
for _, digest := range []string{"sha256:first", "sha256:second"} {
resp, err := client.Get(server.URL + "/v2/library/test/blobs/" + digest)
if err != nil {
t.Fatalf("GET %s: %v", digest, err)
}
body, readErr := io.ReadAll(resp.Body)
_ = resp.Body.Close()
if readErr != nil {
t.Fatalf("read %s response: %v", digest, readErr)
}
if resp.StatusCode != http.StatusOK {
t.Fatalf("GET %s status = %d, want %d", digest, resp.StatusCode, http.StatusOK)
}
if string(body) != "blob" {
t.Errorf("GET %s body = %q, want %q", digest, body, "blob")
}
}
if tokenRequests != 1 {
t.Errorf("token requests = %d, want 1", tokenRequests)
}
if registryRequests != 3 {
t.Errorf("registry requests = %d, want 3", registryRequests)
}
}
func TestTransportAddsConfiguredAuthentication(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if got := r.Header.Get("X-Registry-Token"); got != "configured-token" {
t.Errorf("X-Registry-Token = %q, want %q", got, "configured-token")
}
w.WriteHeader(http.StatusNoContent)
}))
defer server.Close()
authForURL := func(url string) (string, string) {
if strings.HasPrefix(url, server.URL) {
return "X-Registry-Token", "configured-token"
}
return "", ""
}
client := &http.Client{Transport: NewTransport(http.DefaultTransport, authForURL)}
resp, err := client.Get(server.URL + "/metadata")
if err != nil {
t.Fatalf("GET metadata: %v", err)
}
_ = resp.Body.Close()
if resp.StatusCode != http.StatusNoContent {
t.Errorf("status = %d, want %d", resp.StatusCode, http.StatusNoContent)
}
}
func TestTransportPreservesExplicitAuthentication(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if got := r.Header.Get("Authorization"); got != "Bearer explicit-token" {
t.Errorf("Authorization = %q, want %q", got, "Bearer explicit-token")
}
w.WriteHeader(http.StatusNoContent)
}))
defer server.Close()
authForURL := func(string) (string, string) {
return "Authorization", "Bearer configured-token"
}
client := &http.Client{Transport: NewTransport(http.DefaultTransport, authForURL)}
req, err := http.NewRequest(http.MethodGet, server.URL+"/artifact", nil)
if err != nil {
t.Fatal(err)
}
req.Header.Set("Authorization", "Bearer explicit-token")
resp, err := client.Do(req)
if err != nil {
t.Fatalf("GET artifact: %v", err)
}
_ = resp.Body.Close()
if resp.StatusCode != http.StatusNoContent {
t.Errorf("status = %d, want %d", resp.StatusCode, http.StatusNoContent)
}
}
func TestTransportDoesNotReplaceExplicitAuthenticationAfterBearerChallenge(t *testing.T) {
var registryRequests int
var tokenRequests int
var server *httptest.Server
server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/token":
tokenRequests++
_, _ = io.WriteString(w, `{"token":"registry-token"}`)
case "/v2/library/test/blobs/sha256:test":
registryRequests++
if got := r.Header.Get("Authorization"); got != "Bearer explicit-token" {
t.Errorf("Authorization = %q, want %q", got, "Bearer explicit-token")
}
w.Header().Set("WWW-Authenticate", `Bearer realm="`+server.URL+`/token"`)
http.Error(w, "authentication required", http.StatusUnauthorized)
default:
http.NotFound(w, r)
}
}))
defer server.Close()
client := &http.Client{Transport: NewTransport(http.DefaultTransport, nil)}
req, err := http.NewRequest(http.MethodGet, server.URL+"/v2/library/test/blobs/sha256:test", nil)
if err != nil {
t.Fatal(err)
}
req.Header.Set("Authorization", "Bearer explicit-token")
resp, err := client.Do(req)
if err != nil {
t.Fatalf("GET blob: %v", err)
}
_ = resp.Body.Close()
if resp.StatusCode != http.StatusUnauthorized {
t.Errorf("status = %d, want %d", resp.StatusCode, http.StatusUnauthorized)
}
if registryRequests != 1 {
t.Errorf("registry requests = %d, want 1", registryRequests)
}
if tokenRequests != 0 {
t.Errorf("token requests = %d, want 0", tokenRequests)
}
}
func TestTransportDoesNotForwardConfiguredAuthenticationOnTokenRedirect(t *testing.T) {
destination := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if got := r.Header.Get("X-Registry-Token"); got != "" {
t.Errorf("redirected X-Registry-Token = %q, want empty", got)
}
_, _ = io.WriteString(w, `{"token":"registry-token"}`)
}))
defer destination.Close()
source := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if got := r.Header.Get("X-Registry-Token"); got != "configured-token" {
t.Errorf("source X-Registry-Token = %q, want %q", got, "configured-token")
}
http.Redirect(w, r, destination.URL+"/token", http.StatusFound)
}))
defer source.Close()
authForURL := func(rawURL string) (string, string) {
if strings.HasPrefix(rawURL, source.URL) {
return "X-Registry-Token", "configured-token"
}
return "", ""
}
transport := NewTransport(http.DefaultTransport, authForURL)
token, _, err := transport.fetchToken(context.Background(), bearerChallenge{realm: source.URL + "/token"})
if err != nil {
t.Fatalf("fetchToken: %v", err)
}
if token != "registry-token" {
t.Errorf("token = %q, want %q", token, "registry-token")
}
}
func TestTransportPrunesExpiredTokens(t *testing.T) {
transport := NewTransport(http.DefaultTransport, nil)
transport.tokens["expired-unused"] = cachedToken{
value: "expired-token",
expiresAt: time.Now().Add(-time.Minute),
}
transport.cacheToken("current", cachedToken{
value: "current-token",
expiresAt: time.Now().Add(time.Minute),
})
if got := transport.cachedToken("current"); got != "current-token" {
t.Errorf("cachedToken(current) = %q, want %q", got, "current-token")
}
if _, ok := transport.tokens["expired-unused"]; ok {
t.Error("expired unused token was not pruned")
}
}
func TestTransportDoesNotFollowBearerChallengeOutsideOCIRegistry(t *testing.T) {
tokenRequests := 0
var server *httptest.Server
server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/token" {
tokenRequests++
_, _ = io.WriteString(w, `{"token":"unexpected"}`)
return
}
w.Header().Set("WWW-Authenticate", `Bearer realm="`+server.URL+`/token"`)
http.Error(w, "authentication required", http.StatusUnauthorized)
}))
defer server.Close()
client := &http.Client{Transport: NewTransport(http.DefaultTransport, nil)}
resp, err := client.Get(server.URL + "/api/packages")
if err != nil {
t.Fatalf("GET API: %v", err)
}
_ = resp.Body.Close()
if resp.StatusCode != http.StatusUnauthorized {
t.Errorf("status = %d, want %d", resp.StatusCode, http.StatusUnauthorized)
}
if tokenRequests != 0 {
t.Errorf("token requests = %d, want 0", tokenRequests)
}
}

View file

@ -6,7 +6,6 @@ import (
"strconv" "strconv"
"time" "time"
"github.com/git-pkgs/purl"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp" "github.com/prometheus/client_golang/prometheus/promhttp"
) )
@ -121,22 +120,6 @@ var (
Help: "Number of currently active requests", Help: "Number of currently active requests",
}, },
) )
IntegrityFailures = prometheus.NewCounterVec(
prometheus.CounterOpts{
Name: "proxy_integrity_failures_total",
Help: "Cached artifacts that failed hash verification on read",
},
[]string{"ecosystem"},
)
HealthProbeFailures = prometheus.NewCounterVec(
prometheus.CounterOpts{
Name: "proxy_health_probe_failures_total",
Help: "Total number of storage health probe failures, by step (write|size|read|verify|delete).",
},
[]string{"step"},
)
) )
func init() { func init() {
@ -155,8 +138,6 @@ func init() {
StorageOperationDuration, StorageOperationDuration,
StorageErrors, StorageErrors,
ActiveRequests, ActiveRequests,
IntegrityFailures,
HealthProbeFailures,
) )
} }
@ -174,12 +155,12 @@ func RecordRequest(ecosystem string, status int, duration time.Duration) {
// RecordCacheHit increments cache hit counter. // RecordCacheHit increments cache hit counter.
func RecordCacheHit(ecosystem string) { func RecordCacheHit(ecosystem string) {
CacheHits.WithLabelValues(purl.NormalizeEcosystem(ecosystem)).Inc() CacheHits.WithLabelValues(ecosystem).Inc()
} }
// RecordCacheMiss increments cache miss counter. // RecordCacheMiss increments cache miss counter.
func RecordCacheMiss(ecosystem string) { func RecordCacheMiss(ecosystem string) {
CacheMisses.WithLabelValues(purl.NormalizeEcosystem(ecosystem)).Inc() CacheMisses.WithLabelValues(ecosystem).Inc()
} }
// RecordUpstreamFetch tracks upstream fetch duration. // RecordUpstreamFetch tracks upstream fetch duration.
@ -197,17 +178,6 @@ func RecordStorageOperation(operation string, duration time.Duration) {
StorageOperationDuration.WithLabelValues(operation).Observe(duration.Seconds()) StorageOperationDuration.WithLabelValues(operation).Observe(duration.Seconds())
} }
// RecordIntegrityFailure increments the integrity failure counter.
func RecordIntegrityFailure(ecosystem string) {
IntegrityFailures.WithLabelValues(ecosystem).Inc()
}
// RecordHealthProbeFailure increments the health probe failure counter.
// step is one of: "write", "size", "read", "verify", "delete".
func RecordHealthProbeFailure(step string) {
HealthProbeFailures.WithLabelValues(step).Inc()
}
// RecordStorageError increments storage error counter. // RecordStorageError increments storage error counter.
func RecordStorageError(operation string) { func RecordStorageError(operation string) {
StorageErrors.WithLabelValues(operation).Inc() StorageErrors.WithLabelValues(operation).Inc()

View file

@ -6,7 +6,6 @@ import (
"time" "time"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/testutil"
dto "github.com/prometheus/client_model/go" dto "github.com/prometheus/client_model/go"
) )
@ -49,7 +48,7 @@ func TestRecordStorageOperations(t *testing.T) {
func TestUpdateCacheStats(t *testing.T) { func TestUpdateCacheStats(t *testing.T) {
UpdateCacheStats(1024*1024*1024, 100) // 1GB, 100 artifacts UpdateCacheStats(1024*1024*1024, 100) // 1GB, 100 artifacts
UpdateCacheStats(0, 0) // Empty cache UpdateCacheStats(0, 0) // Empty cache
// No panics = success // No panics = success
} }
@ -192,45 +191,22 @@ func TestMetricsEndpointOutput(t *testing.T) {
func TestMetricsLabeling(t *testing.T) { func TestMetricsLabeling(t *testing.T) {
// Test that different ecosystems are properly labeled // Test that different ecosystems are properly labeled
ecosystems := []struct { ecosystems := []string{"npm", "pypi", "cargo", "gem"}
input string
label string
}{
{input: "npm", label: "npm"},
{input: "pypi", label: "pypi"},
{input: "cargo", label: "cargo"},
{input: "gem", label: "rubygems"},
}
for _, eco := range ecosystems { for _, eco := range ecosystems {
RecordRequest(eco.input, 200, 10*time.Millisecond) RecordRequest(eco, 200, 10*time.Millisecond)
RecordCacheHit(eco.input) RecordCacheHit(eco)
} }
// Verify each ecosystem has metrics // Verify each ecosystem has metrics
for _, eco := range ecosystems { for _, eco := range ecosystems {
val := getMetricValue(t, CacheHits, eco.label) val := getMetricValue(t, CacheHits, eco)
if val == 0 { if val == 0 {
t.Errorf("no cache hits recorded for %s", eco.label) t.Errorf("no cache hits recorded for %s", eco)
} }
} }
} }
func TestCacheMetricLabelsAreNormalized(t *testing.T) {
rubyHitsBefore := testutil.ToFloat64(CacheHits.WithLabelValues("rubygems"))
composerMissesBefore := testutil.ToFloat64(CacheMisses.WithLabelValues("packagist"))
RecordCacheHit("gem")
RecordCacheMiss("composer")
if diff := testutil.ToFloat64(CacheHits.WithLabelValues("rubygems")) - rubyHitsBefore; diff != 1 {
t.Errorf("rubygems cache hits delta = %.0f, want 1", diff)
}
if diff := testutil.ToFloat64(CacheMisses.WithLabelValues("packagist")) - composerMissesBefore; diff != 1 {
t.Errorf("packagist cache misses delta = %.0f, want 1", diff)
}
}
func TestMetricNames(t *testing.T) { func TestMetricNames(t *testing.T) {
// Verify metric names follow Prometheus naming conventions // Verify metric names follow Prometheus naming conventions
expectedMetrics := []string{ expectedMetrics := []string{

View file

@ -1,207 +0,0 @@
package mirror
import (
"context"
"crypto/rand"
"fmt"
"sync"
"time"
)
// JobState represents the current state of a mirror job.
type JobState string
const (
JobStatePending JobState = "pending"
JobStateRunning JobState = "running"
JobStateComplete JobState = "complete"
JobStateFailed JobState = "failed"
JobStateCanceled JobState = "canceled"
)
const jobTTL = 1 * time.Hour
const cleanupInterval = 5 * time.Minute //nolint:mnd // cleanup ticker
// Job represents an async mirror operation.
type Job struct {
ID string `json:"id"`
State JobState `json:"state"`
Progress Progress `json:"progress"`
CreatedAt time.Time `json:"created_at"`
Error string `json:"error,omitempty"`
cancel context.CancelFunc
}
// JobRequest is the JSON body for starting a mirror job via the API.
type JobRequest struct {
PURLs []string `json:"purls,omitempty"`
Registry string `json:"registry,omitempty"`
}
// JobStore manages in-memory mirror jobs.
type JobStore struct {
mu sync.RWMutex
jobs map[string]*Job
mirror *Mirror
parentCtx context.Context
}
// NewJobStore creates a new job store. The parent context is used as the base
// for all job contexts so that jobs are canceled when the server shuts down.
func NewJobStore(ctx context.Context, m *Mirror) *JobStore {
return &JobStore{
jobs: make(map[string]*Job),
mirror: m,
parentCtx: ctx,
}
}
// Create starts a new mirror job and returns its ID.
func (js *JobStore) Create(req JobRequest) (string, error) {
source, err := js.sourceFromRequest(req)
if err != nil {
return "", err
}
id := newJobID()
ctx, cancel := context.WithCancel(js.parentCtx)
job := &Job{
ID: id,
State: JobStatePending,
CreatedAt: time.Now(),
cancel: cancel,
}
js.mu.Lock()
js.jobs[id] = job
js.mu.Unlock()
go js.runJob(ctx, cancel, job, source)
return id, nil
}
// Get returns a snapshot of a job by ID. The returned copy is safe to
// serialize without holding the lock.
func (js *JobStore) Get(id string) *Job {
js.mu.RLock()
defer js.mu.RUnlock()
job := js.jobs[id]
if job == nil {
return nil
}
snapshot := *job
snapshot.cancel = nil // don't leak cancel func
if len(job.Progress.Errors) > 0 {
snapshot.Progress.Errors = make([]MirrorError, len(job.Progress.Errors))
copy(snapshot.Progress.Errors, job.Progress.Errors)
}
return &snapshot
}
// Cancel cancels a running job.
func (js *JobStore) Cancel(id string) bool {
js.mu.Lock()
defer js.mu.Unlock()
job := js.jobs[id]
if job == nil || job.cancel == nil {
return false
}
if job.State != JobStatePending && job.State != JobStateRunning {
return false
}
job.cancel()
job.State = JobStateCanceled
return true
}
// Cleanup removes completed/failed/canceled jobs older than jobTTL.
func (js *JobStore) Cleanup() {
js.mu.Lock()
defer js.mu.Unlock()
for id, job := range js.jobs {
if job.State == JobStateComplete || job.State == JobStateFailed || job.State == JobStateCanceled {
if time.Since(job.CreatedAt) > jobTTL {
delete(js.jobs, id)
}
}
}
}
// StartCleanup runs periodic cleanup of old jobs until the context is canceled.
func (js *JobStore) StartCleanup(ctx context.Context) {
ticker := time.NewTicker(cleanupInterval)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
js.Cleanup()
}
}
}
func (js *JobStore) runJob(ctx context.Context, cancel context.CancelFunc, job *Job, source Source) {
defer cancel()
js.mu.Lock()
if job.State == JobStateCanceled {
js.mu.Unlock()
return
}
job.State = JobStateRunning
js.mu.Unlock()
progress, err := js.mirror.Run(ctx, source, func(p Progress) {
js.mu.Lock()
defer js.mu.Unlock()
if job.State == JobStateRunning {
job.Progress = p
}
})
js.mu.Lock()
defer js.mu.Unlock()
// Cancel() may have already set the state; don't overwrite it.
if job.State == JobStateCanceled {
return
}
if err != nil {
job.State = JobStateFailed
job.Error = err.Error()
return
}
job.Progress = *progress
if progress.Failed > 0 && progress.Completed == 0 {
job.State = JobStateFailed
} else {
job.State = JobStateComplete
}
}
func (js *JobStore) sourceFromRequest(req JobRequest) (Source, error) { //nolint:ireturn // interface return is the design
switch {
case len(req.PURLs) > 0:
return &PURLSource{PURLs: req.PURLs}, nil
case req.Registry != "":
return nil, fmt.Errorf("registry mirroring is not yet implemented; use purls instead")
default:
return nil, fmt.Errorf("request must include purls")
}
}
// newJobID generates a random hex job ID.
func newJobID() string {
b := make([]byte, 16) //nolint:mnd // 128-bit ID
_, _ = rand.Read(b)
return fmt.Sprintf("%x", b)
}

View file

@ -1,183 +0,0 @@
package mirror
import (
"context"
"testing"
"time"
)
func TestJobStoreCreateAndGet(t *testing.T) {
m := setupTestMirror(t, 1)
js := NewJobStore(context.Background(), m)
id, err := js.Create(JobRequest{
PURLs: []string{"pkg:npm/lodash@4.17.21"},
})
if err != nil {
t.Fatalf("Create() error = %v", err)
}
if id == "" {
t.Fatal("expected non-empty job ID")
}
// Wait for the job to start (it runs async)
time.Sleep(100 * time.Millisecond)
job := js.Get(id)
if job == nil {
t.Fatal("Get() returned nil")
}
if job.ID != id {
t.Errorf("job ID = %q, want %q", job.ID, id)
}
}
func TestJobStoreGetNotFound(t *testing.T) {
m := setupTestMirror(t, 1)
js := NewJobStore(context.Background(), m)
job := js.Get("nonexistent")
if job != nil {
t.Errorf("expected nil for nonexistent job, got %v", job)
}
}
func TestJobStoreCancelNotFound(t *testing.T) {
m := setupTestMirror(t, 1)
js := NewJobStore(context.Background(), m)
if js.Cancel("nonexistent") {
t.Error("expected Cancel to return false for nonexistent job")
}
}
func TestJobStoreCreateInvalidRequest(t *testing.T) {
m := setupTestMirror(t, 1)
js := NewJobStore(context.Background(), m)
_, err := js.Create(JobRequest{})
if err == nil {
t.Fatal("expected error for empty request")
}
}
func TestJobStoreMultipleJobs(t *testing.T) {
m := setupTestMirror(t, 1)
js := NewJobStore(context.Background(), m)
id1, err := js.Create(JobRequest{PURLs: []string{"pkg:npm/lodash@4.17.21"}})
if err != nil {
t.Fatalf("Create() error = %v", err)
}
id2, err := js.Create(JobRequest{PURLs: []string{"pkg:cargo/serde@1.0.0"}})
if err != nil {
t.Fatalf("Create() error = %v", err)
}
if id1 == id2 {
t.Error("expected different job IDs")
}
job1 := js.Get(id1)
job2 := js.Get(id2)
if job1 == nil || job2 == nil {
t.Fatal("expected both jobs to exist")
}
}
func TestSourceFromRequestPURLs(t *testing.T) {
m := setupTestMirror(t, 1)
js := NewJobStore(context.Background(), m)
source, err := js.sourceFromRequest(JobRequest{PURLs: []string{"pkg:npm/lodash@1.0.0"}})
if err != nil {
t.Fatalf("sourceFromRequest() error = %v", err)
}
if _, ok := source.(*PURLSource); !ok {
t.Errorf("expected *PURLSource, got %T", source)
}
}
func TestSourceFromRequestRegistryRejected(t *testing.T) {
m := setupTestMirror(t, 1)
js := NewJobStore(context.Background(), m)
_, err := js.sourceFromRequest(JobRequest{Registry: "npm"})
if err == nil {
t.Fatal("expected error for registry request")
}
}
func TestJobStoreCleanup(t *testing.T) {
m := setupTestMirror(t, 1)
js := NewJobStore(context.Background(), m)
// Add a completed job with old CreatedAt
js.mu.Lock()
js.jobs["old-job"] = &Job{
ID: "old-job",
State: JobStateComplete,
CreatedAt: time.Now().Add(-2 * time.Hour),
}
js.jobs["recent-job"] = &Job{
ID: "recent-job",
State: JobStateComplete,
CreatedAt: time.Now(),
}
js.jobs["running-job"] = &Job{
ID: "running-job",
State: JobStateRunning,
CreatedAt: time.Now().Add(-2 * time.Hour),
}
js.mu.Unlock()
js.Cleanup()
if js.Get("old-job") != nil {
t.Error("expected old completed job to be cleaned up")
}
if js.Get("recent-job") == nil {
t.Error("expected recent completed job to be kept")
}
if js.Get("running-job") == nil {
t.Error("expected running job to be kept regardless of age")
}
}
func TestJobStoreCancelPreservesStateAfterRunJob(t *testing.T) {
m := setupTestMirror(t, 1)
js := NewJobStore(context.Background(), m)
// 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"}})
if err != nil {
t.Fatalf("Create() error = %v", err)
}
// Cancel immediately -- the job may already be running
js.Cancel(id)
// Wait for runJob goroutine to finish
time.Sleep(200 * time.Millisecond)
job := js.Get(id)
if job == nil {
t.Fatal("Get() returned nil")
}
if job.State != JobStateCanceled {
t.Errorf("state = %q, want %q (cancel should not be overwritten by runJob)", job.State, JobStateCanceled)
}
}
func TestNewJobIDUnique(t *testing.T) {
ids := make(map[string]bool)
for range 100 {
id := newJobID()
if ids[id] {
t.Fatalf("duplicate job ID: %s", id)
}
ids[id] = true
}
}

View file

@ -1,228 +0,0 @@
// Package mirror provides selective package mirroring for pre-populating the proxy cache.
package mirror
import (
"context"
"fmt"
"log/slog"
"sync"
"sync/atomic"
"time"
"github.com/git-pkgs/proxy/internal/database"
"github.com/git-pkgs/proxy/internal/handler"
"github.com/git-pkgs/proxy/internal/storage"
"golang.org/x/sync/errgroup"
)
// Mirror pre-populates the proxy cache from various input sources.
type Mirror struct {
proxy *handler.Proxy
db *database.DB
storage storage.Storage
logger *slog.Logger
workers int
}
// New creates a new Mirror with the given dependencies.
func New(proxy *handler.Proxy, db *database.DB, store storage.Storage, logger *slog.Logger, workers int) *Mirror {
if workers < 1 {
workers = 1
}
return &Mirror{
proxy: proxy,
db: db,
storage: store,
logger: logger,
workers: workers,
}
}
// Progress tracks the state of a mirror operation.
type Progress struct {
Total int64 `json:"total"`
Completed int64 `json:"completed"`
Skipped int64 `json:"skipped"`
Failed int64 `json:"failed"`
Bytes int64 `json:"bytes"`
Errors []MirrorError `json:"errors,omitempty"`
StartedAt time.Time `json:"started_at"`
Phase string `json:"phase"`
}
// MirrorError records a single failed mirror attempt.
type MirrorError struct {
Ecosystem string `json:"ecosystem"`
Name string `json:"name"`
Version string `json:"version"`
Error string `json:"error"`
}
type progressTracker struct {
total atomic.Int64
completed atomic.Int64
skipped atomic.Int64
failed atomic.Int64
bytes atomic.Int64
mu sync.Mutex
errors []MirrorError
startedAt time.Time
phase atomic.Value // string
}
func newProgressTracker() *progressTracker {
pt := &progressTracker{
startedAt: time.Now(),
}
pt.phase.Store("resolving")
return pt
}
const maxTrackedErrors = 1000
const progressReportInterval = 500 * time.Millisecond //nolint:mnd // progress update frequency
func (pt *progressTracker) addError(eco, name, version, err string) {
pt.mu.Lock()
if len(pt.errors) < maxTrackedErrors {
pt.errors = append(pt.errors, MirrorError{
Ecosystem: eco,
Name: name,
Version: version,
Error: err,
})
}
pt.mu.Unlock()
}
func (pt *progressTracker) snapshot() Progress {
pt.mu.Lock()
errs := make([]MirrorError, len(pt.errors))
copy(errs, pt.errors)
pt.mu.Unlock()
phase, _ := pt.phase.Load().(string)
return Progress{
Total: pt.total.Load(),
Completed: pt.completed.Load(),
Skipped: pt.skipped.Load(),
Failed: pt.failed.Load(),
Bytes: pt.bytes.Load(),
Errors: errs,
StartedAt: pt.startedAt,
Phase: phase,
}
}
// ProgressFunc is called periodically with a snapshot of the current progress.
type ProgressFunc func(Progress)
// Run mirrors all packages from the source using a bounded worker pool.
// It returns the final progress when complete. If onProgress is non-nil,
// it is called with progress snapshots as work proceeds.
func (m *Mirror) Run(ctx context.Context, source Source, onProgress ...ProgressFunc) (*Progress, error) {
tracker := newProgressTracker()
// Collect items from source
var items []PackageVersion
tracker.phase.Store("resolving")
err := source.Enumerate(ctx, func(pv PackageVersion) error {
items = append(items, pv)
return nil
})
if err != nil {
return nil, fmt.Errorf("enumerating packages: %w", err)
}
tracker.total.Store(int64(len(items)))
tracker.phase.Store("downloading")
// Start periodic progress reporting if a callback was provided
var progressFn ProgressFunc
if len(onProgress) > 0 && onProgress[0] != nil {
progressFn = onProgress[0]
}
progressDone := make(chan struct{})
if progressFn != nil {
progressFn(tracker.snapshot()) // initial snapshot with total set
go func() {
ticker := time.NewTicker(progressReportInterval)
defer ticker.Stop()
for {
select {
case <-progressDone:
return
case <-ticker.C:
progressFn(tracker.snapshot())
}
}
}()
}
// Process items with bounded concurrency
g, gctx := errgroup.WithContext(ctx)
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)
return nil // never fail the group; errors are tracked
})
}
_ = g.Wait()
close(progressDone) // stop the progress reporter goroutine
tracker.phase.Store("complete")
p := tracker.snapshot()
// Send final snapshot
if progressFn != nil {
progressFn(p)
}
return &p, nil
}
// RunDryRun enumerates what would be mirrored without downloading.
func (m *Mirror) RunDryRun(ctx context.Context, source Source) ([]PackageVersion, error) {
var items []PackageVersion
err := source.Enumerate(ctx, func(pv PackageVersion) error {
items = append(items, pv)
return nil
})
return items, err
}
func (m *Mirror) mirrorOne(ctx context.Context, pv PackageVersion, tracker *progressTracker) {
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)
return
}
_ = result.Reader.Close()
if result.Cached {
tracker.skipped.Add(1)
m.logger.Debug("already cached",
"ecosystem", pv.Ecosystem, "name", pv.Name, "version", pv.Version)
} else {
tracker.completed.Add(1)
tracker.bytes.Add(result.Size)
m.logger.Info("mirrored",
"ecosystem", pv.Ecosystem, "name", pv.Name, "version", pv.Version,
"size", result.Size)
}
}

View file

@ -1,195 +0,0 @@
package mirror
import (
"context"
"log/slog"
"os"
"testing"
"time"
"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"
)
// setupTestMirror creates a Mirror with real DB and filesystem storage for integration tests.
func setupTestMirror(t *testing.T, workers int) *Mirror {
t.Helper()
dbPath := t.TempDir() + "/test.db"
db, err := database.Create(dbPath)
if err != nil {
t.Fatalf("creating database: %v", err)
}
if err := db.MigrateSchema(); err != nil {
t.Fatalf("migrating schema: %v", err)
}
t.Cleanup(func() { _ = db.Close() })
storeDir := t.TempDir()
store, err := storage.OpenBucket(context.Background(), "file://"+storeDir)
if err != nil {
t.Fatalf("opening storage: %v", err)
}
logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelWarn}))
fetcher := fetch.NewFetcher()
resolver := fetch.NewResolver()
proxy := handler.NewProxy(db, store, fetcher, resolver, logger)
return New(proxy, db, store, logger, workers)
}
const testPackageLodash = "lodash"
func TestMirrorRunEmptySource(t *testing.T) {
m := setupTestMirror(t, 2)
source := &PURLSource{PURLs: []string{}}
progress, err := m.Run(context.Background(), source)
if err != nil {
t.Fatalf("Run() error = %v", err)
}
if progress.Total != 0 {
t.Errorf("total = %d, want 0", progress.Total)
}
if progress.Phase != "complete" {
t.Errorf("phase = %q, want %q", progress.Phase, "complete")
}
}
func TestMirrorRunDryRun(t *testing.T) {
m := setupTestMirror(t, 1)
source := &PURLSource{
PURLs: []string{
"pkg:npm/lodash@4.17.21",
"pkg:cargo/serde@1.0.0",
},
}
items, err := m.RunDryRun(context.Background(), source)
if err != nil {
t.Fatalf("RunDryRun() error = %v", err)
}
if len(items) != 2 {
t.Fatalf("got %d items, want 2", len(items))
}
// Dry run should not modify the database
stats, err := m.db.GetCacheStats()
if err != nil {
t.Fatalf("GetCacheStats() error = %v", err)
}
if stats.TotalArtifacts != 0 {
t.Errorf("artifacts = %d, want 0 (dry run should not cache)", stats.TotalArtifacts)
}
}
func TestMirrorRunCanceled(t *testing.T) {
m := setupTestMirror(t, 1)
ctx, cancel := context.WithCancel(context.Background())
cancel() // cancel immediately
// Use a source that produces items but they'll all fail due to canceled context
source := &PURLSource{
PURLs: []string{"pkg:npm/lodash@4.17.21"},
}
progress, err := m.Run(ctx, source)
if err != nil {
t.Fatalf("Run() error = %v", err)
}
// With a canceled context, the fetch should fail
if progress.Failed != 1 {
t.Errorf("failed = %d, want 1", progress.Failed)
}
}
func TestProgressTrackerSnapshot(t *testing.T) {
pt := newProgressTracker()
pt.total.Store(10)
pt.completed.Store(5)
pt.skipped.Store(3)
pt.failed.Store(2)
pt.bytes.Store(1024)
pt.phase.Store("downloading")
pt.addError("npm", testPackageLodash, "4.17.21", "fetch failed")
snap := pt.snapshot()
if snap.Total != 10 {
t.Errorf("total = %d, want 10", snap.Total)
}
if snap.Completed != 5 {
t.Errorf("completed = %d, want 5", snap.Completed)
}
if snap.Skipped != 3 {
t.Errorf("skipped = %d, want 3", snap.Skipped)
}
if snap.Failed != 2 {
t.Errorf("failed = %d, want 2", snap.Failed)
}
if snap.Bytes != 1024 {
t.Errorf("bytes = %d, want 1024", snap.Bytes)
}
if snap.Phase != "downloading" {
t.Errorf("phase = %q, want %q", snap.Phase, "downloading")
}
if len(snap.Errors) != 1 {
t.Fatalf("errors = %d, want 1", len(snap.Errors))
}
if snap.Errors[0].Name != testPackageLodash {
t.Errorf("error name = %q, want %q", snap.Errors[0].Name, testPackageLodash)
}
if snap.StartedAt.IsZero() {
t.Error("started_at should not be zero")
}
}
func TestProgressTrackerConcurrentAccess(t *testing.T) {
pt := newProgressTracker()
done := make(chan struct{})
for range 10 {
go func() {
pt.completed.Add(1)
pt.addError("npm", "test", "1.0.0", "error")
_ = pt.snapshot()
done <- struct{}{}
}()
}
timeout := time.After(5 * time.Second)
for range 10 {
select {
case <-done:
case <-timeout:
t.Fatal("timed out waiting for goroutines")
}
}
snap := pt.snapshot()
if snap.Completed != 10 {
t.Errorf("completed = %d, want 10", snap.Completed)
}
if len(snap.Errors) != 10 {
t.Errorf("errors = %d, want 10", len(snap.Errors))
}
}
func TestNewMirrorDefaultWorkers(t *testing.T) {
m := New(nil, nil, nil, slog.Default(), 0)
if m.workers != 1 {
t.Errorf("workers = %d, want 1 (minimum)", m.workers)
}
m = New(nil, nil, nil, slog.Default(), -5)
if m.workers != 1 {
t.Errorf("workers = %d, want 1 (minimum)", m.workers)
}
}

View file

@ -1,190 +0,0 @@
package mirror
import (
"bytes"
"context"
"encoding/json"
"fmt"
"os"
cdx "github.com/CycloneDX/cyclonedx-go"
"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"
)
// PackageVersion identifies a specific package version to mirror.
type PackageVersion struct {
Ecosystem string
Name string
Version string
}
func (pv PackageVersion) String() string {
return fmt.Sprintf("pkg:%s/%s@%s", pv.Ecosystem, pv.Name, pv.Version)
}
// Source produces PackageVersion items for mirroring.
type Source interface {
Enumerate(ctx context.Context, fn func(PackageVersion) error) error
}
// PURLSource yields packages from PURL strings.
// Versioned PURLs produce a single item. Unversioned PURLs look up all versions from the registry.
type PURLSource struct {
PURLs []string
RegClient *registries.Client
}
func (s *PURLSource) Enumerate(ctx context.Context, fn func(PackageVersion) error) error {
client := s.RegClient
if client == nil {
client = registries.DefaultClient()
}
for _, purlStr := range s.PURLs {
p, err := purl.Parse(purlStr)
if err != nil {
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
}
if p.Version != "" {
if err := fn(PackageVersion{Ecosystem: ecosystem, Name: name, Version: p.Version}); err != nil {
return err
}
continue
}
// Unversioned: enumerate all versions
versions, err := s.fetchVersions(ctx, client, 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 {
return err
}
}
}
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
}
versions, err := reg.FetchVersions(ctx, name)
if err != nil {
return nil, err
}
result := make([]string, len(versions))
for i, v := range versions {
result[i] = v.Number
}
return result, nil
}
// SBOMSource extracts package versions from a CycloneDX or SPDX SBOM file.
type SBOMSource struct {
Path string
RegClient *registries.Client
}
func (s *SBOMSource) Enumerate(ctx context.Context, fn func(PackageVersion) error) error {
purls, err := s.extractPURLs()
if err != nil {
return fmt.Errorf("reading SBOM %s: %w", s.Path, err)
}
inner := &PURLSource{PURLs: purls, RegClient: s.RegClient}
return inner.Enumerate(ctx, fn)
}
func (s *SBOMSource) extractPURLs() ([]string, error) {
data, err := os.ReadFile(s.Path)
if err != nil {
return nil, err
}
// Try CycloneDX first
if purls, err := extractCycloneDXPURLs(data); err == nil && len(purls) > 0 {
return purls, nil
}
// Try SPDX JSON
if purls, err := extractSPDXJSONPURLs(data); err == nil && len(purls) > 0 {
return purls, nil
}
// Try SPDX tag-value
if purls, err := extractSPDXTVPURLs(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)
}
}
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
}

View file

@ -1,243 +0,0 @@
package mirror
import (
"context"
"encoding/json"
"os"
"path/filepath"
"testing"
)
func TestPURLSourceVersioned(t *testing.T) {
source := &PURLSource{
PURLs: []string{
"pkg:npm/lodash@4.17.21",
"pkg:cargo/serde@1.0.0",
"pkg:pypi/requests@2.31.0",
},
}
var items []PackageVersion
err := source.Enumerate(context.Background(), func(pv PackageVersion) error {
items = append(items, pv)
return nil
})
if err != nil {
t.Fatalf("Enumerate() error = %v", err)
}
if len(items) != 3 {
t.Fatalf("got %d items, want 3", len(items))
}
expected := []PackageVersion{
{Ecosystem: "npm", Name: "lodash", Version: "4.17.21"},
{Ecosystem: "cargo", Name: "serde", Version: "1.0.0"},
{Ecosystem: "pypi", Name: "requests", Version: "2.31.0"},
}
for i, want := range expected {
got := items[i]
if got.Ecosystem != want.Ecosystem || got.Name != want.Name || got.Version != want.Version {
t.Errorf("items[%d] = %v, want %v", i, got, want)
}
}
}
func TestPURLSourceScopedPackage(t *testing.T) {
source := &PURLSource{
PURLs: []string{"pkg:npm/%40babel/core@7.23.0"},
}
var items []PackageVersion
err := source.Enumerate(context.Background(), func(pv PackageVersion) error {
items = append(items, pv)
return nil
})
if err != nil {
t.Fatalf("Enumerate() error = %v", err)
}
if len(items) != 1 {
t.Fatalf("got %d items, want 1", len(items))
}
if items[0].Name != "@babel/core" {
t.Errorf("name = %q, want %q", items[0].Name, "@babel/core")
}
if items[0].Version != "7.23.0" {
t.Errorf("version = %q, want %q", items[0].Version, "7.23.0")
}
}
func TestPURLSourceInvalid(t *testing.T) {
source := &PURLSource{
PURLs: []string{"not-a-purl"},
}
err := source.Enumerate(context.Background(), func(pv PackageVersion) error {
return nil
})
if err == nil {
t.Fatal("expected error for invalid PURL")
}
}
func TestPURLSourceCallbackError(t *testing.T) {
source := &PURLSource{
PURLs: []string{"pkg:npm/lodash@4.17.21"},
}
wantErr := context.Canceled
err := source.Enumerate(context.Background(), func(pv PackageVersion) error {
return wantErr
})
if err != wantErr {
t.Fatalf("got error %v, want %v", err, wantErr)
}
}
func TestPackageVersionString(t *testing.T) {
pv := PackageVersion{Ecosystem: "npm", Name: "lodash", Version: "4.17.21"}
got := pv.String()
want := "pkg:npm/lodash@4.17.21"
if got != want {
t.Errorf("String() = %q, want %q", got, want)
}
}
func TestSBOMSourceCycloneDXJSON(t *testing.T) {
bom := map[string]any{
"bomFormat": "CycloneDX",
"specVersion": "1.4",
"components": []map[string]any{
{"type": "library", "name": "lodash", "version": "4.17.21", "purl": "pkg:npm/lodash@4.17.21"},
{"type": "library", "name": "serde", "version": "1.0.0", "purl": "pkg:cargo/serde@1.0.0"},
},
}
path := writeTempJSON(t, bom)
source := &SBOMSource{Path: path}
var items []PackageVersion
err := source.Enumerate(context.Background(), func(pv PackageVersion) error {
items = append(items, pv)
return nil
})
if err != nil {
t.Fatalf("Enumerate() error = %v", err)
}
if len(items) != 2 {
t.Fatalf("got %d items, want 2", len(items))
}
if items[0].Ecosystem != "npm" || items[0].Name != "lodash" || items[0].Version != "4.17.21" {
t.Errorf("items[0] = %v", items[0])
}
if items[1].Ecosystem != "cargo" || items[1].Name != "serde" || items[1].Version != "1.0.0" {
t.Errorf("items[1] = %v", items[1])
}
}
func TestSBOMSourceSPDXJSON(t *testing.T) {
doc := map[string]any{
"spdxVersion": "SPDX-2.3",
"dataLicense": "CC0-1.0",
"SPDXID": "SPDXRef-DOCUMENT",
"name": "test",
"documentNamespace": "https://example.com/test",
"packages": []map[string]any{
{
"SPDXID": "SPDXRef-Package",
"name": "lodash",
"version": "4.17.21",
"downloadLocation": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz",
"externalRefs": []map[string]any{
{
"referenceCategory": "PACKAGE-MANAGER",
"referenceType": "purl",
"referenceLocator": "pkg:npm/lodash@4.17.21",
},
},
},
},
}
path := writeTempJSON(t, doc)
source := &SBOMSource{Path: path}
var items []PackageVersion
err := source.Enumerate(context.Background(), func(pv PackageVersion) error {
items = append(items, pv)
return nil
})
if err != nil {
t.Fatalf("Enumerate() error = %v", err)
}
if len(items) != 1 {
t.Fatalf("got %d items, want 1", len(items))
}
if items[0].Name != "lodash" || items[0].Version != "4.17.21" {
t.Errorf("items[0] = %v", items[0])
}
}
func TestSBOMSourceNonexistentFile(t *testing.T) {
source := &SBOMSource{Path: "/nonexistent/sbom.json"}
err := source.Enumerate(context.Background(), func(pv PackageVersion) error {
return nil
})
if err == nil {
t.Fatal("expected error for nonexistent file")
}
}
func TestSBOMSourceInvalidFormat(t *testing.T) {
path := filepath.Join(t.TempDir(), "invalid.txt")
if err := os.WriteFile(path, []byte("this is not an SBOM"), 0644); err != nil {
t.Fatal(err)
}
source := &SBOMSource{Path: path}
err := source.Enumerate(context.Background(), func(pv PackageVersion) error {
return nil
})
if err == nil {
t.Fatal("expected error for invalid SBOM")
}
}
func TestSBOMSourceEmptyCycloneDX(t *testing.T) {
bom := map[string]any{
"bomFormat": "CycloneDX",
"specVersion": "1.4",
}
path := writeTempJSON(t, bom)
// This should fall through to SPDX parsing, which will also fail,
// resulting in an error about not being able to parse
source := &SBOMSource{Path: path}
err := source.Enumerate(context.Background(), func(pv PackageVersion) error {
return nil
})
if err == nil {
t.Fatal("expected error for empty SBOM")
}
}
func writeTempJSON(t *testing.T, v any) string {
t.Helper()
data, err := json.Marshal(v)
if err != nil {
t.Fatal(err)
}
path := filepath.Join(t.TempDir(), "sbom.json")
if err := os.WriteFile(path, data, 0644); err != nil {
t.Fatal(err)
}
return path
}

View file

@ -12,12 +12,6 @@ import (
"github.com/go-chi/chi/v5" "github.com/go-chi/chi/v5"
) )
const (
maxBodySize = 1 << 20 // 1 MB
licenseCategoryUnknown = "unknown"
defaultSortBy = "hits"
)
// APIHandler provides REST endpoints for package enrichment data. // APIHandler provides REST endpoints for package enrichment data.
type APIHandler struct { type APIHandler struct {
enrichment *enrichment.Service enrichment *enrichment.Service
@ -135,70 +129,33 @@ type BulkResponse struct {
Packages map[string]*PackageResponse `json:"packages"` Packages map[string]*PackageResponse `json:"packages"`
} }
// HandlePackagePath dispatches /api/package/{ecosystem}/* to the appropriate handler. // HandleGetPackage handles GET /api/package/{ecosystem}/{name}
// Resolves namespaced package names (Composer vendor/name, npm @scope/name) from the path. func (h *APIHandler) HandleGetPackage(w http.ResponseWriter, r *http.Request) {
func (h *APIHandler) HandlePackagePath(w http.ResponseWriter, r *http.Request) {
ecosystem := chi.URLParam(r, "ecosystem") ecosystem := chi.URLParam(r, "ecosystem")
segments, err := packagePathSegments(r) name := chi.URLParam(r, "name")
if err != nil {
badRequest(w, err.Error()) if ecosystem == "" || name == "" {
http.Error(w, "ecosystem and name are required", http.StatusBadRequest)
return return
} }
if ecosystem == "" || len(segments) == 0 { // Handle scoped npm packages (e.g., @scope/name)
badRequest(w, "ecosystem and name are required") if strings.HasPrefix(name, "@") {
return // The path is split, so we need to get the rest
} rest := chi.URLParam(r, "rest")
if rest != "" {
// For the API, we don't have a DB to resolve names, so we use a heuristic: name = name + "/" + rest
// the last segment that looks like a version (contains a digit) is the version,
// everything before it is the name. If no version-like segment, it's all name.
//
// With 1 segment: package lookup (name only)
// With 2+ segments: last segment is version, rest is name
// Exception: if this is a namespaced ecosystem and we have exactly 2 segments,
// it could be vendor/name with no version. The enrichment service handles
// both cases (it will try to look up the package either way).
if len(segments) == 1 {
h.getPackage(w, r, ecosystem, segments[0])
return
}
// Try the full path as a package name first via enrichment.
// If it resolves, this is a package-only lookup.
fullName := strings.Join(segments, "/")
info, err := h.enrichment.EnrichPackage(r.Context(), ecosystem, fullName)
if err == nil && info != nil {
resp := &PackageResponse{
Ecosystem: info.Ecosystem,
Name: info.Name,
LatestVersion: info.LatestVersion,
License: info.License,
LicenseCategory: string(h.enrichment.CategorizeLicense(info.License)),
Description: info.Description,
Homepage: info.Homepage,
Repository: info.Repository,
RegistryURL: info.RegistryURL,
} }
writeJSON(w, resp)
return
} }
// Otherwise, last segment is the version.
name := strings.Join(segments[:len(segments)-1], "/")
version := segments[len(segments)-1]
h.getVersion(w, r, ecosystem, name, version)
}
func (h *APIHandler) getPackage(w http.ResponseWriter, r *http.Request, ecosystem, name string) {
info, err := h.enrichment.EnrichPackage(r.Context(), ecosystem, name) info, err := h.enrichment.EnrichPackage(r.Context(), ecosystem, name)
if err != nil { if err != nil {
writeError(w, http.StatusBadGateway, ErrCodeUpstream, "failed to enrich package") http.Error(w, err.Error(), http.StatusInternalServerError)
return return
} }
if info == nil { if info == nil {
notFound(w, "package not found") http.Error(w, "package not found", http.StatusNotFound)
return return
} }
@ -217,10 +174,20 @@ func (h *APIHandler) getPackage(w http.ResponseWriter, r *http.Request, ecosyste
writeJSON(w, resp) writeJSON(w, resp)
} }
func (h *APIHandler) getVersion(w http.ResponseWriter, r *http.Request, ecosystem, name, version string) { // HandleGetVersion handles GET /api/package/{ecosystem}/{name}/{version}
func (h *APIHandler) HandleGetVersion(w http.ResponseWriter, r *http.Request) {
ecosystem := chi.URLParam(r, "ecosystem")
name := chi.URLParam(r, "name")
version := chi.URLParam(r, "version")
if ecosystem == "" || name == "" || version == "" {
http.Error(w, "ecosystem, name, and version are required", http.StatusBadRequest)
return
}
result, err := h.enrichment.EnrichFull(r.Context(), ecosystem, name, version) result, err := h.enrichment.EnrichFull(r.Context(), ecosystem, name, version)
if err != nil { if err != nil {
writeError(w, http.StatusBadGateway, ErrCodeUpstream, "failed to enrich version") http.Error(w, err.Error(), http.StatusInternalServerError)
return return
} }
@ -272,39 +239,25 @@ func (h *APIHandler) getVersion(w http.ResponseWriter, r *http.Request, ecosyste
writeJSON(w, resp) writeJSON(w, resp)
} }
// HandleVulnsPath dispatches /api/vulns/{ecosystem}/* to the vulns handler. // HandleGetVulns handles GET /api/vulns/{ecosystem}/{name}
// Supports both {name} and {name}/{version} paths with namespaced package names. func (h *APIHandler) HandleGetVulns(w http.ResponseWriter, r *http.Request) {
func (h *APIHandler) HandleVulnsPath(w http.ResponseWriter, r *http.Request) {
ecosystem := chi.URLParam(r, "ecosystem") ecosystem := chi.URLParam(r, "ecosystem")
segments, err := packagePathSegments(r) name := chi.URLParam(r, "name")
if err != nil { version := chi.URLParam(r, "version")
badRequest(w, err.Error())
if ecosystem == "" || name == "" {
http.Error(w, "ecosystem and name are required", http.StatusBadRequest)
return return
} }
if ecosystem == "" || len(segments) == 0 { // If no version specified, use "0" to get all vulnerabilities
badRequest(w, "ecosystem and name are required") if version == "" {
return version = "0"
}
// Last segment could be a version. Try full path as name first,
// then split off the last segment as version.
name := strings.Join(segments, "/")
version := "0"
if len(segments) > 1 {
// Try enrichment with the full path as name.
// If it doesn't resolve, assume last segment is version.
info, err := h.enrichment.EnrichPackage(r.Context(), ecosystem, name)
if err != nil || info == nil {
name = strings.Join(segments[:len(segments)-1], "/")
version = segments[len(segments)-1]
}
} }
vulns, err := h.enrichment.CheckVulnerabilities(r.Context(), ecosystem, name, version) vulns, err := h.enrichment.CheckVulnerabilities(r.Context(), ecosystem, name, version)
if err != nil { if err != nil {
writeError(w, http.StatusBadGateway, ErrCodeUpstream, "failed to check vulnerabilities") http.Error(w, err.Error(), http.StatusInternalServerError)
return return
} }
@ -330,25 +283,15 @@ func (h *APIHandler) HandleVulnsPath(w http.ResponseWriter, r *http.Request) {
} }
// HandleOutdated handles POST /api/outdated // HandleOutdated handles POST /api/outdated
// @Summary Check outdated packages
// @Tags api
// @Accept json
// @Produce json
// @Param request body OutdatedRequest true "Packages to check"
// @Success 200 {object} OutdatedResponse
// @Failure 400 {object} ErrorResponse
// @Failure 500 {object} ErrorResponse
// @Router /api/outdated [post]
func (h *APIHandler) HandleOutdated(w http.ResponseWriter, r *http.Request) { func (h *APIHandler) HandleOutdated(w http.ResponseWriter, r *http.Request) {
r.Body = http.MaxBytesReader(w, r.Body, maxBodySize)
var req OutdatedRequest var req OutdatedRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil { if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
badRequest(w, "invalid request body") http.Error(w, "invalid request body", http.StatusBadRequest)
return return
} }
if len(req.Packages) == 0 { if len(req.Packages) == 0 {
badRequest(w, "packages list is required") http.Error(w, "packages list is required", http.StatusBadRequest)
return return
} }
@ -376,25 +319,15 @@ func (h *APIHandler) HandleOutdated(w http.ResponseWriter, r *http.Request) {
} }
// HandleBulkLookup handles POST /api/bulk // HandleBulkLookup handles POST /api/bulk
// @Summary Bulk package lookup by PURL
// @Tags api
// @Accept json
// @Produce json
// @Param request body BulkRequest true "PURLs"
// @Success 200 {object} BulkResponse
// @Failure 400 {object} ErrorResponse
// @Failure 500 {object} ErrorResponse
// @Router /api/bulk [post]
func (h *APIHandler) HandleBulkLookup(w http.ResponseWriter, r *http.Request) { func (h *APIHandler) HandleBulkLookup(w http.ResponseWriter, r *http.Request) {
r.Body = http.MaxBytesReader(w, r.Body, maxBodySize)
var req BulkRequest var req BulkRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil { if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
badRequest(w, "invalid request body") http.Error(w, "invalid request body", http.StatusBadRequest)
return return
} }
if len(req.PURLs) == 0 { if len(req.PURLs) == 0 {
badRequest(w, "purls list is required") http.Error(w, "purls list is required", http.StatusBadRequest)
return return
} }
@ -476,21 +409,12 @@ type SearchPackageResult struct {
} }
// HandleSearch handles GET /api/search // HandleSearch handles GET /api/search
// @Summary Search cached packages
// @Tags api
// @Produce json
// @Param q query string true "Query"
// @Param ecosystem query string false "Ecosystem"
// @Success 200 {object} SearchResponse
// @Failure 400 {object} ErrorResponse
// @Failure 500 {object} ErrorResponse
// @Router /api/search [get]
func (h *APIHandler) HandleSearch(w http.ResponseWriter, r *http.Request) { func (h *APIHandler) HandleSearch(w http.ResponseWriter, r *http.Request) {
query := r.URL.Query().Get("q") query := r.URL.Query().Get("q")
ecosystem := r.URL.Query().Get("ecosystem") ecosystem := r.URL.Query().Get("ecosystem")
if query == "" { if query == "" {
badRequest(w, "query parameter 'q' is required") http.Error(w, "query parameter 'q' is required", http.StatusBadRequest)
return return
} }
@ -500,7 +424,7 @@ func (h *APIHandler) HandleSearch(w http.ResponseWriter, r *http.Request) {
// Search in database // Search in database
results, err := h.db.SearchPackages(query, ecosystem, limit, (page-1)*limit) results, err := h.db.SearchPackages(query, ecosystem, limit, (page-1)*limit)
if err != nil { if err != nil {
internalError(w, "search failed") http.Error(w, err.Error(), http.StatusInternalServerError)
return return
} }
@ -544,7 +468,7 @@ func (h *APIHandler) HandleSearch(w http.ResponseWriter, r *http.Request) {
func writeJSON(w http.ResponseWriter, v any) { func writeJSON(w http.ResponseWriter, v any) {
w.Header().Set("Content-Type", "application/json") w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(v); err != nil { if err := json.NewEncoder(w).Encode(v); err != nil {
internalError(w, "failed to encode response") http.Error(w, "failed to encode response", http.StatusInternalServerError)
} }
} }
@ -573,32 +497,23 @@ type PackageListResult struct {
} }
// HandlePackagesList handles GET /api/packages // HandlePackagesList handles GET /api/packages
// @Summary List cached packages
// @Tags api
// @Produce json
// @Param ecosystem query string false "Ecosystem"
// @Param sort query string false "Sort" Enums(hits,name,size,cached_at,ecosystem,vulns)
// @Success 200 {object} PackagesListResponse
// @Failure 400 {object} ErrorResponse
// @Failure 500 {object} ErrorResponse
// @Router /api/packages [get]
func (h *APIHandler) HandlePackagesList(w http.ResponseWriter, r *http.Request) { func (h *APIHandler) HandlePackagesList(w http.ResponseWriter, r *http.Request) {
ecosystem := r.URL.Query().Get("ecosystem") ecosystem := r.URL.Query().Get("ecosystem")
sortBy := r.URL.Query().Get("sort") sortBy := r.URL.Query().Get("sort")
if sortBy == "" { if sortBy == "" {
sortBy = defaultSortBy sortBy = "hits"
} }
validSorts := map[string]bool{ validSorts := map[string]bool{
defaultSortBy: true, "hits": true,
"name": true, "name": true,
"size": true, "size": true,
"cached_at": true, "cached_at": true,
"ecosystem": true, "ecosystem": true,
"vulns": true, "vulns": true,
} }
if !validSorts[sortBy] { if !validSorts[sortBy] {
badRequest(w, "invalid sort parameter") http.Error(w, "invalid sort parameter", http.StatusBadRequest)
return return
} }
@ -607,7 +522,7 @@ func (h *APIHandler) HandlePackagesList(w http.ResponseWriter, r *http.Request)
packages, err := h.db.ListCachedPackages(ecosystem, sortBy, limit, (page-1)*limit) packages, err := h.db.ListCachedPackages(ecosystem, sortBy, limit, (page-1)*limit)
if err != nil { if err != nil {
internalError(w, "failed to list packages") http.Error(w, err.Error(), http.StatusInternalServerError)
return return
} }
@ -632,7 +547,7 @@ func (h *APIHandler) HandlePackagesList(w http.ResponseWriter, r *http.Request)
latestVersion = pkg.LatestVersion.String latestVersion = pkg.LatestVersion.String
} }
license := "" license := ""
licenseCategory := licenseCategoryUnknown licenseCategory := "unknown"
if pkg.License.Valid { if pkg.License.Valid {
license = pkg.License.String license = pkg.License.String
if h.enrichment != nil { if h.enrichment != nil {

View file

@ -9,16 +9,12 @@ import (
"net/http/httptest" "net/http/httptest"
"os" "os"
"path/filepath" "path/filepath"
"strings"
"testing" "testing"
"github.com/git-pkgs/proxy/internal/database" "github.com/git-pkgs/proxy/internal/database"
"github.com/git-pkgs/proxy/internal/enrichment" "github.com/git-pkgs/proxy/internal/enrichment"
"github.com/go-chi/chi/v5"
) )
const testEcosystemNPM = "npm"
func TestNewAPIHandler(t *testing.T) { func TestNewAPIHandler(t *testing.T) {
logger := slog.New(slog.NewTextHandler(os.Stdout, nil)) logger := slog.New(slog.NewTextHandler(os.Stdout, nil))
svc := enrichment.New(logger) svc := enrichment.New(logger)
@ -32,66 +28,55 @@ func TestNewAPIHandler(t *testing.T) {
} }
} }
func TestHandlePackagePath_MissingParams(t *testing.T) { func TestHandleGetPackage_MissingParams(t *testing.T) {
logger := slog.New(slog.NewTextHandler(os.Stdout, nil)) logger := slog.New(slog.NewTextHandler(os.Stdout, nil))
svc := enrichment.New(logger) svc := enrichment.New(logger)
h := NewAPIHandler(svc, nil) h := NewAPIHandler(svc, nil)
r := chi.NewRouter()
r.Get("/api/package/{ecosystem}/*", h.HandlePackagePath)
req := httptest.NewRequest("GET", "/api/package//", nil) req := httptest.NewRequest("GET", "/api/package//", nil)
req.SetPathValue("ecosystem", "")
req.SetPathValue("name", "")
w := httptest.NewRecorder() w := httptest.NewRecorder()
r.ServeHTTP(w, req) h.HandleGetPackage(w, req)
if w.Code != http.StatusBadRequest && w.Code != http.StatusNotFound { if w.Code != http.StatusBadRequest {
t.Errorf("expected status 400 or 404, got %d", w.Code) t.Errorf("expected status %d, got %d", http.StatusBadRequest, w.Code)
} }
} }
func TestHandlePackagePath_InvalidName(t *testing.T) { func TestHandleGetVersion_MissingParams(t *testing.T) {
logger := slog.New(slog.NewTextHandler(os.Stdout, nil)) logger := slog.New(slog.NewTextHandler(os.Stdout, nil))
svc := enrichment.New(logger) svc := enrichment.New(logger)
h := NewAPIHandler(svc, nil) h := NewAPIHandler(svc, nil)
r := chi.NewRouter() req := httptest.NewRequest("GET", "/api/package///", nil)
r.Get("/api/package/{ecosystem}/*", h.HandlePackagePath) req.SetPathValue("ecosystem", "")
req.SetPathValue("name", "")
req.SetPathValue("version", "")
tests := []struct { w := httptest.NewRecorder()
name string h.HandleGetVersion(w, req)
path string
}{
{"null byte", "/api/package/npm/lodash%00"},
{"too long", "/api/package/npm/" + strings.Repeat("a", maxPackagePathLen+1)},
}
for _, tt := range tests { if w.Code != http.StatusBadRequest {
t.Run(tt.name, func(t *testing.T) { t.Errorf("expected status %d, got %d", http.StatusBadRequest, w.Code)
req := httptest.NewRequest("GET", tt.path, nil)
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
if w.Code != http.StatusBadRequest {
t.Errorf("expected status 400, got %d", w.Code)
}
})
} }
} }
func TestHandleVulnsPath_MissingParams(t *testing.T) { func TestHandleGetVulns_MissingParams(t *testing.T) {
logger := slog.New(slog.NewTextHandler(os.Stdout, nil)) logger := slog.New(slog.NewTextHandler(os.Stdout, nil))
svc := enrichment.New(logger) svc := enrichment.New(logger)
h := NewAPIHandler(svc, nil) h := NewAPIHandler(svc, nil)
r := chi.NewRouter()
r.Get("/api/vulns/{ecosystem}/*", h.HandleVulnsPath)
req := httptest.NewRequest("GET", "/api/vulns//", nil) req := httptest.NewRequest("GET", "/api/vulns//", nil)
w := httptest.NewRecorder() req.SetPathValue("ecosystem", "")
r.ServeHTTP(w, req) req.SetPathValue("name", "")
if w.Code != http.StatusBadRequest && w.Code != http.StatusNotFound { w := httptest.NewRecorder()
t.Errorf("expected status 400 or 404, got %d", w.Code) h.HandleGetVulns(w, req)
if w.Code != http.StatusBadRequest {
t.Errorf("expected status %d, got %d", http.StatusBadRequest, w.Code)
} }
} }
@ -109,25 +94,6 @@ func TestHandleOutdated_EmptyBody(t *testing.T) {
} }
} }
func TestHandleOutdated_OversizedBody(t *testing.T) {
logger := slog.New(slog.NewTextHandler(os.Stdout, nil))
svc := enrichment.New(logger)
h := NewAPIHandler(svc, nil)
// Send a body larger than 1 MB
body := make([]byte, 2<<20)
for i := range body {
body[i] = 'x'
}
req := httptest.NewRequest("POST", "/api/outdated", bytes.NewReader(body))
w := httptest.NewRecorder()
h.HandleOutdated(w, req)
if w.Code != http.StatusBadRequest {
t.Errorf("expected status %d for oversized body, got %d", http.StatusBadRequest, w.Code)
}
}
func TestHandleOutdated_InvalidJSON(t *testing.T) { func TestHandleOutdated_InvalidJSON(t *testing.T) {
logger := slog.New(slog.NewTextHandler(os.Stdout, nil)) logger := slog.New(slog.NewTextHandler(os.Stdout, nil))
svc := enrichment.New(logger) svc := enrichment.New(logger)
@ -192,7 +158,7 @@ func TestWriteJSON(t *testing.T) {
func TestPackageResponseJSON(t *testing.T) { func TestPackageResponseJSON(t *testing.T) {
resp := &PackageResponse{ resp := &PackageResponse{
Ecosystem: testEcosystemNPM, Ecosystem: "npm",
Name: "lodash", Name: "lodash",
LatestVersion: "4.17.21", LatestVersion: "4.17.21",
License: "MIT", License: "MIT",
@ -213,7 +179,7 @@ func TestPackageResponseJSON(t *testing.T) {
t.Fatalf("failed to unmarshal: %v", err) t.Fatalf("failed to unmarshal: %v", err)
} }
if decoded.Ecosystem != testEcosystemNPM { if decoded.Ecosystem != "npm" {
t.Errorf("expected ecosystem npm, got %s", decoded.Ecosystem) t.Errorf("expected ecosystem npm, got %s", decoded.Ecosystem)
} }
if decoded.Name != "lodash" { if decoded.Name != "lodash" {
@ -324,7 +290,7 @@ func TestHandleSearch_WithNullValues(t *testing.T) {
pkg := &database.Package{ pkg := &database.Package{
PURL: "pkg:npm/api-test", PURL: "pkg:npm/api-test",
Ecosystem: testEcosystemNPM, Ecosystem: "npm",
Name: "api-test", Name: "api-test",
} }
if err := db.UpsertPackage(pkg); err != nil { if err := db.UpsertPackage(pkg); err != nil {
@ -383,109 +349,3 @@ func TestHandleSearch_WithNullValues(t *testing.T) {
t.Errorf("expected 3 hits, got %d", result.Hits) t.Errorf("expected 3 hits, got %d", result.Hits)
} }
} }
func TestHandlePackagesListAPI(t *testing.T) {
logger := slog.New(slog.NewTextHandler(os.Stdout, nil))
svc := enrichment.New(logger)
dir := t.TempDir()
dbPath := filepath.Join(dir, "test.db")
db, err := database.Create(dbPath)
if err != nil {
t.Fatalf("Create failed: %v", err)
}
defer func() { _ = db.Close() }()
// Seed two packages
for _, name := range []string{"api-list-one", "api-list-two"} {
pkg := &database.Package{
PURL: "pkg:npm/" + name,
Ecosystem: testEcosystemNPM,
Name: name,
}
if err := db.UpsertPackage(pkg); err != nil {
t.Fatalf("UpsertPackage failed: %v", err)
}
ver := &database.Version{
PURL: "pkg:npm/" + name + "@1.0.0",
PackagePURL: pkg.PURL,
}
if err := db.UpsertVersion(ver); err != nil {
t.Fatalf("UpsertVersion failed: %v", err)
}
art := &database.Artifact{
VersionPURL: ver.PURL,
Filename: name + "-1.0.0.tgz",
UpstreamURL: "https://registry.npmjs.org/" + name + "/-/" + name + "-1.0.0.tgz",
StoragePath: sql.NullString{String: "/tmp/test.tgz", Valid: true},
}
if err := db.UpsertArtifact(art); err != nil {
t.Fatalf("UpsertArtifact failed: %v", err)
}
}
h := NewAPIHandler(svc, db)
r := chi.NewRouter()
r.Get("/api/packages", h.HandlePackagesList)
req := httptest.NewRequest("GET", "/api/packages", nil)
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("expected status 200, got %d", w.Code)
}
var resp PackagesListResponse
if err := json.NewDecoder(w.Body).Decode(&resp); err != nil {
t.Fatalf("failed to decode response: %v", err)
}
if len(resp.Results) < 2 {
t.Fatalf("expected at least 2 results, got %d", len(resp.Results))
}
if resp.SortBy != defaultSortBy {
t.Errorf("expected default sort by hits, got %q", resp.SortBy)
}
found := false
for _, pkg := range resp.Results {
if pkg.Name == "api-list-one" || pkg.Name == "api-list-two" {
found = true
break
}
}
if !found {
t.Error("expected seeded packages in results")
}
}
func TestHandlePackagesListAPI_InvalidSort(t *testing.T) {
logger := slog.New(slog.NewTextHandler(os.Stdout, nil))
svc := enrichment.New(logger)
dir := t.TempDir()
dbPath := filepath.Join(dir, "test.db")
db, err := database.Create(dbPath)
if err != nil {
t.Fatalf("Create failed: %v", err)
}
defer func() { _ = db.Close() }()
h := NewAPIHandler(svc, db)
r := chi.NewRouter()
r.Get("/api/packages", h.HandlePackagesList)
req := httptest.NewRequest("GET", "/api/packages?sort=invalid", nil)
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
if w.Code != http.StatusBadRequest {
t.Errorf("expected status 400 for invalid sort, got %d", w.Code)
}
}

View file

@ -1,7 +1,6 @@
package server package server
import ( import (
"bufio"
"encoding/json" "encoding/json"
"fmt" "fmt"
"io" "io"
@ -11,102 +10,20 @@ import (
"github.com/git-pkgs/archives" "github.com/git-pkgs/archives"
"github.com/git-pkgs/archives/diff" "github.com/git-pkgs/archives/diff"
"github.com/git-pkgs/magic"
"github.com/git-pkgs/proxy/internal/database" "github.com/git-pkgs/proxy/internal/database"
"github.com/git-pkgs/proxy/internal/handler"
"github.com/git-pkgs/purl" "github.com/git-pkgs/purl"
"github.com/go-chi/chi/v5" "github.com/go-chi/chi/v5"
) )
const ( // getStripPrefix returns the path prefix to strip for a given ecosystem.
contentTypePlainText = "text/plain; charset=utf-8" // npm packages wrap content in a "package/" directory.
browseSniffSize = 512 func getStripPrefix(ecosystem string) string {
) switch ecosystem {
case "npm":
// maxBrowseArchiveSize caps how much data openArchive will buffer for return "package/"
// prefix detection. Artifacts larger than this are rejected to prevent default:
// memory exhaustion from a single request.
const maxBrowseArchiveSize = 512 << 20 // 512 MB
// firstBrowsableArtifact returns the first cached artifact that can be opened as
// an archive, or nil if the version has none.
//
// A version's artifact list is not all archives: a PEP 658 core-metadata sidecar
// resolves to the same name and version as the distribution it describes, so it
// is cached under that version too. Sidecars are plain text, and because '-'
// sorts before '.' one can even precede the real distribution in the
// filename-ordered list, so selecting blindly would hand openArchive a file it
// cannot parse.
func firstBrowsableArtifact(artifacts []database.Artifact) *database.Artifact {
for i := range artifacts {
if artifacts[i].StoragePath.Valid && !isMetadataSidecar(artifacts[i].Filename) {
return &artifacts[i]
}
}
return nil
}
// isMetadataSidecar reports whether filename is a core-metadata sidecar rather
// than a distribution archive.
func isMetadataSidecar(filename string) bool {
return strings.HasSuffix(filename, handler.PyPIMetadataSuffix)
}
// detectSingleRootDir returns the single top-level directory name if all files
// in the archive live under one common directory (e.g. GitHub zipballs use
// "repo-hash/"). Returns "" if there's no single root or the archive is flat.
func detectSingleRootDir(reader archives.Reader) string {
files, err := reader.List()
if err != nil || len(files) == 0 {
return "" return ""
} }
var root string
for _, f := range files {
parts := strings.SplitN(f.Path, "/", 2) //nolint:mnd // split into dir + rest
if len(parts) == 0 {
continue
}
dir := parts[0]
if root == "" {
root = dir
} else if dir != root {
return ""
}
}
if root == "" {
return ""
}
return root + "/"
}
// openArchive opens a cached artifact as an archive reader, auto-detecting
// and stripping a single top-level directory prefix (like GitHub zipballs).
// For npm, the hardcoded "package/" prefix takes precedence.
func openArchive(filename string, content io.Reader, ecosystem string) (archives.Reader, error) { //nolint:ireturn // wraps multiple archive implementations
limited := io.LimitReader(content, maxBrowseArchiveSize+1)
data, err := io.ReadAll(limited)
if err != nil {
return nil, fmt.Errorf("reading artifact: %w", err)
}
if int64(len(data)) > maxBrowseArchiveSize {
return nil, fmt.Errorf("artifact too large for browsing (%d bytes)", len(data))
}
if ecosystem == "npm" {
return archives.OpenBytesWithPrefix(filename, data, "package/")
}
probe, err := archives.OpenBytes(filename, data)
if err != nil {
return nil, err
}
prefix := detectSingleRootDir(probe)
_ = probe.Close()
return archives.OpenBytesWithPrefix(filename, data, prefix)
} }
// BrowseListResponse contains the file listing for a directory in an archives. // BrowseListResponse contains the file listing for a directory in an archives.
@ -126,122 +43,36 @@ type BrowseFileInfo struct {
// handleBrowseList returns a list of files in a directory within an archived package version. // handleBrowseList returns a list of files in a directory within an archived package version.
// GET /api/browse/{ecosystem}/{name}/{version}?path=/some/dir // GET /api/browse/{ecosystem}/{name}/{version}?path=/some/dir
// @Summary List files inside a cached artifact func (s *Server) handleBrowseList(w http.ResponseWriter, r *http.Request) {
// @Description Lists files from the first cached artifact for a package version.
// @Tags browse
// @Produce json
// @Param ecosystem path string true "Ecosystem"
// @Param name path string true "Package name"
// @Param version path string true "Version"
// @Param path query string false "Directory path inside the archive"
// @Success 200 {object} BrowseListResponse
// @Failure 404 {object} ErrorResponse
// @Failure 500 {object} ErrorResponse
// @Router /ui/api/browse/{ecosystem}/{name}/{version} [get]
// handleBrowsePath dispatches /api/browse/{ecosystem}/* to the appropriate browse handler.
// It resolves namespaced package names by consulting the database.
//
// Supported paths:
//
// {name}/{version} -> browse list
// {name}/{version}/file/{path} -> browse file
func (s *Server) handleBrowsePath(w http.ResponseWriter, r *http.Request) {
ecosystem := chi.URLParam(r, "ecosystem") ecosystem := chi.URLParam(r, "ecosystem")
segments, err := packagePathSegments(r) name := chi.URLParam(r, "name")
if err != nil { version := chi.URLParam(r, "version")
badRequest(w, err.Error())
return
}
if ecosystem == "" || len(segments) < 2 {
badRequest(w, "ecosystem, name, and version required")
return
}
// Check for /file/ in the path for browse file requests.
fileIdx := -1
for i, seg := range segments {
if seg == "file" && i > 0 {
fileIdx = i
break
}
}
if fileIdx >= 0 {
// Everything before "file" is name+version, everything after is the file path.
nameVersionSegments := segments[:fileIdx]
filePath := strings.Join(segments[fileIdx+1:], "/")
name, rest := resolvePackageName(s.db, ecosystem, nameVersionSegments)
if name == "" && len(nameVersionSegments) >= 2 {
name = strings.Join(nameVersionSegments[:len(nameVersionSegments)-1], "/")
rest = nameVersionSegments[len(nameVersionSegments)-1:]
}
if len(rest) != 1 {
notFound(w, "not found")
return
}
s.browseFile(w, r, ecosystem, name, rest[0], filePath)
return
}
// No /file/ segment: this is a browse list.
name, rest := resolvePackageName(s.db, ecosystem, segments)
if name == "" && len(segments) >= 2 {
name = strings.Join(segments[:len(segments)-1], "/")
rest = segments[len(segments)-1:]
}
if len(rest) != 1 {
notFound(w, "not found")
return
}
s.browseList(w, r, ecosystem, name, rest[0])
}
// handleComparePath dispatches /api/compare/{ecosystem}/* to the compare handler.
// Supported paths: {name}/{fromVersion}/{toVersion}
func (s *Server) handleComparePath(w http.ResponseWriter, r *http.Request) {
ecosystem := chi.URLParam(r, "ecosystem")
segments, err := packagePathSegments(r)
if err != nil {
badRequest(w, err.Error())
return
}
if ecosystem == "" || len(segments) < 3 {
badRequest(w, "ecosystem, name, fromVersion, and toVersion required")
return
}
// The last two segments are fromVersion and toVersion.
// Everything before that is the package name.
name := strings.Join(segments[:len(segments)-2], "/")
fromVersion := segments[len(segments)-2]
toVersion := segments[len(segments)-1]
s.compareDiff(w, r, ecosystem, name, fromVersion, toVersion)
}
func (s *Server) browseList(w http.ResponseWriter, r *http.Request, ecosystem, name, version string) {
dirPath := r.URL.Query().Get("path") dirPath := r.URL.Query().Get("path")
// Get the artifact for this version // Get the artifact for this version
versionPURL := purl.MakePURLString(ecosystem, name, version) versionPURL := purl.MakePURLString(ecosystem, name, version)
artifacts, err := s.db.GetArtifactsByVersionPURL(versionPURL) artifacts, err := s.db.GetArtifactsByVersionPURL(versionPURL)
if err != nil { if err != nil {
notFound(w, "version not found") http.Error(w, "version not found", http.StatusNotFound)
return return
} }
if len(artifacts) == 0 { if len(artifacts) == 0 {
notFound(w, "no artifacts cached") http.Error(w, "no artifacts cached", http.StatusNotFound)
return return
} }
cachedArtifact := firstBrowsableArtifact(artifacts) // Find the first cached artifact
var cachedArtifact *database.Artifact
for i := range artifacts {
if artifacts[i].StoragePath.Valid {
cachedArtifact = &artifacts[i]
break
}
}
if cachedArtifact == nil { if cachedArtifact == nil {
notFound(w, "artifact not cached") http.Error(w, "artifact not cached", http.StatusNotFound)
return return
} }
@ -249,16 +80,17 @@ func (s *Server) browseList(w http.ResponseWriter, r *http.Request, ecosystem, n
artifactReader, err := s.storage.Open(r.Context(), cachedArtifact.StoragePath.String) artifactReader, err := s.storage.Open(r.Context(), cachedArtifact.StoragePath.String)
if err != nil { if err != nil {
s.logger.Error("failed to read artifact from storage", "error", err) s.logger.Error("failed to read artifact from storage", "error", err)
internalError(w, "failed to read artifact") http.Error(w, "failed to read artifact", http.StatusInternalServerError)
return return
} }
defer func() { _ = artifactReader.Close() }() defer func() { _ = artifactReader.Close() }()
// Open archive with auto-detected prefix stripping // Open archive with appropriate prefix stripping
archiveReader, err := openArchive(cachedArtifact.Filename, artifactReader, ecosystem) stripPrefix := getStripPrefix(ecosystem)
archiveReader, err := archives.OpenWithPrefix(cachedArtifact.Filename, artifactReader, stripPrefix)
if err != nil { if err != nil {
s.logger.Error("failed to open archive", "error", err, "filename", cachedArtifact.Filename) s.logger.Error("failed to open archive", "error", err, "filename", cachedArtifact.Filename)
internalError(w, "failed to open archive") http.Error(w, "failed to open archive", http.StatusInternalServerError)
return return
} }
defer func() { _ = archiveReader.Close() }() defer func() { _ = archiveReader.Close() }()
@ -267,7 +99,7 @@ func (s *Server) browseList(w http.ResponseWriter, r *http.Request, ecosystem, n
files, err := archiveReader.ListDir(dirPath) files, err := archiveReader.ListDir(dirPath)
if err != nil { if err != nil {
s.logger.Error("failed to list directory", "error", err, "path", dirPath) s.logger.Error("failed to list directory", "error", err, "path", dirPath)
internalError(w, "failed to list directory") http.Error(w, "failed to list directory", http.StatusInternalServerError)
return return
} }
@ -293,22 +125,15 @@ func (s *Server) browseList(w http.ResponseWriter, r *http.Request, ecosystem, n
// handleBrowseFile returns the contents of a specific file within an archived package version. // handleBrowseFile returns the contents of a specific file within an archived package version.
// GET /api/browse/{ecosystem}/{name}/{version}/file/{filepath...} // GET /api/browse/{ecosystem}/{name}/{version}/file/{filepath...}
// @Summary Fetch a file inside a cached artifact func (s *Server) handleBrowseFile(w http.ResponseWriter, r *http.Request) {
// @Description Streams a single file from the cached artifact. The file path may contain slashes. ecosystem := chi.URLParam(r, "ecosystem")
// @Tags browse name := chi.URLParam(r, "name")
// @Produce application/octet-stream version := chi.URLParam(r, "version")
// @Param ecosystem path string true "Ecosystem"
// @Param name path string true "Package name" // Get the wildcard path
// @Param version path string true "Version" filePath := chi.URLParam(r, "*")
// @Param filepath path string true "File path inside the archive"
// @Success 200 {file} file
// @Failure 400 {object} ErrorResponse
// @Failure 404 {object} ErrorResponse
// @Failure 500 {object} ErrorResponse
// @Router /ui/api/browse/{ecosystem}/{name}/{version}/file/{filepath} [get]
func (s *Server) browseFile(w http.ResponseWriter, r *http.Request, ecosystem, name, version, filePath string) {
if filePath == "" { if filePath == "" {
badRequest(w, "file path required") http.Error(w, "file path required", http.StatusBadRequest)
return return
} }
@ -316,19 +141,26 @@ func (s *Server) browseFile(w http.ResponseWriter, r *http.Request, ecosystem, n
versionPURL := purl.MakePURLString(ecosystem, name, version) versionPURL := purl.MakePURLString(ecosystem, name, version)
artifacts, err := s.db.GetArtifactsByVersionPURL(versionPURL) artifacts, err := s.db.GetArtifactsByVersionPURL(versionPURL)
if err != nil { if err != nil {
notFound(w, "version not found") http.Error(w, "version not found", http.StatusNotFound)
return return
} }
if len(artifacts) == 0 { if len(artifacts) == 0 {
notFound(w, "no artifacts cached") http.Error(w, "no artifacts cached", http.StatusNotFound)
return return
} }
cachedArtifact := firstBrowsableArtifact(artifacts) // Find the first cached artifact
var cachedArtifact *database.Artifact
for i := range artifacts {
if artifacts[i].StoragePath.Valid {
cachedArtifact = &artifacts[i]
break
}
}
if cachedArtifact == nil { if cachedArtifact == nil {
notFound(w, "artifact not cached") http.Error(w, "artifact not cached", http.StatusNotFound)
return return
} }
@ -336,16 +168,17 @@ func (s *Server) browseFile(w http.ResponseWriter, r *http.Request, ecosystem, n
artifactReader, err := s.storage.Open(r.Context(), cachedArtifact.StoragePath.String) artifactReader, err := s.storage.Open(r.Context(), cachedArtifact.StoragePath.String)
if err != nil { if err != nil {
s.logger.Error("failed to read artifact from storage", "error", err) s.logger.Error("failed to read artifact from storage", "error", err)
internalError(w, "failed to read artifact") http.Error(w, "failed to read artifact", http.StatusInternalServerError)
return return
} }
defer func() { _ = artifactReader.Close() }() defer func() { _ = artifactReader.Close() }()
// Open archive with auto-detected prefix stripping // Open archive with appropriate prefix stripping
archiveReader, err := openArchive(cachedArtifact.Filename, artifactReader, ecosystem) stripPrefix := getStripPrefix(ecosystem)
archiveReader, err := archives.OpenWithPrefix(cachedArtifact.Filename, artifactReader, stripPrefix)
if err != nil { if err != nil {
s.logger.Error("failed to open archive", "error", err, "filename", cachedArtifact.Filename) s.logger.Error("failed to open archive", "error", err, "filename", cachedArtifact.Filename)
internalError(w, "failed to open archive") http.Error(w, "failed to open archive", http.StatusInternalServerError)
return return
} }
defer func() { _ = archiveReader.Close() }() defer func() { _ = archiveReader.Close() }()
@ -354,128 +187,103 @@ func (s *Server) browseFile(w http.ResponseWriter, r *http.Request, ecosystem, n
fileReader, err := archiveReader.Extract(filePath) fileReader, err := archiveReader.Extract(filePath)
if err != nil { if err != nil {
if strings.Contains(err.Error(), "not found") { if strings.Contains(err.Error(), "not found") {
notFound(w, "file not found") http.Error(w, "file not found", http.StatusNotFound)
return return
} }
s.logger.Error("failed to extract file", "error", err, "path", filePath) s.logger.Error("failed to extract file", "error", err, "path", filePath)
internalError(w, "failed to extract file") http.Error(w, "failed to extract file", http.StatusInternalServerError)
return return
} }
defer func() { _ = fileReader.Close() }() defer func() { _ = fileReader.Close() }()
contentType, knownPath := detectContentTypeFromPath(filePath) // Set content type based on file extension
var content io.Reader = fileReader contentType := detectContentType(filePath)
if !knownPath {
bufferedFile := bufio.NewReaderSize(fileReader, browseSniffSize)
prefix, _ := bufferedFile.Peek(browseSniffSize)
contentType = detectContentTypeFromPrefix(prefix)
content = bufferedFile
}
w.Header().Set("Content-Type", contentType) w.Header().Set("Content-Type", contentType)
w.Header().Set("Content-Security-Policy", "sandbox")
w.Header().Set("X-Content-Type-Options", "nosniff")
// Set filename for download
_, filename := path.Split(filePath) _, filename := path.Split(filePath)
w.Header().Set("Content-Disposition", fmt.Sprintf("inline; filename=%q", filename)) w.Header().Set("Content-Disposition", fmt.Sprintf("inline; filename=%q", filename))
// Stream the file // Stream the file
_, _ = io.Copy(w, content) _, _ = io.Copy(w, fileReader)
} }
func detectContentTypeFromPath(filename string) (string, bool) { // detectContentType returns an appropriate content type based on file extension.
func detectContentType(filename string) string {
ext := strings.ToLower(path.Ext(filename)) ext := strings.ToLower(path.Ext(filename))
switch ext { switch ext {
// Text formats // Text formats
case ".txt", ".md", ".markdown": case ".txt", ".md", ".markdown":
return contentTypePlainText, true return "text/plain; charset=utf-8"
case ".html", ".htm", ".xhtml": case ".html", ".htm":
return contentTypePlainText, true return "text/html; charset=utf-8"
case ".css": case ".css":
return "text/css; charset=utf-8", true return "text/css; charset=utf-8"
case ".js", ".mjs": case ".js", ".mjs":
return "application/javascript; charset=utf-8", true return "application/javascript; charset=utf-8"
case ".json": case ".json":
return "application/json; charset=utf-8", true return "application/json; charset=utf-8"
case ".xml": case ".xml":
return "application/xml; charset=utf-8", true return "application/xml; charset=utf-8"
case ".yaml", ".yml": case ".yaml", ".yml":
return "text/yaml; charset=utf-8", true return "text/yaml; charset=utf-8"
case ".toml": case ".toml":
return "text/toml; charset=utf-8", true return "text/toml; charset=utf-8"
// Programming languages // Programming languages
case ".go": case ".go":
return "text/x-go; charset=utf-8", true return "text/x-go; charset=utf-8"
case ".rs": case ".rs":
return "text/x-rust; charset=utf-8", true return "text/x-rust; charset=utf-8"
case ".py": case ".py":
return "text/x-python; charset=utf-8", true return "text/x-python; charset=utf-8"
case ".rb": case ".rb":
return "text/x-ruby; charset=utf-8", true return "text/x-ruby; charset=utf-8"
case ".java": case ".java":
return "text/x-java; charset=utf-8", true return "text/x-java; charset=utf-8"
case ".c", ".h": case ".c", ".h":
return "text/x-c; charset=utf-8", true return "text/x-c; charset=utf-8"
case ".cpp", ".cc", ".cxx", ".hpp": case ".cpp", ".cc", ".cxx", ".hpp":
return "text/x-c++; charset=utf-8", true return "text/x-c++; charset=utf-8"
case ".ts": case ".ts":
return "text/typescript; charset=utf-8", true return "text/typescript; charset=utf-8"
case ".tsx": case ".tsx":
return "text/tsx; charset=utf-8", true return "text/tsx; charset=utf-8"
case ".jsx": case ".jsx":
return "text/jsx; charset=utf-8", true return "text/jsx; charset=utf-8"
case ".php": case ".php":
return "text/x-php; charset=utf-8", true return "text/x-php; charset=utf-8"
// Config files // Config files
case ".conf", ".config", ".ini": case ".conf", ".config", ".ini":
return contentTypePlainText, true return "text/plain; charset=utf-8"
case ".sh", ".bash": case ".sh", ".bash":
return "text/x-shellscript; charset=utf-8", true return "text/x-shellscript; charset=utf-8"
case ".dockerfile": case ".dockerfile":
return "text/x-dockerfile; charset=utf-8", true return "text/x-dockerfile; charset=utf-8"
// Images // Images
case ".png": case ".png":
return "image/png", true return "image/png"
case ".jpg", ".jpeg": case ".jpg", ".jpeg":
return "image/jpeg", true return "image/jpeg"
case ".gif": case ".gif":
return "image/gif", true return "image/gif"
case ".svg": case ".svg":
return contentTypePlainText, true return "image/svg+xml"
case ".ico": case ".ico":
return "image/x-icon", true return "image/x-icon"
// Archives // Archives
case ".zip", ".tar", ".gz", ".bz2", ".xz": case ".zip", ".tar", ".gz", ".bz2", ".xz":
return "application/octet-stream", true return "application/octet-stream"
default: default:
// Try to detect if it looks like text
if isLikelyText(filename) { if isLikelyText(filename) {
return contentTypePlainText, true return "text/plain; charset=utf-8"
} }
return "", false
}
}
func detectContentTypeFromPrefix(prefix []byte) string {
result := magic.DetectPrefix(prefix)
if result.Kind == magic.KindText {
return contentTypePlainText
}
switch result.Format {
case "png":
return "image/png"
case "jpeg":
return "image/jpeg"
case "gif":
return "image/gif"
case "pdf":
return "application/pdf"
default:
return "application/octet-stream" return "application/octet-stream"
} }
} }
@ -504,57 +312,72 @@ func isLikelyText(filename string) bool {
} }
// BrowseSourceData contains data for the browse source page. // BrowseSourceData contains data for the browse source page.
//
// Version is the decoded version, for display. EscapedVersion is the same value
// escaped as a single URL path segment and is what the links and the browse API
// calls must use; see database.Version.EscapedVersion.
type BrowseSourceData struct { type BrowseSourceData struct {
Layout Ecosystem string
Ecosystem string PackageName string
PackageName string Version string
Version string
EscapedVersion string
} }
// handleBrowseSource is now showBrowseSource in server.go, dispatched via handlePackagePath. // handleBrowseSource renders the source code browser UI.
// GET /package/{ecosystem}/{name}/{version}/browse
func (s *Server) handleBrowseSource(w http.ResponseWriter, r *http.Request) {
ecosystem := chi.URLParam(r, "ecosystem")
name := chi.URLParam(r, "name")
version := chi.URLParam(r, "version")
data := BrowseSourceData{
Ecosystem: ecosystem,
PackageName: name,
Version: version,
}
if err := s.templates.Render(w, "browse_source", data); err != nil {
s.logger.Error("failed to render browse source page", "error", err)
http.Error(w, "internal server error", http.StatusInternalServerError)
}
}
// handleCompareDiff compares two versions and returns a diff. // handleCompareDiff compares two versions and returns a diff.
// GET /api/compare/{ecosystem}/{name}/{fromVersion}/{toVersion} // GET /api/compare/{ecosystem}/{name}/{fromVersion}/{toVersion}
// @Summary Compare two cached versions func (s *Server) handleCompareDiff(w http.ResponseWriter, r *http.Request) {
// @Description Returns a structured diff for two cached versions. ecosystem := chi.URLParam(r, "ecosystem")
// @Tags browse name := chi.URLParam(r, "name")
// @Produce json fromVersion := chi.URLParam(r, "fromVersion")
// @Param ecosystem path string true "Ecosystem" toVersion := chi.URLParam(r, "toVersion")
// @Param name path string true "Package name"
// @Param fromVersion path string true "From version"
// @Param toVersion path string true "To version"
// @Success 200 {object} map[string]any
// @Failure 404 {object} ErrorResponse
// @Failure 500 {object} ErrorResponse
// @Router /ui/api/compare/{ecosystem}/{name}/{fromVersion}/{toVersion} [get]
func (s *Server) compareDiff(w http.ResponseWriter, r *http.Request, ecosystem, name, fromVersion, toVersion string) {
// Get artifacts for both versions // Get artifacts for both versions
fromPURL := purl.MakePURLString(ecosystem, name, fromVersion) fromPURL := purl.MakePURLString(ecosystem, name, fromVersion)
toPURL := purl.MakePURLString(ecosystem, name, toVersion) toPURL := purl.MakePURLString(ecosystem, name, toVersion)
fromArtifacts, err := s.db.GetArtifactsByVersionPURL(fromPURL) fromArtifacts, err := s.db.GetArtifactsByVersionPURL(fromPURL)
if err != nil || len(fromArtifacts) == 0 { if err != nil || len(fromArtifacts) == 0 {
notFound(w, "from version not found or not cached") http.Error(w, "from version not found or not cached", http.StatusNotFound)
return return
} }
toArtifacts, err := s.db.GetArtifactsByVersionPURL(toPURL) toArtifacts, err := s.db.GetArtifactsByVersionPURL(toPURL)
if err != nil || len(toArtifacts) == 0 { if err != nil || len(toArtifacts) == 0 {
notFound(w, "to version not found or not cached") http.Error(w, "to version not found or not cached", http.StatusNotFound)
return return
} }
// Find cached artifacts // Find cached artifacts
fromArtifact := firstBrowsableArtifact(fromArtifacts) var fromArtifact, toArtifact *database.Artifact
toArtifact := firstBrowsableArtifact(toArtifacts) for i := range fromArtifacts {
if fromArtifacts[i].StoragePath.Valid {
fromArtifact = &fromArtifacts[i]
break
}
}
for i := range toArtifacts {
if toArtifacts[i].StoragePath.Valid {
toArtifact = &toArtifacts[i]
break
}
}
if fromArtifact == nil || toArtifact == nil { if fromArtifact == nil || toArtifact == nil {
notFound(w, "one or both versions not cached") http.Error(w, "one or both versions not cached", http.StatusNotFound)
return return
} }
@ -562,7 +385,7 @@ func (s *Server) compareDiff(w http.ResponseWriter, r *http.Request, ecosystem,
fromReader, err := s.storage.Open(r.Context(), fromArtifact.StoragePath.String) fromReader, err := s.storage.Open(r.Context(), fromArtifact.StoragePath.String)
if err != nil { if err != nil {
s.logger.Error("failed to open from artifact", "error", err) s.logger.Error("failed to open from artifact", "error", err)
internalError(w, "failed to read from version") http.Error(w, "failed to read from version", http.StatusInternalServerError)
return return
} }
defer func() { _ = fromReader.Close() }() defer func() { _ = fromReader.Close() }()
@ -570,23 +393,25 @@ func (s *Server) compareDiff(w http.ResponseWriter, r *http.Request, ecosystem,
toReader, err := s.storage.Open(r.Context(), toArtifact.StoragePath.String) toReader, err := s.storage.Open(r.Context(), toArtifact.StoragePath.String)
if err != nil { if err != nil {
s.logger.Error("failed to open to artifact", "error", err) s.logger.Error("failed to open to artifact", "error", err)
internalError(w, "failed to read to version") http.Error(w, "failed to read to version", http.StatusInternalServerError)
return return
} }
defer func() { _ = toReader.Close() }() defer func() { _ = toReader.Close() }()
fromArchive, err := openArchive(fromArtifact.Filename, fromReader, ecosystem) stripPrefix := getStripPrefix(ecosystem)
fromArchive, err := archives.OpenWithPrefix(fromArtifact.Filename, fromReader, stripPrefix)
if err != nil { if err != nil {
s.logger.Error("failed to open from archive", "error", err) s.logger.Error("failed to open from archive", "error", err)
internalError(w, "failed to open from archive") http.Error(w, "failed to open from archive", http.StatusInternalServerError)
return return
} }
defer func() { _ = fromArchive.Close() }() defer func() { _ = fromArchive.Close() }()
toArchive, err := openArchive(toArtifact.Filename, toReader, ecosystem) toArchive, err := archives.OpenWithPrefix(toArtifact.Filename, toReader, stripPrefix)
if err != nil { if err != nil {
s.logger.Error("failed to open to archive", "error", err) s.logger.Error("failed to open to archive", "error", err)
internalError(w, "failed to open to archive") http.Error(w, "failed to open to archive", http.StatusInternalServerError)
return return
} }
defer func() { _ = toArchive.Close() }() defer func() { _ = toArchive.Close() }()
@ -595,7 +420,7 @@ func (s *Server) compareDiff(w http.ResponseWriter, r *http.Request, ecosystem,
result, err := diff.Compare(fromArchive, toArchive) result, err := diff.Compare(fromArchive, toArchive)
if err != nil { if err != nil {
s.logger.Error("failed to generate diff", "error", err) s.logger.Error("failed to generate diff", "error", err)
internalError(w, "failed to generate diff") http.Error(w, "failed to generate diff", http.StatusInternalServerError)
return return
} }
@ -604,17 +429,40 @@ func (s *Server) compareDiff(w http.ResponseWriter, r *http.Request, ecosystem,
} }
// ComparePageData contains data for the version comparison page. // ComparePageData contains data for the version comparison page.
//
// FromVersion and ToVersion are decoded, for display; the Escaped variants are
// the path-segment form used to build the compare API URL.
type ComparePageData struct { type ComparePageData struct {
Layout Ecosystem string
Ecosystem string PackageName string
PackageName string FromVersion string
FromVersion string ToVersion string
ToVersion string
EscapedFromVersion string
EscapedToVersion string
} }
// handleComparePage is now showComparePage in server.go, dispatched via handlePackagePath. // handleComparePage renders the version comparison UI.
// GET /package/{ecosystem}/{name}/compare/{versions}
// where {versions} is in format "fromVersion...toVersion"
func (s *Server) handleComparePage(w http.ResponseWriter, r *http.Request) {
ecosystem := chi.URLParam(r, "ecosystem")
name := chi.URLParam(r, "name")
versions := chi.URLParam(r, "versions")
// Parse versions (format: "1.0.0...2.0.0")
parts := strings.Split(versions, "...")
if len(parts) != 2 {
http.Error(w, "invalid version format, use: version1...version2", http.StatusBadRequest)
return
}
fromVersion := parts[0]
toVersion := parts[1]
data := ComparePageData{
Ecosystem: ecosystem,
PackageName: name,
FromVersion: fromVersion,
ToVersion: toVersion,
}
if err := s.templates.Render(w, "compare_versions", data); err != nil {
s.logger.Error("failed to render compare page", "error", err)
http.Error(w, "internal server error", http.StatusInternalServerError)
}
}

Some files were not shown because too many files have changed in this diff Show more