Compare commits

...
Sign in to create a new pull request.
Author SHA1 Message Date
c655399a07 Apply 'go fmt' as suggested in CONTRIBUTING.md. 2026-04-18 07:43:22 -04:00
Andrew Nesbitt
e3cc5516b5
Merge pull request #85 from git-pkgs/homebrew-readme
Add Homebrew install instructions
2026-04-13 11:07:59 +01:00
Andrew Nesbitt
50772d8947
Add Homebrew install instructions 2026-04-13 11:03:59 +01:00
Andrew Nesbitt
2816ff2414
Add LICENSE 2026-04-13 10:36:34 +01:00
Andrew Nesbitt
d3d11445c6
Merge pull request #84 from git-pkgs/cosign-signing
Sign release checksums with cosign keyless
2026-04-13 09:22:29 +01:00
Andrew Nesbitt
0c02455dc9
Sign release checksums with cosign keyless 2026-04-13 09:14:33 +01:00
Andrew Nesbitt
9849ac9f16
Merge pull request #40 from git-pkgs/mirror-feature
Add mirror command and API for selective package mirroring
2026-04-13 09:07:43 +01:00
Andrew Nesbitt
7346008aa5
Add metadata TTL and stale-while-revalidate support
Cached metadata is now served directly within a configurable TTL window
(default 5m) without contacting upstream, reducing latency and upstream
load. When upstream is unreachable and the cache is past its TTL, stale
content is served with a Warning: 110 header per RFC 7234.

New config: `metadata_ttl` (YAML) / `PROXY_METADATA_TTL` (env).
Set to "0" to always revalidate with upstream.
2026-04-13 09:01:05 +01:00
Andrew Nesbitt
c01f0a5c05
Fix metadata caching, 404 propagation, mirror progress, and registry stubs
- ProxyCached now stores upstream Last-Modified in the cache and uses it
  (along with ETag) for conditional request handling, returning 304 when
  client validators match. Adds Content-Length to cached responses.

- Handlers calling FetchOrCacheMetadata (pypi, composer, pub, nuget) now
  check for ErrUpstreamNotFound and return 404 instead of 502, matching
  the existing npm and cargo behavior.

- Mirror jobs report live progress via a periodic callback while running,
  so API polls return real counts instead of zeroed progress.

- Registry mirroring removed from CLI flags, API acceptance, README, and
  docs since every enumerator was a stub returning "not yet implemented".

- Added tests for the conditional metadata path (ETag/If-None-Match,
  Last-Modified/If-Modified-Since, 304 responses, header omission).
2026-04-13 09:01:05 +01:00
Andrew Nesbitt
47681066b5
Fix review issues in mirror feature
- Fix race where runJob could overwrite canceled state set by Cancel()
- Fix Debian ecosystem name inconsistency ("deb" -> "debian")
- Stream metadata responses when caching is disabled to avoid buffering
- Add metadata_cache table to initial schema strings for consistency
- Gate mirror API behind mirror_api config flag (disabled by default)
- Fix goconst lint in metadata_cache_test.go
2026-04-13 09:01:04 +01:00
Andrew Nesbitt
02738651ab
Fix concurrency, resource, and reliability issues in mirror
- Wire job contexts to server shutdown context so jobs are canceled on
  server stop instead of running indefinitely
- Defer context cancel in runJob so completed jobs don't leak contexts
- Cap error accumulation in progressTracker to 1000 entries to prevent
  OOM on large mirror operations with many failures
- Add panic recovery in errgroup workers to prevent process crashes
- Use defer for db.Close() in runMirror CLI to ensure cleanup on all
  error paths
2026-04-13 09:01:04 +01:00
Andrew Nesbitt
d62c42b8d7
Add mirror command and API for selective package mirroring
Add a `proxy mirror` CLI command and `/api/mirror` API endpoints that
pre-populate the cache from various input sources: individual PURLs,
SBOM files (CycloneDX and SPDX), or full registry enumeration.

The mirror reuses the existing handler.Proxy.GetOrFetchArtifact()
pipeline so cached artifacts are identical to those fetched on demand.
A bounded worker pool controls download parallelism.

Metadata caching is opt-in via `cache_metadata: true` in config (or
PROXY_CACHE_METADATA=true). The mirror command always enables it. When
enabled, upstream metadata responses are stored for offline fallback
with ETag-based conditional revalidation.

