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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -209,6 +209,8 @@ The Alpine URL is one repository architecture directory, such as `https://dl-cdn

The Debian URL is an archive root with the suites, components and architectures to read as query parameters, which archives don't use: `https://deb.debian.org/debian?suites=bookworm,bookworm-updates&components=main&architectures=amd64`. `components` defaults to `main`. An archive under another root, such as `https://deb.debian.org/debian-security` with suite `bookworm-security`, is a registry of its own. The client reads `dists/<suite>/InRelease`, falling back to `Release`, and checks each `Packages` index against its SHA256 there; without a keyring (below), a suite with neither is read unchecked. It tries `Packages.xz`, `Packages.gz` and `Packages` in that order, of those the Release lists, and decodes them as a stream. Signatures are checked only for an archive given a keyring with `registries.WithDebianKeyring(archiveURL, keyring)`, a binary OpenPGP keyring such as `/usr/share/keyrings/debian-archive-keyring.gpg`, or one or more armored blocks: `InRelease` must then be clearsigned by one of its keys, a `Release` without `InRelease` needs a valid `Release.gpg`, and a suite with neither, or with a signed Release that lists no SHA256 sums or whose `Valid-Until` has passed, is refused. Of several signatures, one that verifies is enough, as in apt. Only the signed text is read. Without a keyring, nothing is verified, so the SHA256 checks only catch indexes that don't match the Release served with them. Each artifact records `arch` and `distro`, the suite's codename without `-updates` or `-security`, for the `arch` and `distro` PURL qualifiers. Versions keep their epoch (`1:9.2p1-2+deb12u3`) and compare with the `deb` scheme. `fetch.Resolver` also takes a `distro` given as the release, as trivy and syft write it (`debian-12`, `debian-12.4`, `ubuntu-22.04`), and a version without its epoch, or with trivy's `epoch` qualifier; a number listed with two epochs needs the epoch, and is otherwise refused with `fetch.ErrAmbiguousVersion`. Source packages (`architectures=source`) are not supported. In a PURL, `repository_url` is this whole URL, query included, so its `?`, `=`, `&` and `,` are percent-encoded.

