diff --git a/README.md b/README.md index a3d7399..79cf8f0 100644 --- a/README.md +++ b/README.md @@ -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//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/` 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. diff --git a/fetch/artifact_fetcher_test.go b/fetch/artifact_fetcher_test.go new file mode 100644 index 0000000..3219cd5 --- /dev/null +++ b/fetch/artifact_fetcher_test.go @@ -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) + } +} diff --git a/fetch/deb_resolver_test.go b/fetch/deb_resolver_test.go index e36719f..8efb03f 100644 --- a/fetch/deb_resolver_test.go +++ b/fetch/deb_resolver_test.go @@ -7,6 +7,9 @@ import ( "errors" "net/http" "net/http/httptest" + "net/url" + "os" + "path/filepath" "testing" "github.com/git-pkgs/registries" @@ -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) + } +} diff --git a/fetch/resolver.go b/fetch/resolver.go index 49593e2..4232344 100644 --- a/fetch/resolver.go +++ b/fetch/resolver.go @@ -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{ @@ -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 { + 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) diff --git a/internal/deb/deb.go b/internal/deb/deb.go index ee00381..453528d 100644 --- a/internal/deb/deb.go +++ b/internal/deb/deb.go @@ -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 { @@ -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. @@ -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, ",") @@ -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")) @@ -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 @@ -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 @@ -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 @@ -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 diff --git a/internal/deb/snapshot.go b/internal/deb/snapshot.go new file mode 100644 index 0000000..cb8f824 --- /dev/null +++ b/internal/deb/snapshot.go @@ -0,0 +1,182 @@ +package deb + +import ( + "context" + "fmt" + "net/url" + "regexp" + "sort" + "strings" + + "github.com/git-pkgs/registries/internal/core" + "github.com/git-pkgs/vers" +) + +// snapshotHost is snapshot.debian.org, which keeps every file Debian has +// published. Its root, as the archive URL, selects the snapshot backend: +// versions come from its machine-readable API rather than from Packages +// indexes. A dated archive under it (/archive/debian/) is an +// ordinary archive. +const snapshotHost = "snapshot.debian.org" + +// sha1Pattern matches the SHA-1 snapshot.debian.org names files by. +var sha1Pattern = regexp.MustCompile(`^[0-9a-f]{40}$`) + +// isSnapshotRoot reports whether u is snapshot.debian.org's root. +func isSnapshotRoot(u *url.URL) bool { + return u.Scheme == "https" && strings.EqualFold(u.Host, snapshotHost) && (u.Path == "" || u.Path == "/") +} + +// configureSnapshot checks the configuration of the snapshot backend: +// architectures only, since the API lists a version's files whatever +// suite they were in. +func (r *Registry) configureSnapshot(q url.Values, baseURL string) error { + r.snapshot = true + r.archiveURL = "https://" + snapshotHost + r.architectures = splitList(q.Get("architectures")) + switch { + case q.Has("suites") || q.Has("components"): + return fmt.Errorf("%w: %s takes no suites or components in %q", ErrInvalidConfig, snapshotHost, baseURL) + case len(r.architectures) == 0: + return fmt.Errorf("%w: no architectures in %q", ErrInvalidConfig, baseURL) + } + for _, arch := range r.architectures { + if !safeSegment(arch) { + return fmt.Errorf("%w: %q", ErrInvalidConfig, arch) + } + if arch == "source" { + return fmt.Errorf("%w: source packages are not supported", ErrInvalidConfig) + } + } + return nil +} + +type snapshotVersions struct { + Result []struct { + BinaryVersion string `json:"binary_version"` + Source string `json:"source"` + Version string `json:"version"` + } `json:"result"` +} + +type snapshotBinfiles struct { + Result []struct { + Architecture string `json:"architecture"` + Hash string `json:"hash"` + } `json:"result"` + Fileinfo map[string][]struct { + ArchiveName string `json:"archive_name"` + FirstSeen string `json:"first_seen"` + Name string `json:"name"` + Size int64 `json:"size"` + } `json:"fileinfo"` +} + +// snapshotGet reads a snapshot API document, returning a NotFoundError +// for name and version on a 404. +func (r *Registry) snapshotGet(ctx context.Context, apiPath, name, version string, v any) error { + if r.configErr != nil { + return r.configErr + } + err := r.client.GetJSON(ctx, r.archiveURL+apiPath, v) + if isNotFound(err) { + return &core.NotFoundError{Ecosystem: ecosystem, Name: name, Version: version} + } + return err +} + +// snapshotVersions lists a binary package's versions, newest first. Each +// takes another request to list its files, so they come without +// artifacts; FetchVersion adds them. +func (r *Registry) snapshotVersions(ctx context.Context, name string) ([]core.Version, error) { + _, pkg := splitName(name) + var doc snapshotVersions + if err := r.snapshotGet(ctx, "/mr/binary/"+url.PathEscape(pkg)+"/", name, "", &doc); err != nil { + return nil, err + } + seen := map[string]bool{} + var versions []core.Version + for _, entry := range doc.Result { + if entry.BinaryVersion == "" || seen[entry.BinaryVersion] { + continue + } + seen[entry.BinaryVersion] = true + versions = append(versions, core.Version{ + Number: entry.BinaryVersion, + Metadata: map[string]any{"source": entry.Source, "source_version": entry.Version}, + }) + } + if len(versions) == 0 { + return nil, &core.NotFoundError{Ecosystem: ecosystem, Name: name} + } + sort.SliceStable(versions, func(i, j int) bool { + return vers.CompareWithScheme(versions[i].Number, versions[j].Number, ecosystem) > 0 + }) + return versions, nil +} + +// snapshotVersion lists a version's files for the configured +// architectures, and Architecture: all. Their integrity is the SHA-1 +// snapshot.debian.org names them by, not a SHA256 from a signed index. +func (r *Registry) snapshotVersion(ctx context.Context, name, version string) (*core.Version, error) { + _, pkg := splitName(name) + apiPath := "/mr/binary/" + url.PathEscape(pkg) + "/" + url.PathEscape(version) + "/binfiles?fileinfo=1" + var doc snapshotBinfiles + if err := r.snapshotGet(ctx, apiPath, name, version, &doc); err != nil { + return nil, err + } + v := &core.Version{Number: version} + for _, file := range doc.Result { + if !r.wantsArch(file.Architecture) || !sha1Pattern.MatchString(file.Hash) { + continue + } + infos := doc.Fileinfo[file.Hash] + if len(infos) == 0 || !safeFilename(infos[0].Name) { + continue + } + info := infos[0] + v.Artifacts = append(v.Artifacts, core.Artifact{ + URL: r.archiveURL + "/file/" + file.Hash, + Filename: info.Name, + Size: info.Size, + Integrity: "sha1-" + file.Hash, + Metadata: map[string]any{ + "arch": file.Architecture, + "archive": info.ArchiveName, + "first_seen": info.FirstSeen, + }, + }) + } + return v, nil +} + +func (r *Registry) wantsArch(arch string) bool { + if arch == archAll { + return true + } + for _, want := range r.architectures { + if arch == want { + return true + } + } + return false +} + +// safeFilename refuses a file name that isn't a plain name. +func safeFilename(name string) bool { + return name != "" && safeSegment(name) && !strings.ContainsAny(name, "\x00") +} + +func (r *Registry) snapshotPackage(ctx context.Context, name string) (*core.Package, error) { + versions, err := r.snapshotVersions(ctx, name) + if err != nil { + return nil, err + } + namespace, pkg := splitName(name) + return &core.Package{ + Name: pkg, + Namespace: namespace, + LatestVersion: versions[0].Number, + Metadata: map[string]any{"source": versions[0].Metadata["source"]}, + }, nil +} diff --git a/internal/deb/snapshot_test.go b/internal/deb/snapshot_test.go new file mode 100644 index 0000000..2c1346c --- /dev/null +++ b/internal/deb/snapshot_test.go @@ -0,0 +1,366 @@ +package deb + +import ( + "context" + "errors" + "net/http" + "net/http/httptest" + "net/url" + "os" + "reflect" + "sync" + "testing" + + "github.com/git-pkgs/registries/internal/core" +) + +// snapshotFixtures maps snapshot.debian.org API paths to responses trimmed +// from the real service. +var snapshotFixtures = map[string]string{ + "/mr/binary/hello/": "binary-hello.json", + "/mr/binary/hello/2.10-3/binfiles": "binfiles-hello-2.10-3.json", + "/mr/binary/openssh-client/": "binary-openssh-client.json", + "/mr/binary/openssh-client/1:9.2p1-2+deb12u3/binfiles": "binfiles-openssh-client.json", + "/mr/binary/ca-certificates/20230311/binfiles": "binfiles-ca-certificates.json", +} + +// rewriteTransport sends requests for any host to target, so a Registry +// configured with https://snapshot.debian.org talks to the test server. +type rewriteTransport struct{ target *url.URL } + +func (t rewriteTransport) 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) +} + +// snapshotServer serves the fixtures and records the paths requested. +func snapshotServer(t *testing.T) (*core.Client, func() []string) { + t.Helper() + var mu sync.Mutex + var requested []string + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + mu.Lock() + requested = append(requested, r.URL.Path+"?"+r.URL.RawQuery) + mu.Unlock() + name, ok := snapshotFixtures[r.URL.Path] + if !ok { + http.NotFound(w, r) + return + } + body, err := os.ReadFile("testdata/snapshot/" + name) + if err != nil { + t.Error(err) + } + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write(body) + })) + t.Cleanup(srv.Close) + target, _ := url.Parse(srv.URL) + client := core.DefaultClient() + client.HTTPClient = &http.Client{Transport: rewriteTransport{target}} + return client, func() []string { + mu.Lock() + defer mu.Unlock() + return append([]string(nil), requested...) + } +} + +func TestSnapshotVersions(t *testing.T) { + client, requested := snapshotServer(t) + reg := New("https://snapshot.debian.org?architectures=amd64", client) + + versions, err := reg.FetchVersions(context.Background(), "debian/hello") + if err != nil { + t.Fatal(err) + } + var got []string + for _, v := range versions { + got = append(got, v.Number) + if len(v.Artifacts) != 0 { + t.Errorf("%s has artifacts %v, want them left to FetchVersion", v.Number, v.Artifacts) + } + } + want := []string{"2.12.3-1", "2.10-5+b1", "2.10-5", "2.10-4", "2.10-3+b1", "2.10-3", "2.10-2", "2.10-1+deb9u1"} + if !reflect.DeepEqual(got, want) { + t.Errorf("versions = %v, want %v", got, want) + } + if src := versions[1].Metadata["source_version"]; src != "2.10-5" { + t.Errorf("source_version of 2.10-5+b1 = %v, want 2.10-5", src) + } + if paths := requested(); !reflect.DeepEqual(paths, []string{"/mr/binary/hello/?"}) { + t.Errorf("requested %v, want only the binary's version list", paths) + } + if got := reg.URLs().PURL("debian/hello", "2.10-3"); got != "pkg:deb/debian/hello@2.10-3?repository_url=https:%2F%2Fsnapshot.debian.org%3Farchitectures%3Damd64" { + t.Errorf("PURL = %s", got) + } +} + +func TestSnapshotVersionsSortNewestFirst(t *testing.T) { + client, _ := snapshotServer(t) + reg := New("https://snapshot.debian.org?architectures=amd64", client) + versions, err := reg.FetchVersions(context.Background(), "openssh-client") + if err != nil { + t.Fatal(err) + } + if len(versions) != 2 || versions[0].Number != "1:9.2p1-2+deb12u10" || versions[1].Number != "1:9.2p1-2+deb12u3" { + t.Errorf("versions = %+v", versions) + } + pkg, err := reg.FetchPackage(context.Background(), "openssh-client") + if err != nil { + t.Fatal(err) + } + if pkg.Name != "openssh-client" || pkg.LatestVersion != "1:9.2p1-2+deb12u10" || pkg.Metadata["source"] != "openssh" { + t.Errorf("package = %+v", pkg) + } +} + +func TestSnapshotFetchVersion(t *testing.T) { + client, requested := snapshotServer(t) + reg := New("https://snapshot.debian.org?architectures=amd64,arm64", client) + + v, err := reg.FetchVersion(context.Background(), "debian/openssh-client", "1:9.2p1-2+deb12u3") + if err != nil { + t.Fatal(err) + } + want := []core.Artifact{ + { + URL: "https://snapshot.debian.org/file/81171c850daaaedc27dabae3717dc20943ef371a", + Filename: "openssh-client_9.2p1-2+deb12u3_amd64.deb", + Size: 990808, + Integrity: "sha1-81171c850daaaedc27dabae3717dc20943ef371a", + Metadata: map[string]any{"arch": "amd64", "archive": "debian-security", "first_seen": "20240701T082523Z"}, + }, + { + URL: "https://snapshot.debian.org/file/cbd60f5bdf4f576681cb75f888761abc94cb72ca", + Filename: "openssh-client_9.2p1-2+deb12u3_arm64.deb", + Size: 937432, + Integrity: "sha1-cbd60f5bdf4f576681cb75f888761abc94cb72ca", + Metadata: map[string]any{"arch": "arm64", "archive": "debian-security", "first_seen": "20240701T082523Z"}, + }, + } + if v.Number != "1:9.2p1-2+deb12u3" || !reflect.DeepEqual(v.Artifacts, want) { + t.Errorf("version = %+v\nwant artifacts %+v", v, want) + } + if paths := requested(); !reflect.DeepEqual(paths, []string{"/mr/binary/openssh-client/1:9.2p1-2+deb12u3/binfiles?fileinfo=1"}) { + t.Errorf("requested %v", paths) + } +} + +func TestSnapshotFetchVersionKeepsConfiguredArchitectures(t *testing.T) { + client, _ := snapshotServer(t) + reg := New("https://snapshot.debian.org?architectures=arm64", client) + + v, err := reg.FetchVersion(context.Background(), "hello", "2.10-3") + if err != nil { + t.Fatal(err) + } + if len(v.Artifacts) != 1 || v.Artifacts[0].Filename != "hello_2.10-3_arm64.deb" { + t.Errorf("artifacts = %+v, want only arm64", v.Artifacts) + } + + // Architecture: all packages are kept whatever is configured. + v, err = reg.FetchVersion(context.Background(), "ca-certificates", "20230311") + if err != nil { + t.Fatal(err) + } + if len(v.Artifacts) != 1 || v.Artifacts[0].Metadata["arch"] != "all" || v.Artifacts[0].Filename != "ca-certificates_20230311_all.deb" { + t.Errorf("artifacts = %+v, want the all package", v.Artifacts) + } +} + +func TestSnapshotNotFound(t *testing.T) { + client, requested := snapshotServer(t) + reg := New("https://snapshot.debian.org?architectures=amd64", client) + + var notFound *core.NotFoundError + if _, err := reg.FetchVersions(context.Background(), "no-such-package"); !errors.As(err, ¬Found) { + t.Errorf("FetchVersions: err = %v, want NotFoundError", err) + } + if _, err := reg.FetchVersion(context.Background(), "hello", "9.9-9"); !errors.As(err, ¬Found) || notFound.Version != "9.9-9" { + t.Errorf("FetchVersion: err = %v, want NotFoundError for the version", err) + } + for _, path := range requested() { + if path[:4] != "/mr/" { + t.Errorf("requested %s, want only the snapshot API", path) + } + } +} + +func TestSnapshotHasNoDependenciesOrMaintainers(t *testing.T) { + client, _ := snapshotServer(t) + reg := New("https://snapshot.debian.org?architectures=amd64", client) + if _, err := reg.FetchDependencies(context.Background(), "hello", "2.10-3"); !errors.Is(err, errors.ErrUnsupported) { + t.Errorf("FetchDependencies: err = %v, want ErrUnsupported", err) + } + if _, err := reg.FetchMaintainers(context.Background(), "hello"); !errors.Is(err, errors.ErrUnsupported) { + t.Errorf("FetchMaintainers: err = %v, want ErrUnsupported", err) + } +} + +func TestSnapshotConfig(t *testing.T) { + for _, tc := range []struct { + url string + snapshot bool + wantErr bool + }{ + {"https://snapshot.debian.org?architectures=amd64", true, false}, + {"https://snapshot.debian.org/?architectures=amd64", true, false}, + {"https://snapshot.debian.org", true, true}, + {"https://snapshot.debian.org?suites=bookworm&architectures=amd64", true, true}, + {"https://snapshot.debian.org?components=main&architectures=amd64", true, true}, + {"https://snapshot.debian.org?architectures=source", true, true}, + {"https://snapshot.debian.org?architectures=..", true, true}, + // Only https selects the API; otherwise it is an archive missing + // its suites. + {"http://snapshot.debian.org?architectures=amd64", false, true}, + // A dated archive under snapshot.debian.org is an ordinary archive. + {"https://snapshot.debian.org/archive/debian/20240101T000000Z?suites=bookworm&architectures=amd64", false, false}, + {"https://deb.debian.org/debian?suites=bookworm&architectures=amd64", false, false}, + } { + reg := New(tc.url, nil) + if reg.snapshot != tc.snapshot || (reg.configErr != nil) != tc.wantErr { + t.Errorf("%s: snapshot = %v, err = %v", tc.url, reg.snapshot, reg.configErr) + } + if tc.wantErr && !errors.Is(reg.configErr, ErrInvalidConfig) { + t.Errorf("%s: err = %v, want ErrInvalidConfig", tc.url, reg.configErr) + } + } +} + +func TestSnapshotRefusesBadFiles(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _, _ = w.Write([]byte(`{"binary_version":"1","fileinfo":{ + "0123456789abcdef0123456789abcdef01234567":[{"archive_name":"debian","name":"../evil.deb","size":1}], + "not-a-sha1":[{"archive_name":"debian","name":"x_1_amd64.deb","size":1}], + "89abcdef0123456789abcdef0123456789abcdef":[], + "1111111111111111111111111111111111111111":[{"archive_name":"debian","name":"","size":1}], + "2222222222222222222222222222222222222222":[{"archive_name":"debian","name":"x\u0000.deb","size":1}]}, + "result":[ + {"architecture":"amd64","hash":"0123456789abcdef0123456789abcdef01234567"}, + {"architecture":"amd64","hash":"not-a-sha1"}, + {"architecture":"amd64","hash":"89abcdef0123456789abcdef0123456789abcdef"}, + {"architecture":"amd64","hash":"fedcba9876543210fedcba9876543210fedcba98"}, + {"architecture":"amd64","hash":"1111111111111111111111111111111111111111"}, + {"architecture":"amd64","hash":"2222222222222222222222222222222222222222"}]}`)) + })) + t.Cleanup(srv.Close) + target, _ := url.Parse(srv.URL) + client := core.DefaultClient() + client.HTTPClient = &http.Client{Transport: rewriteTransport{target}} + reg := New("https://snapshot.debian.org?architectures=amd64", client) + v, err := reg.FetchVersion(context.Background(), "x", "1") + if err != nil { + t.Fatal(err) + } + if len(v.Artifacts) != 0 { + t.Errorf("artifacts = %+v, want none", v.Artifacts) + } +} + +func TestFetchArtifacts(t *testing.T) { + client, _ := snapshotServer(t) + reg := New("https://snapshot.debian.org?architectures=amd64", client) + artifacts, err := reg.FetchArtifacts(context.Background(), "hello", "2.10-3") + if err != nil { + t.Fatal(err) + } + if len(artifacts) != 1 || artifacts[0].Filename != "hello_2.10-3_amd64.deb" { + t.Errorf("artifacts = %+v", artifacts) + } +} + +func TestFetchVersionFromIndexes(t *testing.T) { + _, base := standard(t) + reg := newRegistry(base, "suites=bookworm&architectures=amd64") + v, err := reg.FetchVersion(context.Background(), "debian/curl", "7.88.1-10+deb12u5") + if err != nil { + t.Fatal(err) + } + if len(v.Artifacts) != 1 || v.Artifacts[0].Filename != "curl_7.88.1-10+deb12u5_amd64.deb" { + t.Errorf("version = %+v", v) + } + var notFound *core.NotFoundError + if _, err := reg.FetchVersion(context.Background(), "debian/curl", "0.1"); !errors.As(err, ¬Found) || notFound.Version != "0.1" { + t.Errorf("err = %v, want NotFoundError for the version", err) + } + if _, err := reg.FetchVersion(context.Background(), "nope", "0.1"); !errors.As(err, ¬Found) { + t.Errorf("err = %v, want NotFoundError", err) + } +} + +func TestSnapshotPURLRoundTrip(t *testing.T) { + client, _ := snapshotServer(t) + p := New("https://snapshot.debian.org?architectures=amd64,arm64", nil).URLs().PURL("debian/hello", "2.10-3") + reg, name, version, err := core.NewFromPURL(p, client) + if err != nil { + t.Fatal(err) + } + v, err := reg.(*Registry).FetchVersion(context.Background(), name, version) + if err != nil || len(v.Artifacts) != 2 { + t.Errorf("FetchVersion = %+v, %v", v, err) + } +} + +// fakeSnapshot serves body for every request and records the raw paths. +func fakeSnapshot(t *testing.T, body string) (*core.Client, *[]string) { + t.Helper() + var requested []string + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + requested = append(requested, r.URL.EscapedPath()) + _, _ = w.Write([]byte(body)) + })) + t.Cleanup(srv.Close) + target, _ := url.Parse(srv.URL) + client := core.DefaultClient() + client.HTTPClient = &http.Client{Transport: rewriteTransport{target}} + return client, &requested +} + +func TestSnapshotVersionsSkipsRepeatsAndBlanks(t *testing.T) { + client, _ := fakeSnapshot(t, `{"result":[ + {"binary_version":"2","source":"x","version":"2"}, + {"binary_version":"","source":"x","version":"1"}, + {"binary_version":"2","source":"x","version":"2"}, + {"binary_version":"1","source":"x","version":"1"}]}`) + reg := New("https://snapshot.debian.org?architectures=amd64", client) + versions, err := reg.FetchVersions(context.Background(), "x") + if err != nil { + t.Fatal(err) + } + if got := numbers(versions); !reflect.DeepEqual(got, []string{"2", "1"}) { + t.Errorf("versions = %v, want [2 1]", got) + } + + client, _ = fakeSnapshot(t, `{"result":[]}`) + reg = New("https://snapshot.debian.org?architectures=amd64", client) + var notFound *core.NotFoundError + if _, err := reg.FetchVersions(context.Background(), "x"); !errors.As(err, ¬Found) { + t.Errorf("no versions: err = %v, want NotFoundError", err) + } +} + +func TestSnapshotEscapesPathSegments(t *testing.T) { + client, requested := fakeSnapshot(t, `{"result":[{"binary_version":"1"}]}`) + reg := New("https://snapshot.debian.org?architectures=amd64", client) + _, _ = reg.FetchVersions(context.Background(), "a?b") + _, _ = reg.FetchVersion(context.Background(), "a?b", "1#2") + want := []string{"/mr/binary/a%3Fb/", "/mr/binary/a%3Fb/1%232/binfiles"} + if !reflect.DeepEqual(*requested, want) { + t.Errorf("requested %v, want %v", *requested, want) + } +} + +func TestSnapshotMisconfiguredMakesNoRequest(t *testing.T) { + client, requested := fakeSnapshot(t, `{"result":[]}`) + reg := New("https://snapshot.debian.org?suites=bookworm&architectures=amd64", client) + if _, err := reg.FetchVersions(context.Background(), "x"); !errors.Is(err, ErrInvalidConfig) { + t.Errorf("FetchVersions: err = %v, want ErrInvalidConfig", err) + } + if _, err := reg.FetchVersion(context.Background(), "x", "1"); !errors.Is(err, ErrInvalidConfig) { + t.Errorf("FetchVersion: err = %v, want ErrInvalidConfig", err) + } + if len(*requested) != 0 { + t.Errorf("requested %v, want nothing", *requested) + } +} diff --git a/internal/deb/testdata/snapshot/binary-hello.json b/internal/deb/testdata/snapshot/binary-hello.json new file mode 100644 index 0000000..36a500d --- /dev/null +++ b/internal/deb/testdata/snapshot/binary-hello.json @@ -0,0 +1,54 @@ +{ + "_comment": "foo", + "binary": "hello", + "result": [ + { + "binary_version": "2.12.3-1", + "name": "hello", + "source": "hello", + "version": "2.12.3-1" + }, + { + "binary_version": "2.10-5+b1", + "name": "hello", + "source": "hello", + "version": "2.10-5" + }, + { + "binary_version": "2.10-5", + "name": "hello", + "source": "hello", + "version": "2.10-5" + }, + { + "binary_version": "2.10-4", + "name": "hello", + "source": "hello", + "version": "2.10-4" + }, + { + "binary_version": "2.10-3+b1", + "name": "hello", + "source": "hello", + "version": "2.10-3" + }, + { + "binary_version": "2.10-3", + "name": "hello", + "source": "hello", + "version": "2.10-3" + }, + { + "binary_version": "2.10-2", + "name": "hello", + "source": "hello", + "version": "2.10-2" + }, + { + "binary_version": "2.10-1+deb9u1", + "name": "hello", + "source": "hello", + "version": "2.10-1+deb9u1" + } + ] +} \ No newline at end of file diff --git a/internal/deb/testdata/snapshot/binary-openssh-client.json b/internal/deb/testdata/snapshot/binary-openssh-client.json new file mode 100644 index 0000000..e26f67c --- /dev/null +++ b/internal/deb/testdata/snapshot/binary-openssh-client.json @@ -0,0 +1,18 @@ +{ + "_comment": "foo", + "binary": "openssh-client", + "result": [ + { + "binary_version": "1:9.2p1-2+deb12u10", + "name": "openssh-client", + "source": "openssh", + "version": "1:9.2p1-2+deb12u10" + }, + { + "binary_version": "1:9.2p1-2+deb12u3", + "name": "openssh-client", + "source": "openssh", + "version": "1:9.2p1-2+deb12u3" + } + ] +} \ No newline at end of file diff --git a/internal/deb/testdata/snapshot/binfiles-ca-certificates.json b/internal/deb/testdata/snapshot/binfiles-ca-certificates.json new file mode 100644 index 0000000..581b806 --- /dev/null +++ b/internal/deb/testdata/snapshot/binfiles-ca-certificates.json @@ -0,0 +1 @@ +{"_comment":"foo","binary":"ca-certificates","binary_version":"20230311","fileinfo":{"2723803bd4497bd27a499a249e57936821dedbed":[{"archive_name":"debian","first_seen":"20230311T205846Z","name":"ca-certificates_20230311_all.deb","path":"/pool/main/c/ca-certificates","size":153456},{"archive_name":"debian-ports","first_seen":"20230313T210052Z","name":"ca-certificates_20230311_all.deb","path":"/pool/main/c/ca-certificates","size":153456}]},"result":[{"architecture":"all","hash":"2723803bd4497bd27a499a249e57936821dedbed"}]} diff --git a/internal/deb/testdata/snapshot/binfiles-hello-2.10-3.json b/internal/deb/testdata/snapshot/binfiles-hello-2.10-3.json new file mode 100644 index 0000000..462c27a --- /dev/null +++ b/internal/deb/testdata/snapshot/binfiles-hello-2.10-3.json @@ -0,0 +1,48 @@ +{ + "_comment": "foo", + "binary": "hello", + "binary_version": "2.10-3", + "fileinfo": { + "2d5dfa44e05ee29114965a29a1b503722e1e3feb": [ + { + "archive_name": "debian", + "first_seen": "20221227T032939Z", + "name": "hello_2.10-3_s390x.deb", + "path": "/pool/main/h/hello", + "size": 52508 + } + ], + "886b91e2acb631a2e0dcdfdf21af03f55d801d22": [ + { + "archive_name": "debian", + "first_seen": "20221227T032939Z", + "name": "hello_2.10-3_arm64.deb", + "path": "/pool/main/h/hello", + "size": 52308 + } + ], + "f322085c1e2f95e8febe24989f776cfac268ff90": [ + { + "archive_name": "debian", + "first_seen": "20221227T032939Z", + "name": "hello_2.10-3_amd64.deb", + "path": "/pool/main/h/hello", + "size": 53080 + } + ] + }, + "result": [ + { + "architecture": "arm64", + "hash": "886b91e2acb631a2e0dcdfdf21af03f55d801d22" + }, + { + "architecture": "amd64", + "hash": "f322085c1e2f95e8febe24989f776cfac268ff90" + }, + { + "architecture": "s390x", + "hash": "2d5dfa44e05ee29114965a29a1b503722e1e3feb" + } + ] +} \ No newline at end of file diff --git a/internal/deb/testdata/snapshot/binfiles-openssh-client.json b/internal/deb/testdata/snapshot/binfiles-openssh-client.json new file mode 100644 index 0000000..4c07f7c --- /dev/null +++ b/internal/deb/testdata/snapshot/binfiles-openssh-client.json @@ -0,0 +1,49 @@ +{ + "_comment": "foo", + "binary": "openssh-client", + "binary_version": "1:9.2p1-2+deb12u3", + "fileinfo": { + "81171c850daaaedc27dabae3717dc20943ef371a": [ + { + "archive_name": "debian-security", + "first_seen": "20240701T082523Z", + "name": "openssh-client_9.2p1-2+deb12u3_amd64.deb", + "path": "/pool/updates/main/o/openssh", + "size": 990808 + }, + { + "archive_name": "debian", + "first_seen": "20240701T204138Z", + "name": "openssh-client_9.2p1-2+deb12u3_amd64.deb", + "path": "/pool/main/o/openssh", + "size": 990808 + } + ], + "cbd60f5bdf4f576681cb75f888761abc94cb72ca": [ + { + "archive_name": "debian-security", + "first_seen": "20240701T082523Z", + "name": "openssh-client_9.2p1-2+deb12u3_arm64.deb", + "path": "/pool/updates/main/o/openssh", + "size": 937432 + }, + { + "archive_name": "debian", + "first_seen": "20240701T204138Z", + "name": "openssh-client_9.2p1-2+deb12u3_arm64.deb", + "path": "/pool/main/o/openssh", + "size": 937432 + } + ] + }, + "result": [ + { + "architecture": "amd64", + "hash": "81171c850daaaedc27dabae3717dc20943ef371a" + }, + { + "architecture": "arm64", + "hash": "cbd60f5bdf4f576681cb75f888761abc94cb72ca" + } + ] +} \ No newline at end of file