New internal/mirror package with Source interface, PURLSource,
SBOMSource, RegistrySource, and async JobStore. New metadata_cache
database table for offline metadata serving.
2026-04-13 09:01:04 +01:00
Andrew Nesbitt
7985a28839
Merge pull request #79 from git-pkgs/fix-metadata-size-limit
Fix silent truncation of large npm metadata responses
2026-04-13 08:47:31 +01:00
Andrew Nesbitt
773fe55bd9
Merge pull request #80 from git-pkgs/dependabot/go_modules/github.com/git-pkgs/vulns-0.1.4
Bump github.com/git-pkgs/vulns from 0.1.3 to 0.1.4
2026-04-10 15:42:53 +01:00
Andrew Nesbitt
d919d9ce3e
Merge pull request #82 from git-pkgs/dependabot/go_modules/modernc.org/sqlite-1.48.0
Bump modernc.org/sqlite from 1.47.0 to 1.48.0
2026-04-10 10:54:00 +01:00
dependabot[bot]
73d78c28fb
Bump github.com/git-pkgs/vulns from 0.1.3 to 0.1.4
Bumps [github.com/git-pkgs/vulns](https://github.com/git-pkgs/vulns) from 0.1.3 to 0.1.4.
- [Commits](https://github.com/git-pkgs/vulns/compare/v0.1.3...v0.1.4)

---
updated-dependencies:
- dependency-name: github.com/git-pkgs/vulns
  dependency-version: 0.1.4
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-04-10 09:53:57 +00:00
Andrew Nesbitt
7d0ac94c6c
Merge pull request #81 from git-pkgs/dependabot/go_modules/github.com/git-pkgs/enrichment-0.2.2
Bump github.com/git-pkgs/enrichment from 0.2.1 to 0.2.2
2026-04-10 10:53:21 +01:00
Andrew Nesbitt
5c4f6f3b85
Merge pull request #83 from git-pkgs/dependabot/go_modules/github.com/lib/pq-1.12.2
Bump github.com/lib/pq from 1.12.0 to 1.12.2
2026-04-10 10:52:37 +01:00
dependabot[bot]
497afdf317
Bump github.com/lib/pq from 1.12.0 to 1.12.2
Bumps [github.com/lib/pq](https://github.com/lib/pq) from 1.12.0 to 1.12.2.
- [Release notes](https://github.com/lib/pq/releases)
- [Changelog](https://github.com/lib/pq/blob/master/CHANGELOG.md)
- [Commits](https://github.com/lib/pq/compare/v1.12.0...v1.12.2)

---
updated-dependencies:
- dependency-name: github.com/lib/pq
  dependency-version: 1.12.2
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-04-09 15:24:54 +00:00
dependabot[bot]
55db8f94fc
Bump modernc.org/sqlite from 1.47.0 to 1.48.0
Bumps [modernc.org/sqlite](https://gitlab.com/cznic/sqlite) from 1.47.0 to 1.48.0.
- [Changelog](https://gitlab.com/cznic/sqlite/blob/master/CHANGELOG.md)
- [Commits](https://gitlab.com/cznic/sqlite/compare/v1.47.0...v1.48.0)

---
updated-dependencies:
- dependency-name: modernc.org/sqlite
  dependency-version: 1.48.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-04-09 15:24:50 +00:00
dependabot[bot]
d64fcb5b98
Bump github.com/git-pkgs/enrichment from 0.2.1 to 0.2.2
Bumps [github.com/git-pkgs/enrichment](https://github.com/git-pkgs/enrichment) from 0.2.1 to 0.2.2.
- [Commits](https://github.com/git-pkgs/enrichment/compare/v0.2.1...v0.2.2)

---
updated-dependencies:
- dependency-name: github.com/git-pkgs/enrichment
  dependency-version: 0.2.2
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-04-09 15:24:42 +00:00
Andrew Nesbitt
01b4e7210d
Use abbreviated npm metadata when cooldown is disabled
Request application/vnd.npm.install-v1+json from the npm registry
when cooldown filtering is not enabled. This format strips READMEs
and other bulk data, reducing drizzle-orm metadata from 92MB to 4MB.

Fall back to full metadata when cooldown is enabled since the
abbreviated format lacks the time map needed for publish-date filtering.
2026-04-08 16:12:43 +01:00
Andrew Nesbitt
8b762ffb39
Fix silent truncation of large npm metadata responses
ReadMetadata used io.LimitReader which silently truncated responses at
the size limit. For packages like drizzle-orm (~92MB metadata), this
produced invalid JSON that was served to clients.

Now returns ErrMetadataTooLarge when the limit is exceeded, and bumps
the limit from 50MB to 100MB.

Fixes #78
2026-04-08 16:02:30 +01:00
Andrew Nesbitt
94f4a7dfa6
Merge pull request #77 from kpfleming/sort-ecosystems-for-ui
Sort the ecosystems list for presentation in the UI
2026-04-07 08:45:52 +01:00
a947a7546a Sort the ecosystems list for presentation in the UI
In the page footer and the 'select' list on the packages page, the
list of ecosystems should be sorted in a predictable order.
2026-04-06 18:06:16 -04:00
Andrew Nesbitt
e1d2331ff0
Merge pull request #71 from git-pkgs/fix-composer-dist-urls
Fix composer dist URL rewriting and browse source
2026-04-06 19:26:16 +01:00
Andrew Nesbitt
e36a92433e
Clean up review feedback: use path.Ext for extension checks, remove dead getStripPrefix, add openArchive tests 2026-04-06 19:06:48 +01:00
Andrew Nesbitt
941ed51f76
Auto-detect and strip single top-level directory prefix when browsing archives
GitHub zipballs wrap all files in a repo-hash/ directory. Instead of
hardcoding prefixes per ecosystem, open the archive once to check if all
files share a single root directory and strip it automatically. The npm
package/ prefix is still handled as a special case.
2026-04-06 17:14:15 +01:00
Andrew Nesbitt
b68184cbab
Fix composer dist URL rewriting and browse source for extensionless filenames
GitHub zipball URLs end in a bare commit hash with no file extension.
rewriteDistURL now appends .zip when the filename has no extension and
the dist type is zip. expandMinifiedVersions deep copies inherited
values so in-place URL rewriting no longer corrupts shared references.
browse.go infers .zip for extensionless filenames so existing cached
artifacts can still be opened.
2026-04-06 17:07:20 +01:00
Andrew Nesbitt
bcbb883d1b
Add failing tests for composer dist URL and shared reference bugs
GitHub zipball URLs produce filenames without .zip extension, breaking
browse source. Minified version expansion shares nested map references,
causing dist URL corruption when versions inherit unchanged dist fields.
2026-04-06 17:07:20 +01:00
Andrew Nesbitt
33d99e337b
Merge pull request #72 from git-pkgs/bump-archives-v0.2.2
Bump archives to v0.2.2
2026-04-06 17:06:58 +01:00
Andrew Nesbitt
81f505757f
Bump archives to v0.2.2
Fixes duplicate directory entries in browse source for archives with
explicit directory entries (e.g. GitHub zipballs).
2026-04-06 17:00:50 +01:00
Andrew Nesbitt
7a758b9450
Remove redundant cooldown ecosystem list from README
The supported registries table already shows which ecosystems have
cooldown support. The inline list kept getting out of sync.
2026-04-06 13:27:05 +01:00
Andrew Nesbitt
3bccc01776
Merge pull request #70 from git-pkgs/add-hex-cooldown
Add cooldown support for Hex
2026-04-06 13:21:20 +01:00
Andrew Nesbitt
43a164ed72
Add cooldown support for Hex
Decode the Hex registry protobuf format, filter releases by fetching
timestamps from the Hex HTTP API (hex.pm/api/packages/{name}), and
re-encode without the original signature.

The protobuf handling uses protowire for low-level encoding/decoding
of the Signed wrapper, Package, and Release messages. Timestamps come
from the inserted_at field in the JSON API response.

Since the proxy re-encodes the payload without the original signature,
users need to disable registry signature verification.
2026-04-06 13:18:57 +01:00
Andrew Nesbitt
9708fe31a8
Merge pull request #69 from git-pkgs/add-rubygems-cooldown
Add cooldown support for RubyGems
2026-04-06 13:18:43 +01:00
Andrew Nesbitt
cb9bbbc385
Add cooldown support for RubyGems
Filter versions from the compact index (/info/{name}) by fetching
timestamps from the versions API (/api/v1/versions/{name}.json).
Both requests run concurrently to minimize latency. If the versions
API is unavailable, the compact index is proxied unfiltered.

Handles platform-specific versions (e.g. 1.0.0-java) by matching
the compact index format.
2026-04-06 13:16:26 +01:00
Andrew Nesbitt
75ff85f2f0
Add cooldown support for Conda (#68)
* Add cooldown support for Conda

Filter entries from Conda repodata.json based on the timestamp field
(milliseconds since epoch). Filters both packages and packages.conda
sections. When cooldown is disabled, repodata requests are proxied
directly without parsing.

* Update README table to mark Conda cooldown support
2026-04-06 13:16:00 +01:00
Andrew Nesbitt
70fe686953
Add cooldown support for NuGet (#67)
* Add cooldown support for NuGet

Filter versions from NuGet registration pages based on the
catalogEntry.published timestamp. Handles both RFC3339 and NuGet's
fractional-second timestamp formats. When cooldown is disabled,
registration requests are proxied directly without parsing.

* Update README table to mark NuGet cooldown support
2026-04-06 13:12:18 +01:00
Andrew Nesbitt
24d5e77443
Fix cross-device link error when running in Docker with volumes (#66)
`fileblob` creates temp files in `os.TempDir()` (`/tmp`) by default,
then uses `os.Rename` to move them to the final path. When the storage
directory is on a different filesystem (e.g. a Docker volume mount at
`/data`), the rename fails with "invalid cross-device link".

Set `no_tmp_dir=true` on file:// bucket URLs so fileblob creates temp
files next to the final destination instead.

Fixes #65
2026-04-06 13:07:31 +01:00
Andrew Nesbitt
15c133f1fa
Fix Composer minified metadata expansion and namespaced package routing (#63)
* Fix Composer minified metadata expansion and namespaced package routing

Packagist serves metadata in a minified format where only the first version
entry has all fields and subsequent entries inherit from the previous one.
The proxy was passing this through without expanding it, which meant cooldown
filtering could break the inheritance chain (losing fields like `name`) and
`~dev` sentinel markers were silently dropped.

The proxy now expands the minified format before filtering and rewriting,
ensuring every version entry is self-contained.

Web UI and API routes used single-segment chi URL params for package names,
which broke for Composer's `vendor/name` format. `/package/composer/monolog/monolog`
would match the version show route instead of the package show route.

All `/package/` and related API routes now use wildcard paths with a
`resolvePackageName` helper that tries increasingly longer path prefixes as
package names via DB lookup, correctly handling namespaced packages across
all endpoints (show, version, browse, compare, vulns).

Fixes #61, fixes #62

* Add namespaced package routing tests for all affected ecosystems

Verifies the wildcard routing handles slashes in package names for
npm (@babel/core), Go modules (github.com/stretchr/testify),
OCI images (library/nginx), Conda (conda-forge/numpy), and
Conan (zlib/1.2.13@demo/stable).

* Regenerate swagger docs after route refactor

The swagger annotations for the old per-endpoint handlers were removed
during the wildcard routing refactor. Regenerate to match current state.
2026-04-06 13:07:02 +01:00
Andrew Nesbitt
e45706d808
Track applied migrations to skip column checks on startup (#60)
* Track applied migrations to skip column checks on startup

Add a migrations table that records which migrations have been applied.
On boot, load the set of applied names in one query and only run new ones.
A fully migrated database now does 1 query instead of ~12 HasColumn/HasTable
checks.

Fresh databases created via CreateSchema record all migrations as already
applied. Old databases get the migrations table on first MigrateSchema call
and each migration is recorded after it runs.

Closes #54

* Add benchmark for MigrateSchema on fully migrated database

* Optimize MigrateSchema to single query for fully migrated databases

Skip HasTable/HasColumn checks when the migrations table already exists.
A fully migrated database now does one SELECT instead of ~12 individual
column and table checks.

* Add migration docs and link from architecture

* Add test for upgrade from fully migrated database without migrations table
2026-04-06 13:06:45 +01:00
Andrew Nesbitt
34009bad98
Lazy-load HTML templates behind sync.Once (#59)
Templates are parsed on first Render call instead of at server startup.
API-only traffic never pays the ~780µs parsing cost.

Closes #53
2026-04-06 13:06:25 +01:00
Kevin P. Fleming
ec9c437498
Correct ecosystem name in UI for Go (golang). (#64) 2026-04-05 16:20:57 +01:00
72 changed files with 7171 additions and 1384 deletions

View file

@ -7,6 +7,7 @@ on:
permissions: permissions:
contents: write contents: write
id-token: write
jobs: jobs:
release: release:
@ -18,6 +19,8 @@ jobs:
fetch-depth: 0 fetch-depth: 0
persist-credentials: false persist-credentials: false
- uses: sigstore/cosign-installer@cad07c2e89fa2edd6e2d7bab4c1aa38e53f76003 # v4.1.1
- name: Set up Go - name: Set up Go
uses: actions/setup-go@4a3601121dd01d1626a1e23e37211e3254c1c06c # v6.4.0 uses: actions/setup-go@4a3601121dd01d1626a1e23e37211e3254c1c06c # v6.4.0
with: with:

View file

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

232
LICENSE Normal file
View file

@ -0,0 +1,232 @@
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>.

View file

@ -18,9 +18,7 @@ cooldown:
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. 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. 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.
Currently works with npm, PyPI, pub.dev, Composer, and Cargo, which all include publish timestamps in their metadata. See [docs/configuration.md](docs/configuration.md) for the full config reference.
## Supported Registries ## Supported Registries
@ -28,16 +26,16 @@ Currently works with npm, PyPI, pub.dev, Composer, and Cargo, which all include
|----------|-------------------|:--------:|:---------:| |----------|-------------------|:--------:|:---------:|
| npm | JavaScript | Yes | ✓ | | npm | JavaScript | Yes | ✓ |
| Cargo | Rust | Yes | ✓ | | Cargo | Rust | Yes | ✓ |
| RubyGems | Ruby | | ✓ | | RubyGems | Ruby | Yes | ✓ |
| Go proxy | Go | | ✓ | | Go proxy | Go | | ✓ |
| Hex | Elixir | | ✓ | | Hex | Elixir | Yes* | ✓ |
| pub.dev | Dart | Yes | ✓ | | pub.dev | Dart | Yes | ✓ |
| PyPI | Python | Yes | ✓ | | PyPI | Python | Yes | ✓ |
| Maven | Java | | ✓ | | Maven | Java | | ✓ |
| NuGet | .NET | | ✓ | | NuGet | .NET | Yes | ✓ |
| Composer | PHP | Yes | ✓ | | Composer | PHP | Yes | ✓ |
| Conan | C/C++ | | ✓ | | Conan | C/C++ | | ✓ |
| Conda | Python/R | | ✓ | | Conda | Python/R | Yes | ✓ |
| CRAN | R | | ✓ | | CRAN | R | | ✓ |
| Container | Docker/OCI | | ✓ | | Container | Docker/OCI | | ✓ |
| Debian | Debian/Ubuntu | | ✓ | | Debian | Debian/Ubuntu | | ✓ |
@ -52,6 +50,16 @@ Currently works with npm, PyPI, pub.dev, Composer, and Cargo, which all include
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. 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
```bash ```bash
@ -460,6 +468,44 @@ 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.
@ -534,6 +580,14 @@ Recently cached:
| `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.

View file

@ -16,6 +16,7 @@
// //
// 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:
// //
@ -100,7 +101,11 @@ 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 const defaultTopN = 10
@ -124,6 +129,10 @@ 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)
@ -145,6 +154,7 @@ 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.
@ -340,6 +350,151 @@ func runStats() {
} }
} }
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 {
fmt.Fprintf(os.Stderr, "error opening database: %v\n", err)
os.Exit(1)
}
defer func() { _ = db.Close() }()
if err := db.MigrateSchema(); err != nil {
_ = 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()
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 { func printStats(db *database.DB, popular, recent int, asJSON bool) error {
defer func() { _ = db.Close() }() defer func() { _ = db.Close() }()

View file

@ -161,11 +161,25 @@ vulnerabilities (
updated_at DATETIME updated_at DATETIME
) )
-- indexes: (vuln_id, ecosystem, package_name) unique, (ecosystem, package_name) -- 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`. 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 adding missing columns via `ALTER TABLE` as needed. 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
@ -277,6 +291,12 @@ Version age filtering for supply chain attack mitigation. Configurable at global
Package metadata enrichment. Fetches license, description, homepage, repository URL, and vulnerability data from upstream registries. Powers the `/api/` endpoints and the web UI's package detail pages. Package metadata enrichment. 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`
Configuration loading. Configuration loading.
@ -326,10 +346,11 @@ 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?** **Why not cache metadata (by default)?**
- 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
**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

@ -209,7 +209,68 @@ Durations support days (`7d`), hours (`48h`), and minutes (`30m`). Set to `0` to
Resolution order: package override, then ecosystem override, then global default. This lets you set a conservative default while exempting trusted packages. 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, and Composer. These ecosystems include publish timestamps in their metadata. Other ecosystems (Go, Cargo, RubyGems) would require extra API calls and are not yet supported. 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.
```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.
## 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

51
docs/migrations.md Normal file
View file

@ -0,0 +1,51 @@
# 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

@ -297,115 +297,6 @@ const docTemplate = `{
} }
} }
}, },
"/api/package/{ecosystem}/{name}": {
"get": {
"description": "Returns enriched package metadata. URL-encode scoped names (e.g. @scope/name -\u003e %40scope%2Fname).",
"produces": [
"application/json"
],
"tags": [
"api"
],
"summary": "Get package metadata",
"parameters": [
{
"type": "string",
"description": "Ecosystem",
"name": "ecosystem",
"in": "path",
"required": true
},
{
"type": "string",
"description": "Package name",
"name": "name",
"in": "path",
"required": true
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/server.PackageResponse"
}
},
"400": {
"description": "Bad Request",
"schema": {
"type": "string"
}
},
"404": {
"description": "Not Found",
"schema": {
"type": "string"
}
},
"500": {
"description": "Internal Server Error",
"schema": {
"type": "string"
}
}
}
}
},
"/api/package/{ecosystem}/{name}/{version}": {
"get": {
"description": "Returns enriched package+version metadata and vulnerability data.",
"produces": [
"application/json"
],
"tags": [
"api"
],
"summary": "Get version metadata and vulnerabilities",
"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
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/server.EnrichmentResponse"
}
},
"400": {
"description": "Bad Request",
"schema": {
"type": "string"
}
},
"500": {
"description": "Internal Server Error",
"schema": {
"type": "string"
}
}
}
}
},
"/api/packages": { "/api/packages": {
"get": { "get": {
"produces": [ "produces": [
@ -505,108 +396,6 @@ const docTemplate = `{
} }
} }
}, },
"/api/vulns/{ecosystem}/{name}": {
"get": {
"description": "Returns vulnerabilities for a package across versions, or for a specific version if provided.",
"produces": [
"application/json"
],
"tags": [
"api"
],
"summary": "Get vulnerabilities for a package or version",
"parameters": [
{
"type": "string",
"description": "Ecosystem",
"name": "ecosystem",
"in": "path",
"required": true
},
{
"type": "string",
"description": "Package name",
"name": "name",
"in": "path",
"required": true
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/server.VulnsResponse"
}
},
"400": {
"description": "Bad Request",
"schema": {
"type": "string"
}
},
"500": {
"description": "Internal Server Error",
"schema": {
"type": "string"
}
}
}
}
},
"/api/vulns/{ecosystem}/{name}/{version}": {
"get": {
"description": "Returns vulnerabilities for a package across versions, or for a specific version if provided.",
"produces": [
"application/json"
],
"tags": [
"api"
],
"summary": "Get vulnerabilities for a package or version",
"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"
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/server.VulnsResponse"
}
},
"400": {
"description": "Bad Request",
"schema": {
"type": "string"
}
},
"500": {
"description": "Internal Server Error",
"schema": {
"type": "string"
}
}
}
}
},
"/health": { "/health": {
"get": { "get": {
"produces": [ "produces": [
@ -715,29 +504,6 @@ const docTemplate = `{
} }
} }
}, },
"server.EnrichmentResponse": {
"type": "object",
"properties": {
"is_outdated": {
"type": "boolean"
},
"license_category": {
"type": "string"
},
"package": {
"$ref": "#/definitions/server.PackageResponse"
},
"version": {
"$ref": "#/definitions/server.VersionResponse"
},
"vulnerabilities": {
"type": "array",
"items": {
"$ref": "#/definitions/server.VulnResponse"
}
}
}
},
"server.OutdatedPackage": { "server.OutdatedPackage": {
"type": "object", "type": "object",
"properties": { "properties": {
@ -949,84 +715,6 @@ const docTemplate = `{
"type": "integer" "type": "integer"
} }
} }
},
"server.VersionResponse": {
"type": "object",
"properties": {
"ecosystem": {
"type": "string"
},
"integrity": {
"type": "string"
},
"is_outdated": {
"type": "boolean"
},
"license": {
"type": "string"
},
"name": {
"type": "string"
},
"published_at": {
"type": "string"
},
"version": {
"type": "string"
},
"yanked": {
"type": "boolean"
}
}
},
"server.VulnResponse": {
"type": "object",
"properties": {
"cvss_score": {
"type": "number"
},
"fixed_version": {
"type": "string"
},
"id": {
"type": "string"
},
"references": {
"type": "array",
"items": {
"type": "string"
}
},
"severity": {
"type": "string"
},
"summary": {
"type": "string"
}
}
},
"server.VulnsResponse": {
"type": "object",
"properties": {
"count": {
"type": "integer"
},
"ecosystem": {
"type": "string"
},
"name": {
"type": "string"
},
"version": {
"type": "string"
},
"vulnerabilities": {
"type": "array",
"items": {
"$ref": "#/definitions/server.VulnResponse"
}
}
}
} }
} }
}` }`

View file

@ -290,115 +290,6 @@
} }
} }
}, },
"/api/package/{ecosystem}/{name}": {
"get": {
"description": "Returns enriched package metadata. URL-encode scoped names (e.g. @scope/name -\u003e %40scope%2Fname).",
"produces": [
"application/json"
],
"tags": [
"api"
],
"summary": "Get package metadata",
"parameters": [
{
"type": "string",
"description": "Ecosystem",
"name": "ecosystem",
"in": "path",
"required": true
},
{
"type": "string",
"description": "Package name",
"name": "name",
"in": "path",
"required": true
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/server.PackageResponse"
}
},
"400": {
"description": "Bad Request",
"schema": {
"type": "string"
}
},
"404": {
"description": "Not Found",
"schema": {
"type": "string"
}
},
"500": {
"description": "Internal Server Error",
"schema": {
"type": "string"
}
}
}
}
},
"/api/package/{ecosystem}/{name}/{version}": {
"get": {
"description": "Returns enriched package+version metadata and vulnerability data.",
"produces": [
"application/json"
],
"tags": [
"api"
],
"summary": "Get version metadata and vulnerabilities",
"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
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/server.EnrichmentResponse"
}
},
"400": {
"description": "Bad Request",
"schema": {
"type": "string"
}
},
"500": {
"description": "Internal Server Error",
"schema": {
"type": "string"
}
}
}
}
},
"/api/packages": { "/api/packages": {
"get": { "get": {
"produces": [ "produces": [
@ -498,108 +389,6 @@
} }
} }
}, },
"/api/vulns/{ecosystem}/{name}": {
"get": {
"description": "Returns vulnerabilities for a package across versions, or for a specific version if provided.",
"produces": [
"application/json"
],
"tags": [
"api"
],
"summary": "Get vulnerabilities for a package or version",
"parameters": [
{
"type": "string",
"description": "Ecosystem",
"name": "ecosystem",
"in": "path",
"required": true
},
{
"type": "string",
"description": "Package name",
"name": "name",
"in": "path",
"required": true
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/server.VulnsResponse"
}
},
"400": {
"description": "Bad Request",
"schema": {
"type": "string"
}
},
"500": {
"description": "Internal Server Error",
"schema": {
"type": "string"
}
}
}
}
},
"/api/vulns/{ecosystem}/{name}/{version}": {
"get": {
"description": "Returns vulnerabilities for a package across versions, or for a specific version if provided.",
"produces": [
"application/json"
],
"tags": [
"api"
],
"summary": "Get vulnerabilities for a package or version",
"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"
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/server.VulnsResponse"
}
},
"400": {
"description": "Bad Request",
"schema": {
"type": "string"
}
},
"500": {
"description": "Internal Server Error",
"schema": {
"type": "string"
}
}
}
}
},
"/health": { "/health": {
"get": { "get": {
"produces": [ "produces": [
@ -708,29 +497,6 @@
} }
} }
}, },
"server.EnrichmentResponse": {
"type": "object",
"properties": {
"is_outdated": {
"type": "boolean"
},
"license_category": {
"type": "string"
},
"package": {
"$ref": "#/definitions/server.PackageResponse"
},
"version": {
"$ref": "#/definitions/server.VersionResponse"
},
"vulnerabilities": {
"type": "array",
"items": {
"$ref": "#/definitions/server.VulnResponse"
}
}
}
},
"server.OutdatedPackage": { "server.OutdatedPackage": {
"type": "object", "type": "object",
"properties": { "properties": {
@ -942,84 +708,6 @@
"type": "integer" "type": "integer"
} }
} }
},
"server.VersionResponse": {
"type": "object",
"properties": {
"ecosystem": {
"type": "string"
},
"integrity": {
"type": "string"
},
"is_outdated": {
"type": "boolean"
},
"license": {
"type": "string"
},
"name": {
"type": "string"
},
"published_at": {
"type": "string"
},
"version": {
"type": "string"
},
"yanked": {
"type": "boolean"
}
}
},
"server.VulnResponse": {
"type": "object",
"properties": {
"cvss_score": {
"type": "number"
},
"fixed_version": {
"type": "string"
},
"id": {
"type": "string"
},
"references": {
"type": "array",
"items": {
"type": "string"
}
},
"severity": {
"type": "string"
},
"summary": {
"type": "string"
}
}
},
"server.VulnsResponse": {
"type": "object",
"properties": {
"count": {
"type": "integer"
},
"ecosystem": {
"type": "string"
},
"name": {
"type": "string"
},
"version": {
"type": "string"
},
"vulnerabilities": {
"type": "array",
"items": {
"$ref": "#/definitions/server.VulnResponse"
}
}
}
} }
} }
} }

19
go.mod
View file

@ -3,22 +3,26 @@ module github.com/git-pkgs/proxy
go 1.25.6 go 1.25.6
require ( require (
github.com/git-pkgs/archives v0.2.0 github.com/CycloneDX/cyclonedx-go v0.10.0
github.com/git-pkgs/enrichment v0.2.1 github.com/git-pkgs/archives v0.2.2
github.com/git-pkgs/enrichment v0.2.2
github.com/git-pkgs/purl v0.1.10 github.com/git-pkgs/purl v0.1.10
github.com/git-pkgs/registries v0.4.0 github.com/git-pkgs/registries v0.4.0
github.com/git-pkgs/spdx v0.1.2 github.com/git-pkgs/spdx v0.1.2
github.com/git-pkgs/vers v0.2.4 github.com/git-pkgs/vers v0.2.4
github.com/git-pkgs/vulns v0.1.3 github.com/git-pkgs/vulns v0.1.4
github.com/go-chi/chi/v5 v5.2.5 github.com/go-chi/chi/v5 v5.2.5
github.com/jmoiron/sqlx v1.4.0 github.com/jmoiron/sqlx v1.4.0
github.com/lib/pq v1.12.0 github.com/lib/pq v1.12.2
github.com/prometheus/client_golang v1.23.2 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
github.com/swaggo/swag v1.16.6 github.com/swaggo/swag v1.16.6
gocloud.dev v0.45.0 gocloud.dev v0.45.0
golang.org/x/sync v0.20.0
google.golang.org/protobuf v1.36.11
gopkg.in/yaml.v3 v3.0.1 gopkg.in/yaml.v3 v3.0.1
modernc.org/sqlite v1.47.0 modernc.org/sqlite v1.48.0
) )
require ( require (
@ -51,6 +55,7 @@ require (
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.0 // indirect github.com/ashanbrown/forbidigo/v2 v2.3.0 // indirect
github.com/ashanbrown/makezero/v2 v2.1.0 // indirect github.com/ashanbrown/makezero/v2 v2.1.0 // indirect
@ -276,7 +281,6 @@ require (
golang.org/x/exp/typeparams v0.0.0-20260209203927-2842357ff358 // indirect golang.org/x/exp/typeparams v0.0.0-20260209203927-2842357ff358 // indirect
golang.org/x/mod v0.33.0 // indirect golang.org/x/mod v0.33.0 // indirect
golang.org/x/net v0.51.0 // indirect golang.org/x/net v0.51.0 // indirect
golang.org/x/sync v0.20.0 // indirect
golang.org/x/sys v0.42.0 // indirect golang.org/x/sys v0.42.0 // indirect
golang.org/x/text v0.34.0 // indirect golang.org/x/text v0.34.0 // indirect
golang.org/x/tools v0.42.0 // indirect golang.org/x/tools v0.42.0 // indirect
@ -284,7 +288,6 @@ require (
google.golang.org/api v0.269.0 // indirect google.golang.org/api v0.269.0 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20260226221140-a57be14db171 // indirect google.golang.org/genproto/googleapis/rpc v0.0.0-20260226221140-a57be14db171 // indirect
google.golang.org/grpc v1.79.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.7.0 // indirect honnef.co/go/tools v0.7.0 // indirect
@ -293,7 +296,7 @@ require (
modernc.org/memory v1.11.0 // indirect modernc.org/memory v1.11.0 // indirect
mvdan.cc/gofumpt v0.9.2 // indirect mvdan.cc/gofumpt v0.9.2 // indirect
mvdan.cc/unparam v0.0.0-20251027182757-5beb8c8f8f15 // indirect mvdan.cc/unparam v0.0.0-20251027182757-5beb8c8f8f15 // indirect
sigs.k8s.io/yaml v1.3.0 // 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

40
go.sum
View file

@ -46,6 +46,8 @@ github.com/Antonboom/testifylint v1.6.4/go.mod h1:YO33FROXX2OoUfwjz8g+gUxQXio5i9
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
github.com/BurntSushi/toml v1.6.0 h1:dRaEfpa2VI55EwlIW72hMRHdWouJeRF7TPYhI+AUQjk= github.com/BurntSushi/toml v1.6.0 h1:dRaEfpa2VI55EwlIW72hMRHdWouJeRF7TPYhI+AUQjk=
github.com/BurntSushi/toml v1.6.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho= github.com/BurntSushi/toml v1.6.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho=
github.com/CycloneDX/cyclonedx-go v0.10.0 h1:7xyklU7YD+CUyGzSFIARG18NYLsKVn4QFg04qSsu+7Y=
github.com/CycloneDX/cyclonedx-go v0.10.0/go.mod h1:vUvbCXQsEm48OI6oOlanxstwNByXjCZ2wuleUlwGEO8=
github.com/Djarvur/go-err113 v0.1.1 h1:eHfopDqXRwAi+YmCUas75ZE0+hoBHJ2GQNLYRSxao4g= github.com/Djarvur/go-err113 v0.1.1 h1:eHfopDqXRwAi+YmCUas75ZE0+hoBHJ2GQNLYRSxao4g=
github.com/Djarvur/go-err113 v0.1.1/go.mod h1:IaWJdYFLg76t2ihfflPZnM1LIQszWOsFDh2hhhAVF6k= github.com/Djarvur/go-err113 v0.1.1/go.mod h1:IaWJdYFLg76t2ihfflPZnM1LIQszWOsFDh2hhhAVF6k=
github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.30.0 h1:sBEjpZlNHzK1voKq9695PJSX2o5NEXl7/OL3coiIY0c= github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.30.0 h1:sBEjpZlNHzK1voKq9695PJSX2o5NEXl7/OL3coiIY0c=
@ -85,6 +87,8 @@ github.com/alingse/asasalint v0.0.11 h1:SFwnQXJ49Kx/1GghOFz1XGqHYKp21Kq1nHad/0WQ
github.com/alingse/asasalint v0.0.11/go.mod h1:nCaoMhw7a9kSJObvQyVzNTPBDbNpdocqrSP7t/cW5+I= github.com/alingse/asasalint v0.0.11/go.mod h1:nCaoMhw7a9kSJObvQyVzNTPBDbNpdocqrSP7t/cW5+I=
github.com/alingse/nilnesserr v0.2.0 h1:raLem5KG7EFVb4UIDAXgrv3N2JIaffeKNtcEXkEWd/w= github.com/alingse/nilnesserr v0.2.0 h1:raLem5KG7EFVb4UIDAXgrv3N2JIaffeKNtcEXkEWd/w=
github.com/alingse/nilnesserr v0.2.0/go.mod h1:1xJPrXonEtX7wyTq8Dytns5P2hNzoWymVUIaKm4HNFg= github.com/alingse/nilnesserr v0.2.0/go.mod h1:1xJPrXonEtX7wyTq8Dytns5P2hNzoWymVUIaKm4HNFg=
github.com/anchore/go-struct-converter v0.1.0 h1:2rDRssAl6mgKBSLNiVCMADgZRhoqtw9dedlWa0OhD30=
github.com/anchore/go-struct-converter v0.1.0/go.mod h1:rYqSE9HbjzpHTI74vwPvae4ZVYZd1lue2ta6xHPdblA=
github.com/apapsch/go-jsonmerge/v2 v2.0.0 h1:axGnT1gRIfimI7gJifB699GoE/oq+F2MU7Dml6nw9rQ= github.com/apapsch/go-jsonmerge/v2 v2.0.0 h1:axGnT1gRIfimI7gJifB699GoE/oq+F2MU7Dml6nw9rQ=
github.com/apapsch/go-jsonmerge/v2 v2.0.0/go.mod h1:lvDnEdqiQrp0O42VQGgmlKpxL1AP2+08jFMw88y4klk= github.com/apapsch/go-jsonmerge/v2 v2.0.0/go.mod h1:lvDnEdqiQrp0O42VQGgmlKpxL1AP2+08jFMw88y4klk=
github.com/ashanbrown/forbidigo/v2 v2.3.0 h1:OZZDOchCgsX5gvToVtEBoV2UWbFfI6RKQTir2UZzSxo= github.com/ashanbrown/forbidigo/v2 v2.3.0 h1:OZZDOchCgsX5gvToVtEBoV2UWbFfI6RKQTir2UZzSxo=
@ -144,6 +148,8 @@ github.com/bombsimon/wsl/v4 v4.7.0 h1:1Ilm9JBPRczjyUs6hvOPKvd7VL1Q++PL8M0SXBDf+j
github.com/bombsimon/wsl/v4 v4.7.0/go.mod h1:uV/+6BkffuzSAVYD+yGyld1AChO7/EuLrCF/8xTiapg= github.com/bombsimon/wsl/v4 v4.7.0/go.mod h1:uV/+6BkffuzSAVYD+yGyld1AChO7/EuLrCF/8xTiapg=
github.com/bombsimon/wsl/v5 v5.6.0 h1:4z+/sBqC5vUmSp1O0mS+czxwH9+LKXtCWtHH9rZGQL8= github.com/bombsimon/wsl/v5 v5.6.0 h1:4z+/sBqC5vUmSp1O0mS+czxwH9+LKXtCWtHH9rZGQL8=
github.com/bombsimon/wsl/v5 v5.6.0/go.mod h1:Uqt2EfrMj2NV8UGoN1f1Y3m0NpUVCsUdrNCdet+8LvU= github.com/bombsimon/wsl/v5 v5.6.0/go.mod h1:Uqt2EfrMj2NV8UGoN1f1Y3m0NpUVCsUdrNCdet+8LvU=
github.com/bradleyjkemp/cupaloy/v2 v2.8.0 h1:any4BmKE+jGIaMpnU8YgH/I2LPiLBufr6oMMlVBbn9M=
github.com/bradleyjkemp/cupaloy/v2 v2.8.0/go.mod h1:bm7JXdkRd4BHJk9HpwqAI8BoAY1lps46Enkdqw6aRX0=
github.com/breml/bidichk v0.3.3 h1:WSM67ztRusf1sMoqH6/c4OBCUlRVTKq+CbSeo0R17sE= github.com/breml/bidichk v0.3.3 h1:WSM67ztRusf1sMoqH6/c4OBCUlRVTKq+CbSeo0R17sE=
github.com/breml/bidichk v0.3.3/go.mod h1:ISbsut8OnjB367j5NseXEGGgO/th206dVa427kR8YTE= github.com/breml/bidichk v0.3.3/go.mod h1:ISbsut8OnjB367j5NseXEGGgO/th206dVa427kR8YTE=
github.com/breml/errchkjson v0.4.1 h1:keFSS8D7A2T0haP9kzZTi7o26r7kE3vymjZNeNDRDwg= github.com/breml/errchkjson v0.4.1 h1:keFSS8D7A2T0haP9kzZTi7o26r7kE3vymjZNeNDRDwg=
@ -224,10 +230,10 @@ github.com/fzipp/gocyclo v0.6.0 h1:lsblElZG7d3ALtGMx9fmxeTKZaLLpU8mET09yN4BBLo=
github.com/fzipp/gocyclo v0.6.0/go.mod h1:rXPyn8fnlpa0R2csP/31uerbiVBugk5whMdlyaLkLoA= github.com/fzipp/gocyclo v0.6.0/go.mod h1:rXPyn8fnlpa0R2csP/31uerbiVBugk5whMdlyaLkLoA=
github.com/ghostiam/protogetter v0.3.20 h1:oW7OPFit2FxZOpmMRPP9FffU4uUpfeE/rEdE1f+MzD0= github.com/ghostiam/protogetter v0.3.20 h1:oW7OPFit2FxZOpmMRPP9FffU4uUpfeE/rEdE1f+MzD0=
github.com/ghostiam/protogetter v0.3.20/go.mod h1:FjIu5Yfs6FT391m+Fjp3fbAYJ6rkL/J6ySpZBfnODuI= github.com/ghostiam/protogetter v0.3.20/go.mod h1:FjIu5Yfs6FT391m+Fjp3fbAYJ6rkL/J6ySpZBfnODuI=
github.com/git-pkgs/archives v0.2.0 h1:8OuuGwAB+Eww8/1ayyYpZzP0wVEH0/VWBG3mQrfi9SM= github.com/git-pkgs/archives v0.2.2 h1:RxOjrV8RzKicbMVdf2GDKOqIOHZNVjrLY/Pc7KSE/WQ=
github.com/git-pkgs/archives v0.2.0/go.mod h1:LTJ1iQVFA7otizWMOyiI82NYVmyBWAPRzwu/e30rcXU= github.com/git-pkgs/archives v0.2.2/go.mod h1:LTJ1iQVFA7otizWMOyiI82NYVmyBWAPRzwu/e30rcXU=
github.com/git-pkgs/enrichment v0.2.1 h1:mJJt4YQBzl9aOfu4226ylnC9H6YO9YZDjGpbSPVahKc= github.com/git-pkgs/enrichment v0.2.2 h1:vaQu5vs3tjQB5JI0gzBrUCynUc9z3l5byPhgKFaNZrc=
github.com/git-pkgs/enrichment v0.2.1/go.mod h1:q9eDZpRrUbYwzD4Mtg/T6LRdBMlt2DYRIvVRDULFnKg= github.com/git-pkgs/enrichment v0.2.2/go.mod h1:5JWGmlHWcv5HQHUrctcpnRUNpEF5VAixD2z4zvqKejs=
github.com/git-pkgs/packageurl-go v0.3.1 h1:WM3RBABQZLaRBxgKyYughc3cVBE8KyQxbSC6Jt5ak7M= github.com/git-pkgs/packageurl-go v0.3.1 h1:WM3RBABQZLaRBxgKyYughc3cVBE8KyQxbSC6Jt5ak7M=
github.com/git-pkgs/packageurl-go v0.3.1/go.mod h1:rcIxiG37BlQLB6FZfgdj9Fm7yjhRQd3l+5o7J0QPAk4= github.com/git-pkgs/packageurl-go v0.3.1/go.mod h1:rcIxiG37BlQLB6FZfgdj9Fm7yjhRQd3l+5o7J0QPAk4=
github.com/git-pkgs/purl v0.1.10 h1:NMjeF10nzFn3tdQlz6rbmHB+i+YkyrFQxho3e33ePTQ= github.com/git-pkgs/purl v0.1.10 h1:NMjeF10nzFn3tdQlz6rbmHB+i+YkyrFQxho3e33ePTQ=
@ -238,8 +244,8 @@ github.com/git-pkgs/spdx v0.1.2 h1:wHSK+CqFsO5N7yDTPvxDmer5LgNEa7vAsiZhi5Aci0A=
github.com/git-pkgs/spdx v0.1.2/go.mod h1:V98MgZapNgYw54/pdGR82d7RU93qzJoybahbpZqTfw8= github.com/git-pkgs/spdx v0.1.2/go.mod h1:V98MgZapNgYw54/pdGR82d7RU93qzJoybahbpZqTfw8=
github.com/git-pkgs/vers v0.2.4 h1:Zr3jR/Xf1i/6cvBaJKPxhCwjzqz7uvYHE0Fhid/GPBk= github.com/git-pkgs/vers v0.2.4 h1:Zr3jR/Xf1i/6cvBaJKPxhCwjzqz7uvYHE0Fhid/GPBk=
github.com/git-pkgs/vers v0.2.4/go.mod h1:biTbSQK1qdbrsxDEKnqe3Jzclxz8vW6uDcwKjfUGcOo= github.com/git-pkgs/vers v0.2.4/go.mod h1:biTbSQK1qdbrsxDEKnqe3Jzclxz8vW6uDcwKjfUGcOo=
github.com/git-pkgs/vulns v0.1.3 h1:Q9GixxhAYpP5vVDetKNMACHxGnWwB8aE5c9kbE8xxqU= github.com/git-pkgs/vulns v0.1.4 h1:SlnGWHNmtdQgABjfrX/I/pVe+DWLbZ5Yi9xg+/De5r8=
github.com/git-pkgs/vulns v0.1.3/go.mod h1:/PVy7S1oZNVF9X8yVOZ9SX5MFpyVWCtLnIX0kAfPjY0= github.com/git-pkgs/vulns v0.1.4/go.mod h1:34xkR7QncIVfxoi78k3YT6Y9DfTEaL7j6PzCqjsRP9U=
github.com/github/go-spdx/v2 v2.4.0 h1:+4IwVwJJbm3rzvrQ6P1nI9BDMcy3la4RchRy5uehV/M= github.com/github/go-spdx/v2 v2.4.0 h1:+4IwVwJJbm3rzvrQ6P1nI9BDMcy3la4RchRy5uehV/M=
github.com/github/go-spdx/v2 v2.4.0/go.mod h1:/5rwgS0txhGtRdUZwc02bTglzg6HK3FfuEbECKlK2Sg= github.com/github/go-spdx/v2 v2.4.0/go.mod h1:/5rwgS0txhGtRdUZwc02bTglzg6HK3FfuEbECKlK2Sg=
github.com/go-chi/chi/v5 v5.2.5 h1:Eg4myHZBjyvJmAFjFvWgrqDTXFyOzjj7YIm3L3mu6Ug= github.com/go-chi/chi/v5 v5.2.5 h1:Eg4myHZBjyvJmAFjFvWgrqDTXFyOzjj7YIm3L3mu6Ug=
@ -426,8 +432,8 @@ github.com/ldez/usetesting v0.5.0/go.mod h1:Spnb4Qppf8JTuRgblLrEWb7IE6rDmUpGvxY3
github.com/leonklingele/grouper v1.1.2 h1:o1ARBDLOmmasUaNDesWqWCIFH3u7hoFlM84YrjT3mIY= github.com/leonklingele/grouper v1.1.2 h1:o1ARBDLOmmasUaNDesWqWCIFH3u7hoFlM84YrjT3mIY=
github.com/leonklingele/grouper v1.1.2/go.mod h1:6D0M/HVkhs2yRKRFZUoGjeDy7EZTfFBE9gl4kjmIGkA= github.com/leonklingele/grouper v1.1.2/go.mod h1:6D0M/HVkhs2yRKRFZUoGjeDy7EZTfFBE9gl4kjmIGkA=
github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o= github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
github.com/lib/pq v1.12.0 h1:mC1zeiNamwKBecjHarAr26c/+d8V5w/u4J0I/yASbJo= github.com/lib/pq v1.12.2 h1:ajJNv84limnK3aPbDIhLtcjrUbqAw/5XNdkuI6KNe/Q=
github.com/lib/pq v1.12.0/go.mod h1:/p+8NSbOcwzAEI7wiMXFlgydTwcgTr3OSKMsD2BitpA= github.com/lib/pq v1.12.2/go.mod h1:/p+8NSbOcwzAEI7wiMXFlgydTwcgTr3OSKMsD2BitpA=
github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY= github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY=
github.com/lucasb-eyer/go-colorful v1.2.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0= github.com/lucasb-eyer/go-colorful v1.2.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=
github.com/macabu/inamedparam v0.2.0 h1:VyPYpOc10nkhI2qeNUdh3Zket4fcZjEWe35poddBCpE= github.com/macabu/inamedparam v0.2.0 h1:VyPYpOc10nkhI2qeNUdh3Zket4fcZjEWe35poddBCpE=
@ -568,6 +574,8 @@ github.com/sonatard/noctx v0.4.0 h1:7MC/5Gg4SQ4lhLYR6mvOP6mQVSxCrdyiExo7atBs27o=
github.com/sonatard/noctx v0.4.0/go.mod h1:64XdbzFb18XL4LporKXp8poqZtPKbCrqQ402CV+kJas= github.com/sonatard/noctx v0.4.0/go.mod h1:64XdbzFb18XL4LporKXp8poqZtPKbCrqQ402CV+kJas=
github.com/sourcegraph/go-diff v0.7.0 h1:9uLlrd5T46OXs5qpp8L/MTltk0zikUGi0sNNyCpA8G0= github.com/sourcegraph/go-diff v0.7.0 h1:9uLlrd5T46OXs5qpp8L/MTltk0zikUGi0sNNyCpA8G0=
github.com/sourcegraph/go-diff v0.7.0/go.mod h1:iBszgVvyxdc8SFZ7gm69go2KDdt3ag071iBaWPF6cjs= github.com/sourcegraph/go-diff v0.7.0/go.mod h1:iBszgVvyxdc8SFZ7gm69go2KDdt3ag071iBaWPF6cjs=
github.com/spdx/tools-golang v0.5.7 h1:+sWcKGnhwp3vLdMqPcLdA6QK679vd86cK9hQWH3AwCg=
github.com/spdx/tools-golang v0.5.7/go.mod h1:jg7w0LOpoNAw6OxKEzCoqPC2GCTj45LyTlVmXubDsYw=
github.com/spf13/afero v1.15.0 h1:b/YBCLWAJdFWJTN9cLhiXXcD7mzKn9Dm86dNnfyQw1I= github.com/spf13/afero v1.15.0 h1:b/YBCLWAJdFWJTN9cLhiXXcD7mzKn9Dm86dNnfyQw1I=
github.com/spf13/afero v1.15.0/go.mod h1:NC2ByUVxtQs4b3sIUphxK0NioZnmxgyCrfzeuq8lxMg= github.com/spf13/afero v1.15.0/go.mod h1:NC2ByUVxtQs4b3sIUphxK0NioZnmxgyCrfzeuq8lxMg=
github.com/spf13/cast v1.5.0 h1:rj3WzYc11XZaIZMPKmwP96zkFEnnAmV8s6XbB2aY32w= github.com/spf13/cast v1.5.0 h1:rj3WzYc11XZaIZMPKmwP96zkFEnnAmV8s6XbB2aY32w=
@ -606,6 +614,8 @@ github.com/tenntenn/modver v1.0.1 h1:2klLppGhDgzJrScMpkj9Ujy3rXPUspSjAcev9tSEBgA
github.com/tenntenn/modver v1.0.1/go.mod h1:bePIyQPb7UeioSRkw3Q0XeMhYZSMx9B8ePqg6SAMGH0= github.com/tenntenn/modver v1.0.1/go.mod h1:bePIyQPb7UeioSRkw3Q0XeMhYZSMx9B8ePqg6SAMGH0=
github.com/tenntenn/text/transform v0.0.0-20200319021203-7eef512accb3 h1:f+jULpRQGxTSkNYKJ51yaw6ChIqO+Je8UqsTKN/cDag= github.com/tenntenn/text/transform v0.0.0-20200319021203-7eef512accb3 h1:f+jULpRQGxTSkNYKJ51yaw6ChIqO+Je8UqsTKN/cDag=
github.com/tenntenn/text/transform v0.0.0-20200319021203-7eef512accb3/go.mod h1:ON8b8w4BN/kE1EOhwT0o+d62W65a6aPw1nouo9LMgyY= github.com/tenntenn/text/transform v0.0.0-20200319021203-7eef512accb3/go.mod h1:ON8b8w4BN/kE1EOhwT0o+d62W65a6aPw1nouo9LMgyY=
github.com/terminalstatic/go-xsd-validate v0.1.6 h1:TenYeQ3eY631qNi1/cTmLH/s2slHPRKTTHT+XSHkepo=
github.com/terminalstatic/go-xsd-validate v0.1.6/go.mod h1:18lsvYFofBflqCrvo1umpABZ99+GneNTw2kEEc8UPJw=
github.com/tetafro/godot v1.5.4 h1:u1ww+gqpRLiIA16yF2PV1CV1n/X3zhyezbNXC3E14Sg= github.com/tetafro/godot v1.5.4 h1:u1ww+gqpRLiIA16yF2PV1CV1n/X3zhyezbNXC3E14Sg=
github.com/tetafro/godot v1.5.4/go.mod h1:eOkMrVQurDui411nBY2FA05EYH01r14LuWY/NrVDVcU= github.com/tetafro/godot v1.5.4/go.mod h1:eOkMrVQurDui411nBY2FA05EYH01r14LuWY/NrVDVcU=
github.com/timakin/bodyclose v0.0.0-20241222091800-1db5c5ca4d67 h1:9LPGD+jzxMlnk5r6+hJnar67cgpDIz/iyD+rfl5r2Vk= github.com/timakin/bodyclose v0.0.0-20241222091800-1db5c5ca4d67 h1:9LPGD+jzxMlnk5r6+hJnar67cgpDIz/iyD+rfl5r2Vk=
@ -628,6 +638,12 @@ github.com/uudashr/gocognit v1.2.0 h1:3BU9aMr1xbhPlvJLSydKwdLN3tEUUrzPSSM8S4hDYR
github.com/uudashr/gocognit v1.2.0/go.mod h1:k/DdKPI6XBZO1q7HgoV2juESI2/Ofj9AcHPZhBBdrTU= github.com/uudashr/gocognit v1.2.0/go.mod h1:k/DdKPI6XBZO1q7HgoV2juESI2/Ofj9AcHPZhBBdrTU=
github.com/uudashr/iface v1.4.1 h1:J16Xl1wyNX9ofhpHmQ9h9gk5rnv2A6lX/2+APLTo0zU= github.com/uudashr/iface v1.4.1 h1:J16Xl1wyNX9ofhpHmQ9h9gk5rnv2A6lX/2+APLTo0zU=
github.com/uudashr/iface v1.4.1/go.mod h1:pbeBPlbuU2qkNDn0mmfrxP2X+wjPMIQAy+r1MBXSXtg= github.com/uudashr/iface v1.4.1/go.mod h1:pbeBPlbuU2qkNDn0mmfrxP2X+wjPMIQAy+r1MBXSXtg=
github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f h1:J9EGpcZtP0E/raorCMxlFGSTBrsSlaDGf3jU/qvAE2c=
github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f/go.mod h1:N2zxlSyiKSe5eX1tZViRH5QA0qijqEDrYZiPEAiq3wU=
github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 h1:EzJWgHovont7NscjpAxXsDA8S8BMYve8Y5+7cuRE7R0=
github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415/go.mod h1:GwrjFmJcFw6At/Gs6z4yjiIwzuJ1/+UwLxMQDVQXShQ=
github.com/xeipuuv/gojsonschema v1.2.0 h1:LhYJRs+L4fBtjZUfuSZIKGeVu0QRy8e5Xi7D17UxZ74=
github.com/xeipuuv/gojsonschema v1.2.0/go.mod h1:anYRn/JVcOK2ZgGU+IjEV4nwlhoK5sQluxsYJ78Id3Y=
github.com/xen0n/gosmopolitan v1.3.0 h1:zAZI1zefvo7gcpbCOrPSHJZJYA9ZgLfJqtKzZ5pHqQM= github.com/xen0n/gosmopolitan v1.3.0 h1:zAZI1zefvo7gcpbCOrPSHJZJYA9ZgLfJqtKzZ5pHqQM=
github.com/xen0n/gosmopolitan v1.3.0/go.mod h1:rckfr5T6o4lBtM1ga7mLGKZmLxswUoH1zxHgNXOsEt4= github.com/xen0n/gosmopolitan v1.3.0/go.mod h1:rckfr5T6o4lBtM1ga7mLGKZmLxswUoH1zxHgNXOsEt4=
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e h1:JVG44RsyaB9T2KIHavMF/ppJZNG9ZpyihvCd0w101no= github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e h1:JVG44RsyaB9T2KIHavMF/ppJZNG9ZpyihvCd0w101no=
@ -857,8 +873,8 @@ modernc.org/opt v0.1.4 h1:2kNGMRiUjrp4LcaPuLY2PzUfqM/w9N23quVwhKt5Qm8=
modernc.org/opt v0.1.4/go.mod h1:03fq9lsNfvkYSfxrfUhZCWPk1lm4cq4N+Bh//bEtgns= modernc.org/opt v0.1.4/go.mod h1:03fq9lsNfvkYSfxrfUhZCWPk1lm4cq4N+Bh//bEtgns=
modernc.org/sortutil v1.2.1 h1:+xyoGf15mM3NMlPDnFqrteY07klSFxLElE2PVuWIJ7w= modernc.org/sortutil v1.2.1 h1:+xyoGf15mM3NMlPDnFqrteY07klSFxLElE2PVuWIJ7w=
modernc.org/sortutil v1.2.1/go.mod h1:7ZI3a3REbai7gzCLcotuw9AC4VZVpYMjDzETGsSMqJE= modernc.org/sortutil v1.2.1/go.mod h1:7ZI3a3REbai7gzCLcotuw9AC4VZVpYMjDzETGsSMqJE=
modernc.org/sqlite v1.47.0 h1:R1XyaNpoW4Et9yly+I2EeX7pBza/w+pmYee/0HJDyKk= modernc.org/sqlite v1.48.0 h1:ElZyLop3Q2mHYk5IFPPXADejZrlHu7APbpB0sF78bq4=
modernc.org/sqlite v1.47.0/go.mod h1:hWjRO6Tj/5Ik8ieqxQybiEOUXy0NJFNp2tpvVpKlvig= modernc.org/sqlite v1.48.0/go.mod h1:hWjRO6Tj/5Ik8ieqxQybiEOUXy0NJFNp2tpvVpKlvig=
modernc.org/strutil v1.2.1 h1:UneZBkQA+DX2Rp35KcM69cSsNES9ly8mQWD71HKlOA0= modernc.org/strutil v1.2.1 h1:UneZBkQA+DX2Rp35KcM69cSsNES9ly8mQWD71HKlOA0=
modernc.org/strutil v1.2.1/go.mod h1:EHkiggD70koQxjVdSBM3JKM7k6L0FbGE5eymy9i3B9A= modernc.org/strutil v1.2.1/go.mod h1:EHkiggD70koQxjVdSBM3JKM7k6L0FbGE5eymy9i3B9A=
modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y= modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y=
@ -867,5 +883,5 @@ mvdan.cc/gofumpt v0.9.2 h1:zsEMWL8SVKGHNztrx6uZrXdp7AX8r421Vvp23sz7ik4=
mvdan.cc/gofumpt v0.9.2/go.mod h1:iB7Hn+ai8lPvofHd9ZFGVg2GOr8sBUw1QUWjNbmIL/s= mvdan.cc/gofumpt v0.9.2/go.mod h1:iB7Hn+ai8lPvofHd9ZFGVg2GOr8sBUw1QUWjNbmIL/s=
mvdan.cc/unparam v0.0.0-20251027182757-5beb8c8f8f15 h1:ssMzja7PDPJV8FStj7hq9IKiuiKhgz9ErWw+m68e7DI= mvdan.cc/unparam v0.0.0-20251027182757-5beb8c8f8f15 h1:ssMzja7PDPJV8FStj7hq9IKiuiKhgz9ErWw+m68e7DI=
mvdan.cc/unparam v0.0.0-20251027182757-5beb8c8f8f15/go.mod h1:4M5MMXl2kW6fivUT6yRGpLLPNfuGtU2Z0cPvFquGDYU= mvdan.cc/unparam v0.0.0-20251027182757-5beb8c8f8f15/go.mod h1:4M5MMXl2kW6fivUT6yRGpLLPNfuGtU2Z0cPvFquGDYU=
sigs.k8s.io/yaml v1.3.0 h1:a2VclLzOGrwOHDiV8EfBGhvjHvP46CtW5j6POvhYGGo= sigs.k8s.io/yaml v1.6.0 h1:G8fkbMSAFqgEFgh4b1wmtzDnioxFCUgTZhlbj5P9QYs=
sigs.k8s.io/yaml v1.3.0/go.mod h1:GeOyir5tyXNByN85N/dRIT9es5UQNerPYEKK56eTBm8= sigs.k8s.io/yaml v1.6.0/go.mod h1:796bPqUfzR/0jLAl6XjHl3Ck7MiyVv8dbTdyT3/pMf4=

View file

@ -55,6 +55,7 @@ import (
"path/filepath" "path/filepath"
"strconv" "strconv"
"strings" "strings"
"time"
"gopkg.in/yaml.v3" "gopkg.in/yaml.v3"
) )
@ -83,6 +84,20 @@ type Config struct {
// Cooldown configures version age filtering to mitigate supply chain attacks. // Cooldown configures version age filtering to mitigate supply chain attacks.
Cooldown CooldownConfig `json:"cooldown" yaml:"cooldown"` 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"`
// 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"`
} }
// CooldownConfig configures version cooldown periods. // CooldownConfig configures version cooldown periods.
@ -306,6 +321,15 @@ func (c *Config) LoadFromEnv() {
if v := os.Getenv("PROXY_COOLDOWN_DEFAULT"); v != "" { if v := os.Getenv("PROXY_COOLDOWN_DEFAULT"); v != "" {
c.Cooldown.Default = v c.Cooldown.Default = v
} }
if v := os.Getenv("PROXY_CACHE_METADATA"); v != "" {
c.CacheMetadata = v == "true" || v == "1"
}
if v := os.Getenv("PROXY_MIRROR_API"); v != "" {
c.MirrorAPI = v == "true" || v == "1"
}
if v := os.Getenv("PROXY_METADATA_TTL"); v != "" {
c.MetadataTTL = v
}
} }
// Validate checks the configuration for errors. // Validate checks the configuration for errors.
@ -355,9 +379,34 @@ func (c *Config) Validate() error {
} }
} }
// Validate metadata TTL if specified
if c.MetadataTTL != "" && c.MetadataTTL != "0" {
if _, err := time.ParseDuration(c.MetadataTTL); err != nil {
return fmt.Errorf("invalid metadata_ttl %q: %w", c.MetadataTTL, err)
}
}
return nil return nil
} }
const defaultMetadataTTL = 5 * time.Minute //nolint:mnd // sensible default
// 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
}
// 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) {

View file

@ -4,6 +4,7 @@ import (
"os" "os"
"path/filepath" "path/filepath"
"testing" "testing"
"time"
) )
const ( const (
@ -301,3 +302,56 @@ func TestLoadFileNotFound(t *testing.T) {
t.Error("expected error for nonexistent file") t.Error("expected error for nonexistent file")
} }
} }
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 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 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")
}
}