`https://snapshot.debian.org?architectures=amd64` reads [snapshot.debian.org](https://snapshot.debian.org)'s API instead of an archive's indexes, so it finds versions that have left the archive; it takes architectures but no suites or components. It is Debian only, and nothing falls back to it when a version is missing from another archive. `FetchVersions` lists a binary package's versions without artifacts, since each version's files take another request; `FetchArtifacts` (or `FetchVersion`) lists them for one version, and `fetch.Resolver` does that for the version it picks. An artifact's URL is `https://snapshot.debian.org/file/<sha1>` and its integrity is that `sha1-` hash, which snapshot.debian.org names the file by, not a SHA256 checked against a signed index. Artifacts record `arch`, the `archive` the file was first seen in (`debian`, `debian-security`, …) and `first_seen`, but no `distro`. `FetchDependencies` and `FetchMaintainers` return errors wrapping `errors.ErrUnsupported`, since the API lists neither. A dated archive under it, such as `https://snapshot.debian.org/archive/debian/20240101T000000Z?suites=bookworm&architectures=amd64`, is an ordinary archive.

The RPM URL is one repository, the directory that holds `repodata/`, such as `https://dl.fedoraproject.org/pub/fedora/linux/releases/43/Everything/x86_64/os`. The client doesn't pick a release, variant or architecture from a mirror root, and doesn't follow mirror lists or metalinks. It reads `repodata/repomd.xml`, follows its `primary` entry, checks that file against the checksum and size listed there, and decodes `.zst`, `.xz`, `.gz` or plain XML as a stream. Repository metadata doesn't name its distribution, so the `distro` to record on artifacts is given as a query parameter: `.../x86_64/os?distro=fedora-43`. Each artifact records `arch`, `epoch` and that `distro`, with the package's own checksum as integrity (`sha256-...`). The version number is `version-release`, as in the `rpm` PURL type, where the epoch is a qualifier; versions are ordered by epoch, version and release. Dependencies are the requirements that name packages, leaving out file paths, sonames and capabilities in parentheses such as `rpmlib(...)`; a constraint on a package is listed once per distinct constraint. A virtual capability such as `webserver` can't be told from a package name and is listed as one. In a PURL, `repository_url` is the whole URL, `distro` parameter included, so its `?` and `=` are percent-encoded.

GitHub Actions are git repositories, so `FetchPackage` reads `/repos/{owner}/{repo}` and `FetchVersions` lists tags from the GitHub REST API. Unauthenticated requests are limited to 60 per hour. A subdirectory action such as `pkg:githubactions/github/codeql-action/init@v3` resolves to the `github/codeql-action` repository. `URLs().Download` returns the `/archive/{ref}.tar.gz` source tarball for any tag, branch or commit SHA. GitHub doesn't guarantee these tarballs are byte-stable, so versions carry no `Integrity`. Dependencies and maintainers return an error wrapping `errors.ErrUnsupported`. For GitHub Enterprise Server, pass the `/api/v3` API root as the base URL.
Expand Down
96 changes: 96 additions & 0 deletions fetch/artifact_fetcher_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
package fetch

import (
"context"
"errors"
"reflect"
"testing"

"github.com/git-pkgs/registries"
"github.com/git-pkgs/registries/client"
)

// listingRegistry lists versions without artifacts and returns them from
// FetchArtifacts, as the deb client does for snapshot.debian.org.
type listingRegistry struct {
versions []registries.Version
full map[string]*registries.Version
err error
fetched []string
}

func (l *listingRegistry) Ecosystem() string { return "deb" }
func (l *listingRegistry) URLs() client.URLBuilder { return &client.BaseURLs{} } //nolint:ireturn // satisfying Registry interface
func (l *listingRegistry) FetchVersions(ctx context.Context, name string) ([]registries.Version, error) {
return l.versions, nil
}

func (l *listingRegistry) FetchArtifacts(ctx context.Context, name, version string) ([]registries.Artifact, error) {
l.fetched = append(l.fetched, name+"@"+version)
if l.err != nil {
return nil, l.err
}
return l.full[version].Artifacts, nil
}

func TestResolveFetchesArtifactsOfAListedVersion(t *testing.T) {
const number = "1:9.2p1-2+deb12u3"
file := func(arch, hash string) registries.Artifact {
return registries.Artifact{
URL: "https://snapshot.debian.org/file/" + hash,
Filename: "openssh-client_9.2p1-2+deb12u3_" + arch + ".deb",
Integrity: "sha1-" + hash,
Size: 1,
Metadata: map[string]any{"arch": arch},
}
}
reg := &listingRegistry{
versions: []registries.Version{{Number: "1:9.2p1-2+deb12u10"}, {Number: number}},
full: map[string]*registries.Version{number: {Number: number, Artifacts: []registries.Artifact{
file("amd64", "81171c850daaaedc27dabae3717dc20943ef371a"),
file("arm64", "cbd60f5bdf4f576681cb75f888761abc94cb72ca"),
}}},
}
r := NewResolver()
r.RegisterRegistry(reg)

// Given without its epoch, as scanners write it.
info, err := r.ResolveWithOptions(context.Background(), "deb", "debian/openssh-client", "9.2p1-2+deb12u3",
ResolveOptions{Qualifiers: map[string]string{"arch": "arm64"}})
if err != nil {
t.Fatal(err)
}
if info.URL != "https://snapshot.debian.org/file/cbd60f5bdf4f576681cb75f888761abc94cb72ca" ||
info.Integrity != "sha1-cbd60f5bdf4f576681cb75f888761abc94cb72ca" {
t.Errorf("info = %+v, want the arm64 file", info)
}
if want := []string{"debian/openssh-client@" + number}; !reflect.DeepEqual(reg.fetched, want) {
t.Errorf("fetched %v, want %v", reg.fetched, want)
}
}

func TestResolveReportsAFailedVersionFetch(t *testing.T) {
boom := errors.New("boom")
reg := &listingRegistry{versions: []registries.Version{{Number: "1.0"}}, err: boom}
r := NewResolver()
r.RegisterRegistry(reg)
if _, err := r.ResolveWithOptions(context.Background(), "deb", "x", "1.0",
ResolveOptions{Qualifiers: map[string]string{"arch": "amd64"}}); !errors.Is(err, boom) {
t.Errorf("err = %v, want boom", err)
}
}

func TestResolveKeepsListedArtifacts(t *testing.T) {
listed := registries.Artifact{URL: "https://deb.debian.org/debian/pool/x.deb", Filename: "x.deb", Metadata: map[string]any{"arch": "amd64"}}
reg := &listingRegistry{versions: []registries.Version{{Number: "1.0", Artifacts: []registries.Artifact{listed}}}}
r := NewResolver()
r.RegisterRegistry(reg)
info, err := r.ResolveWithOptions(context.Background(), "deb", "x", "1.0",
ResolveOptions{Qualifiers: map[string]string{"arch": "amd64"}})
if err != nil || info.URL != listed.URL {
t.Fatalf("info = %+v, %v", info, err)
}
if len(reg.fetched) != 0 {
t.Errorf("fetched %v, want no FetchArtifacts for a version with artifacts", reg.fetched)
}
}
79 changes: 79 additions & 0 deletions fetch/deb_resolver_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@ import (
"errors"
"net/http"
"net/http/httptest"
"net/url"
"os"
"path/filepath"
"testing"

"github.com/git-pkgs/registries"
Expand Down Expand Up @@ -184,3 +187,79 @@ func TestResolveDebVersionWithoutEpoch(t *testing.T) {
}
}
}