View file

@ -651,58 +651,159 @@ func TestMigrationFromOldSchema(t *testing.T) {
} }
defer func() { _ = db.Close() }() defer func() { _ = db.Close() }()
// Try to run queries that require new columns - these should fail without migration // Queries that require new columns should fail without migration
t.Run("queries should fail without migration", func(t *testing.T) { if _, err := db.GetEnrichmentStats(); err == nil {
_, err := db.GetEnrichmentStats() t.Error("GetEnrichmentStats: expected error querying enriched_at column, got nil")
if err == nil { }
t.Error("GetEnrichmentStats: expected error querying enriched_at column, got nil") if _, err := db.GetPackageByEcosystemName("npm", "test-package"); err == nil {
} t.Error("GetPackageByEcosystemName: expected error querying registry_url column, got nil")
}
_, err = db.GetPackageByEcosystemName("npm", "test-package") // SearchPackages should work even with old schema because it uses sql.NullString
if err == nil { if _, err := db.SearchPackages("test", "", 10, 0); err != nil {
t.Error("GetPackageByEcosystemName: expected error querying registry_url column, got nil") t.Errorf("SearchPackages: unexpected error with old schema: %v", err)
} }
// 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
t.Run("migrate schema", func(t *testing.T) { if err := db.MigrateSchema(); err != nil {
if err := db.MigrateSchema(); err != nil { t.Fatalf("MigrateSchema failed: %v", err)
t.Fatalf("MigrateSchema failed: %v", err) }
}
})
// Verify queries work after migration // Verify queries work after migration
t.Run("queries should work after migration", func(t *testing.T) { stats, err := db.GetEnrichmentStats()
stats, err := db.GetEnrichmentStats() if err != nil {
if err != nil { t.Errorf("GetEnrichmentStats failed after migration: %v", err)
t.Errorf("GetEnrichmentStats failed after migration: %v", err) }
} if stats == nil {
if stats == nil { t.Error("GetEnrichmentStats returned nil after migration")
t.Error("GetEnrichmentStats returned nil after migration") }
}
pkg, err := db.GetPackageByEcosystemName("npm", "test-package") pkg, err := db.GetPackageByEcosystemName("npm", "test-package")
if err != nil { if err != nil {
t.Errorf("GetPackageByEcosystemName failed after migration: %v", err) t.Errorf("GetPackageByEcosystemName failed after migration: %v", err)
} }
if pkg == nil { if pkg == nil {
t.Fatal("GetPackageByEcosystemName returned nil after migration") t.Fatal("GetPackageByEcosystemName returned nil after migration")
} }
if pkg.Name != "test-package" { if pkg.Name != "test-package" {
t.Errorf("expected package name test-package, got %s", pkg.Name) t.Errorf("expected package name test-package, got %s", pkg.Name)
} }
// Note: SearchPackages not tested here because old timestamp data // Verify migrations were recorded
// stored as strings can't be scanned into time.Time. This is a data applied, err := db.appliedMigrations()
// migration issue, not a schema migration issue. 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)
}
}
// 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) {
dir := t.TempDir()
dbPath := filepath.Join(dir, "test.db")
db, err := Create(dbPath)
if err != nil {
t.Fatalf("Create failed: %v", err)
}
defer func() { _ = db.Close() }()
// 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)
if err := db.MigrateSchema(); err != nil {
t.Fatalf("second MigrateSchema failed: %v", err)
}
} }
func TestConcurrentWrites(t *testing.T) { func TestConcurrentWrites(t *testing.T) {
@ -890,3 +991,26 @@ 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

@ -0,0 +1,180 @@
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},
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.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")
}
}