// snapshotFixtures are the snapshot.debian.org API responses the deb
// package's tests record, by request path.
var snapshotFixtures = map[string]string{
"/mr/binary/openssh-client/": "binary-openssh-client.json",
"/mr/binary/openssh-client/1:9.2p1-2+deb12u3/binfiles": "binfiles-openssh-client.json",
}

// snapshotHostTransport sends every request to target, so a registry for
// https://snapshot.debian.org reads the recorded responses.
type snapshotHostTransport struct{ target *url.URL }

func (t snapshotHostTransport) RoundTrip(req *http.Request) (*http.Response, error) {
req = req.Clone(req.Context())
req.URL.Scheme, req.URL.Host = t.target.Scheme, t.target.Host
return http.DefaultTransport.RoundTrip(req)
}

// snapshotResolver resolves through the deb registry for
// snapshot.debian.org with architectures, serving its API from the
// recorded responses.
func snapshotResolver(t *testing.T, architectures string) *Resolver {
t.Helper()
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
name, ok := snapshotFixtures[r.URL.Path]
if !ok {
http.NotFound(w, r)
return
}
body, err := os.ReadFile(filepath.Join("..", "internal", "deb", "testdata", "snapshot", name))
if err != nil {
t.Error(err)
}
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write(body)
}))
t.Cleanup(server.Close)
target, _ := url.Parse(server.URL)
client := registries.DefaultClient()
client.HTTPClient = &http.Client{Transport: snapshotHostTransport{target}}
reg, err := registries.New("deb", "https://snapshot.debian.org?architectures="+architectures, client)
if err != nil {
t.Fatal(err)
}
r := NewResolver()
r.RegisterRegistry(reg)
return r
}

// A scanner's PURL carries a distro, which snapshot artifacts don't record,
// and a version without its epoch.
func TestResolveDebFromSnapshot(t *testing.T) {
r := snapshotResolver(t, "amd64")
info, err := r.ResolveWithOptions(context.Background(), "deb", "debian/openssh-client", "9.2p1-2+deb12u3",
ResolveOptions{Qualifiers: map[string]string{"arch": "amd64", "distro": "debian-12"}})
if err != nil {
t.Fatalf("Resolve: %v", err)
}
want := ArtifactInfo{
URL: "https://snapshot.debian.org/file/81171c850daaaedc27dabae3717dc20943ef371a",
Filename: "openssh-client_9.2p1-2+deb12u3_amd64.deb",
Integrity: "sha1-81171c850daaaedc27dabae3717dc20943ef371a",
Size: 990808,
}
if *info != want {
t.Errorf("info = %+v, want %+v", *info, want)
}
}

func TestResolveDebFromSnapshotWithoutFileForArchitecture(t *testing.T) {
r := snapshotResolver(t, "riscv64")
_, err := r.ResolveWithOptions(context.Background(), "deb", "debian/openssh-client", "9.2p1-2+deb12u3", ResolveOptions{})
if !errors.Is(err, ErrNoMatchingArtifact) {
t.Errorf("err = %v, want ErrNoMatchingArtifact", err)
}
}
19 changes: 19 additions & 0 deletions fetch/resolver.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,12 @@ type Registry interface {
URLs() client.URLBuilder
}

// artifactFetcher is a Registry whose FetchVersions can leave out a
// version's artifacts, which FetchArtifacts then lists.
type artifactFetcher interface {
FetchArtifacts(ctx context.Context, name, version string) ([]registries.Artifact, error)
}