View file

@ -887,3 +887,66 @@ 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,
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,
size, last_modified, fetched_at, created_at, updated_at)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
ON CONFLICT(ecosystem, name) DO UPDATE SET
storage_path = EXCLUDED.storage_path,
etag = EXCLUDED.etag,
content_type = EXCLUDED.content_type,
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,
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,
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.Size, entry.LastModified, entry.FetchedAt, now, now,
)
if err != nil {
return fmt.Errorf("upserting metadata cache: %w", err)
}
return nil
}

View file

@ -1,6 +1,10 @@
package database package database
import "fmt" import (
"fmt"
"strings"
"time"
)
const postgresTimestamp = "TIMESTAMP" const postgresTimestamp = "TIMESTAMP"
@ -86,6 +90,26 @@ 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,
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 = `
@ -166,6 +190,26 @@ 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,
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.
@ -232,6 +276,11 @@ 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()
} }
@ -292,24 +341,136 @@ func (db *DB) HasColumn(table, column string) (bool, error) {
return exists, err return exists, err
} }
// MigrateSchema adds missing columns to existing tables for backward compatibility. // migration represents a named schema migration.
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},
}
// 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 = "TIMESTAMP"
} else {
ts = "DATETIME"
}
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 {
// Check and add missing columns to packages table applied, err := db.appliedMigrations()
packagesColumns := map[string]string{ if err != nil {
"registry_url": "TEXT", return err
"supplier_name": "TEXT", }
"supplier_type": "TEXT",
"source": "TEXT", // If the migrations table didn't exist, create it now.
"enriched_at": "DATETIME", if applied == nil {
"vulns_synced_at": "DATETIME", if err := db.createMigrationsTable(); err != nil {
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": "TEXT",
"supplier_name": "TEXT",
"supplier_type": "TEXT",
"source": "TEXT",
"enriched_at": "DATETIME",
"vulns_synced_at": "DATETIME",
} }
if db.dialect == DialectPostgres { if db.dialect == DialectPostgres {
packagesColumns["enriched_at"] = postgresTimestamp columns["enriched_at"] = postgresTimestamp
packagesColumns["vulns_synced_at"] = postgresTimestamp columns["vulns_synced_at"] = postgresTimestamp
} }
for column, colType := range packagesColumns { for column, colType := range columns {
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)
@ -321,9 +482,11 @@ func (db *DB) MigrateSchema() error {
} }
} }
} }
return nil
}
// Check and add missing columns to versions table func migrateAddVersionsEnrichmentColumns(db *DB) error {
versionsColumns := map[string]string{ columns := map[string]string{
"integrity": "TEXT", "integrity": "TEXT",
"yanked": "INTEGER DEFAULT 0", "yanked": "INTEGER DEFAULT 0",
"source": "TEXT", "source": "TEXT",
@ -331,11 +494,11 @@ func (db *DB) MigrateSchema() error {
} }
if db.dialect == DialectPostgres { if db.dialect == DialectPostgres {
versionsColumns["yanked"] = "BOOLEAN DEFAULT FALSE" columns["yanked"] = "BOOLEAN DEFAULT FALSE"
versionsColumns["enriched_at"] = postgresTimestamp columns["enriched_at"] = postgresTimestamp
} }
for column, colType := range versionsColumns { for column, colType := range columns {
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)
@ -347,62 +510,121 @@ func (db *DB) MigrateSchema() error {
} }
} }
} }
return nil
}
// Ensure artifacts table exists func migrateEnsureArtifactsTable(db *DB) error {
if err := db.EnsureArtifactsTable(); err != nil { return db.EnsureArtifactsTable()
return fmt.Errorf("ensuring artifacts table: %w", err) }
}
// Ensure vulnerabilities table exists func migrateEnsureVulnerabilitiesTable(db *DB) error {
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 {
var vulnSchema string return nil
if db.dialect == DialectPostgres { }
vulnSchema = `
CREATE TABLE vulnerabilities ( var vulnSchema string
id SERIAL PRIMARY KEY, if db.dialect == DialectPostgres {
vuln_id TEXT NOT NULL, vulnSchema = `
ecosystem TEXT NOT NULL, CREATE TABLE vulnerabilities (
package_name TEXT NOT NULL, id SERIAL PRIMARY KEY,
severity TEXT, vuln_id TEXT NOT NULL,
summary TEXT, ecosystem TEXT NOT NULL,
fixed_version TEXT, package_name TEXT NOT NULL,
cvss_score REAL, severity TEXT,
"references" TEXT, summary TEXT,
fetched_at TIMESTAMP, fixed_version TEXT,
created_at TIMESTAMP, cvss_score REAL,
updated_at TIMESTAMP "references" TEXT,
); fetched_at TIMESTAMP,
CREATE UNIQUE INDEX IF NOT EXISTS idx_vulns_id_pkg ON vulnerabilities(vuln_id, ecosystem, package_name); created_at TIMESTAMP,
CREATE INDEX IF NOT EXISTS idx_vulns_ecosystem_pkg ON vulnerabilities(ecosystem, package_name); updated_at TIMESTAMP
` );
} else { CREATE UNIQUE INDEX IF NOT EXISTS idx_vulns_id_pkg ON vulnerabilities(vuln_id, ecosystem, package_name);
vulnSchema = ` CREATE INDEX IF NOT EXISTS idx_vulns_ecosystem_pkg ON vulnerabilities(ecosystem, package_name);
CREATE TABLE vulnerabilities ( `
id INTEGER PRIMARY KEY, } else {
vuln_id TEXT NOT NULL, vulnSchema = `
ecosystem TEXT NOT NULL, CREATE TABLE vulnerabilities (
package_name TEXT NOT NULL, id INTEGER PRIMARY KEY,
severity TEXT, vuln_id TEXT NOT NULL,
summary TEXT, ecosystem TEXT NOT NULL,
fixed_version TEXT, package_name TEXT NOT NULL,
cvss_score REAL, severity TEXT,
"references" TEXT, summary TEXT,
fetched_at DATETIME, fixed_version TEXT,
created_at DATETIME, cvss_score REAL,
updated_at DATETIME "references" TEXT,
); fetched_at DATETIME,
CREATE UNIQUE INDEX IF NOT EXISTS idx_vulns_id_pkg ON vulnerabilities(vuln_id, ecosystem, package_name); created_at DATETIME,
CREATE INDEX IF NOT EXISTS idx_vulns_ecosystem_pkg ON vulnerabilities(ecosystem, package_name); updated_at DATETIME
` );
} CREATE UNIQUE INDEX IF NOT EXISTS idx_vulns_id_pkg ON vulnerabilities(vuln_id, ecosystem, package_name);
if _, err := db.Exec(vulnSchema); err != nil { CREATE INDEX IF NOT EXISTS idx_vulns_ecosystem_pkg ON vulnerabilities(ecosystem, package_name);
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()
}
// 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,
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,
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

@ -76,18 +76,33 @@ func (a *Artifact) IsCached() bool {
return a.StoragePath.Valid && a.FetchedAt.Valid return a.StoragePath.Valid && a.FetchedAt.Valid
} }
// Vulnerability represents a cached vulnerability record. // MetadataCacheEntry represents a cached metadata blob for offline serving.
type Vulnerability struct { type MetadataCacheEntry struct {
ID int64 `db:"id" json:"id"` ID int64 `db:"id" json:"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"` Name string `db:"name" json:"name"`
Severity sql.NullString `db:"severity" json:"severity,omitempty"` StoragePath string `db:"storage_path" json:"storage_path"`
Summary sql.NullString `db:"summary" json:"summary,omitempty"` ETag sql.NullString `db:"etag" json:"etag,omitempty"`
FixedVersion sql.NullString `db:"fixed_version" json:"fixed_version,omitempty"` ContentType sql.NullString `db:"content_type" json:"content_type,omitempty"`
CVSSScore sql.NullFloat64 `db:"cvss_score" json:"cvss_score,omitempty"` Size sql.NullInt64 `db:"size" json:"size,omitempty"`
References sql.NullString `db:"references" json:"references,omitempty"` LastModified sql.NullTime `db:"last_modified" json:"last_modified,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"`
} }
// Vulnerability represents a cached vulnerability record.
type Vulnerability struct {
ID int64 `db:"id" json:"id"`
VulnID string `db:"vuln_id" json:"vuln_id"`
Ecosystem string `db:"ecosystem" json:"ecosystem"`
PackageName string `db:"package_name" json:"package_name"`
Severity sql.NullString `db:"severity" json:"severity,omitempty"`
Summary sql.NullString `db:"summary" json:"summary,omitempty"`
FixedVersion sql.NullString `db:"fixed_version" json:"fixed_version,omitempty"`
CVSSScore sql.NullFloat64 `db:"cvss_score" json:"cvss_score,omitempty"`
References sql.NullString `db:"references" json:"references,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"`
}