// defaultBaseURLs are the public registry hosts used when no registry is
// registered for an ecosystem and WithBaseURLs does not override them.
var defaultBaseURLs = map[string]string{
Expand Down Expand Up @@ -272,6 +278,19 @@ func (r *Resolver) resolveFromMetadata(
if err != nil {
return nil, err
}
// A registry that lists versions without their artifacts, such as deb
// on snapshot.debian.org, fetches them for the version found.
if fetcher, ok := reg.(artifactFetcher); ok && len(v.Artifacts) == 0 {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A version that exists on snapshot but has no file for the configured architectures comes back from FetchArtifacts empty, then falls through the download_url/tarball lookups and returns ErrNoDownloadURL. Return ErrNoMatchingArtifact when FetchArtifacts succeeds with nothing, with a test case for it.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in d8d434c: a version FetchArtifacts lists nothing for is now ErrNoMatchingArtifact, tested with a snapshot registry for riscv64.

v.Artifacts, err = fetcher.FetchArtifacts(ctx, name, v.Number)
if err != nil {
return nil, fmt.Errorf("fetching artifacts: %w", err)
}
// The version exists but has no file the registry is set to
// read, such as one for another architecture.
if len(v.Artifacts) == 0 {
return nil, ErrNoMatchingArtifact
}
}

if len(v.Artifacts) > 0 {
return r.selectArtifact(ctx, v.Artifacts, options)
Expand Down
54 changes: 54 additions & 0 deletions internal/deb/deb.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,11 @@ func init() {
// components defaults to main. An archive under another root, such as
// deb.debian.org/debian-security, is a Registry of its own.
//
// snapshot.debian.org's root, with architectures only, reads its API
// instead, and so finds versions that have left the archive:
//
// https://snapshot.debian.org?architectures=amd64
//
// The indexes are downloaded once per Registry and kept for its lifetime,
// so callers looking up many packages should reuse one Registry.
type Registry struct {
Expand All @@ -75,6 +80,7 @@ type Registry struct {
components []string
architectures []string
configErr error
snapshot bool
client *core.Client
urls *URLs
// keyring, when set, is what the Release files must be signed with.
Expand Down Expand Up @@ -105,6 +111,9 @@ func (r *Registry) repositoryURL() string {
if r.archiveURL == "" {
return ""
}
if r.snapshot {
return r.archiveURL + "?architectures=" + strings.Join(r.architectures, ",")
}
return r.archiveURL + "?suites=" + strings.Join(r.suites, ",") +
"&components=" + strings.Join(r.components, ",") +
"&architectures=" + strings.Join(r.architectures, ",")
Expand All @@ -116,6 +125,9 @@ func (r *Registry) configure(baseURL string) error {
return fmt.Errorf("%w: %q is not an archive URL", ErrInvalidConfig, baseURL)
}
q := u.Query()
if isSnapshotRoot(u) {
return r.configureSnapshot(q, baseURL)
}
r.archiveURL = archiveRoot(u)
r.suites = splitList(q.Get("suites"))
r.components = splitList(q.Get("components"))
Expand Down Expand Up @@ -409,6 +421,9 @@ func (r *Registry) lookup(ctx context.Context, name string) ([]record, error) {
}

func (r *Registry) FetchPackage(ctx context.Context, name string) (*core.Package, error) {
if r.snapshot {
return r.snapshotPackage(ctx, name)
}
recs, err := r.lookup(ctx, name)
if err != nil {
return nil, err
Expand All @@ -430,7 +445,13 @@ func (r *Registry) FetchPackage(ctx context.Context, name string) (*core.Package

// FetchVersions returns one Version per version number, newest first, with
// an artifact for each architecture and suite it was found in.
//
// On snapshot.debian.org, versions come without artifacts, which
// FetchVersion lists.
func (r *Registry) FetchVersions(ctx context.Context, name string) ([]core.Version, error) {
if r.snapshot {
return r.snapshotVersions(ctx, name)
}
recs, err := r.lookup(ctx, name)
if err != nil {
return nil, err
Expand Down Expand Up @@ -477,7 +498,37 @@ func (r *Registry) artifact(rec record) (core.Artifact, bool) {
return artifact, true
}

// FetchVersion returns one version with its artifacts.
func (r *Registry) FetchVersion(ctx context.Context, name, version string) (*core.Version, error) {
if r.snapshot {
return r.snapshotVersion(ctx, name, version)
}
versions, err := r.FetchVersions(ctx, name)
if err != nil {
return nil, err
}
for i := range versions {
if versions[i].Number == version {
return &versions[i], nil
}
}
return nil, &core.NotFoundError{Ecosystem: ecosystem, Name: name, Version: version}
}

// FetchArtifacts returns a version's artifacts, which FetchVersions leaves
// out on snapshot.debian.org.
func (r *Registry) FetchArtifacts(ctx context.Context, name, version string) ([]core.Artifact, error) {
v, err := r.FetchVersion(ctx, name, version)
if err != nil {
return nil, err
}
return v.Artifacts, nil
}

func (r *Registry) FetchDependencies(ctx context.Context, name, version string) ([]core.Dependency, error) {
if r.snapshot {
return nil, fmt.Errorf("%w: %s lists no dependencies", errors.ErrUnsupported, snapshotHost)
}
recs, err := r.lookup(ctx, name)
if err != nil {
return nil, err
Expand All @@ -496,6 +547,9 @@ func (r *Registry) FetchDependencies(ctx context.Context, name, version string)
}

func (r *Registry) FetchMaintainers(ctx context.Context, name string) ([]core.Maintainer, error) {
if r.snapshot {
return nil, fmt.Errorf("%w: %s lists no maintainers", errors.ErrUnsupported, snapshotHost)
}
recs, err := r.lookup(ctx, name)
if err != nil {
return nil, err
Expand Down
Loading