View file

@ -3,8 +3,8 @@ package handler
import ( import (
"bufio" "bufio"
"encoding/json" "encoding/json"
"errors"
"fmt" "fmt"
"io"
"net/http" "net/http"
"strings" "strings"
"time" "time"
@ -88,44 +88,27 @@ 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)
req, err := http.NewRequestWithContext(r.Context(), http.MethodGet, upstreamURL, nil) body, contentType, err := h.proxy.FetchOrCacheMetadata(r.Context(), "cargo", name, upstreamURL, "text/plain")
if err != nil {
http.Error(w, "internal error", http.StatusInternalServerError)
return
}
resp, err := h.proxy.HTTPClient.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 resp.StatusCode == http.StatusNotFound { if contentType == "" {
http.Error(w, "not found", http.StatusNotFound) contentType = "text/plain; charset=utf-8"
return
}
if resp.StatusCode != http.StatusOK {
http.Error(w, fmt.Sprintf("upstream returned %d", resp.StatusCode), http.StatusBadGateway)
return
} }
// Copy headers and body w.Header().Set("Content-Type", contentType)
w.Header().Set("Content-Type", "text/plain; charset=utf-8") w.WriteHeader(http.StatusOK)
if etag := resp.Header.Get("ETag"); etag != "" { h.applyCooldownFiltering(w, body)
w.Header().Set("ETag", etag)
}
if lastMod := resp.Header.Get("Last-Modified"); lastMod != "" {
w.Header().Set("Last-Modified", lastMod)
}
h.applyCooldownFiltering(w, resp.Body)
} }
type crateIndexEntry struct { type crateIndexEntry struct {
@ -134,56 +117,45 @@ type crateIndexEntry struct {
PublishTime string `json:"pubtime,omitempty"` PublishTime string `json:"pubtime,omitempty"`
} }
func (h *CargoHandler) applyCooldownFiltering(downstreamResponse io.Writer, upstreamBody io.Reader) { func (h *CargoHandler) applyCooldownFiltering(downstreamResponse http.ResponseWriter, body []byte) {
if h.proxy.Cooldown == nil || !h.proxy.Cooldown.Enabled() { if h.proxy.Cooldown == nil || !h.proxy.Cooldown.Enabled() {
// not using cooldowns, just copy the upstream to the downstream _, _ = downstreamResponse.Write(body)
_, _ = io.Copy(downstreamResponse, upstreamBody)
return return
} }
// create a scanner on the body of the http response scanner := bufio.NewScanner(strings.NewReader(string(body)))
requestScanner := bufio.NewScanner(upstreamBody)
// the response is newline-delimited JSON, loop through each line for scanner.Scan() {
for requestScanner.Scan() { line := scanner.Text()
line := requestScanner.Text()
// decode the line
var crate crateIndexEntry var crate crateIndexEntry
err := json.Unmarshal([]byte(line), &crate) err := json.Unmarshal([]byte(line), &crate)
if err != nil { if err != nil {
// if there is an error parsing this line then exclude it and move to the next entry
h.proxy.Logger.Error("failed to parse json entry in index", "error", err) h.proxy.Logger.Error("failed to parse json entry in index", "error", err)
continue continue
} }
// parse publish time
publishedAt, err := time.Parse(time.RFC3339, crate.PublishTime) publishedAt, err := time.Parse(time.RFC3339, crate.PublishTime)
if crate.PublishTime == "" || err != nil { if crate.PublishTime == "" || err != nil {
// publish time is empty/missing/invalid, presumably was published before pubtime was added as a field
// write line to response
_, _ = downstreamResponse.Write([]byte(line + "\n")) _, _ = downstreamResponse.Write([]byte(line + "\n"))
continue continue
} }
// make PURL
cratePURL := purl.MakePURLString("cargo", crate.Name, "") cratePURL := purl.MakePURLString("cargo", crate.Name, "")
if !h.proxy.Cooldown.IsAllowed("cargo", cratePURL, publishedAt) { if !h.proxy.Cooldown.IsAllowed("cargo", cratePURL, publishedAt) {
// crate is not allowed, move to next crate
h.proxy.Logger.Info("cooldown: filtering cargo version", h.proxy.Logger.Info("cooldown: filtering cargo version",
"crate", crate.Name, "version", crate.Version, "crate", crate.Name, "version", crate.Version,
"published", crate.PublishTime) "published", crate.PublishTime)
continue continue
} }
// crate passes, write to response
_, _ = downstreamResponse.Write([]byte(line + "\n")) _, _ = downstreamResponse.Write([]byte(line + "\n"))
} }
if err := requestScanner.Err(); err != nil { if err := scanner.Err(); err != nil {
h.proxy.Logger.Error("error reading index response", "error", err) h.proxy.Logger.Error("error reading index response", "error", err)
} }
} }

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