diff --git a/README.md b/README.md index 79cf8f0..c71c1f8 100644 --- a/README.md +++ b/README.md @@ -136,6 +136,7 @@ packages = registries.BulkFetchPackagesWithConcurrency(ctx, purls, nil, 5) | Terraform | `pkg:terraform/hashicorp/consul/aws@0.11.0` (module), `pkg:terraform/hashicorp/random@3.6.0` (provider) | | GitHub Actions | `pkg:githubactions/actions/checkout@v4` | | VS Code extension | `pkg:vscode-extension/redhat/vscode-yaml@1.15.0` | +| Arch Linux | `pkg:alpm/arch/pacman@7.1.0.r9.g54d9411-4?arch=x86_64&repository_url=https://geo.mirror.pkgbuild.com/core/os/x86_64/core.db` | | Alpine | `pkg:apk/alpine/curl@8.22.0-r0?arch=x86_64&repository_url=https://dl-cdn.alpinelinux.org/alpine/v3.23/main/x86_64` | | Debian | `pkg:deb/debian/curl@7.88.1-10+deb12u14?arch=amd64&distro=bookworm&repository_url=https://deb.debian.org/debian%3Fsuites%3Dbookworm%2Cbookworm-updates%26architectures%3Damd64` | | RPM | `pkg:rpm/fedora/curl@8.15.0-4.fc43?arch=x86_64&distro=fedora-43&repository_url=https://dl.fedoraproject.org/pub/fedora/linux/releases/43/Everything/x86_64/os%3Fdistro%3Dfedora-43` | @@ -198,6 +199,7 @@ import _ "github.com/git-pkgs/registries/all" | Deno | `deno` | https://apiland.deno.dev | | Terraform | `terraform` | https://registry.terraform.io | | Swift | `swift` | URL required | +| Arch Linux | `alpm` | URL required | | Alpine | `apk` | URL required | | Debian | `deb` | URL required | | RPM | `rpm` | URL required | @@ -205,6 +207,8 @@ import _ "github.com/git-pkgs/registries/all" | VS Code extension | `vscode-extension` | https://open-vsx.org | | APM | None | URL required | +The Arch Linux URL is one pacman sync database, such as `https://geo.mirror.pkgbuild.com/core/os/x86_64/core.db`, which names the repository and architecture; the client doesn't pick either from a mirror root. It reads the database's tar compressed with gzip, zstd or xz, or uncompressed, telling them apart by their first bytes, and caps it at 1 GiB decompressed. A path that is absolute, climbs out with `..` or nests below a package's directory, a `NAME` or `VERSION` that disagrees with the directory name, or a `FILENAME` holding a path makes the whole database an error. Each version's artifact is its `FILENAME` beside the database, with `SHA256SUM` as integrity (`sha256-...`), `CSIZE` as size and the metadata `arch` (`x86_64`, `any`, …), so `URLs().Download` is empty and `fetch.Resolver` reads the database. Versions keep their epoch and package release (`1:1.4-1`) and compare with the `alpm` scheme. `DEPENDS` are runtime dependencies and `OPTDEPENDS` optional ones, without their descriptions. A name another package provides, such as `libcurl.so=4-64`, is listed as that package, the first by name of those whose provided version meets the constraint; one nothing in the database satisfies is kept as written. Make, check, conflict, replace and provide relations, groups, the base package and the packager are in the version's metadata. `FetchMaintainers` reads `PACKAGER`, splitting `Name `. Through a PURL, the `arch` namespace is kept as `Package.Namespace`. + The Alpine URL is one repository architecture directory, such as `https://dl-cdn.alpinelinux.org/alpine/v3.23/main/x86_64`, or the `APKINDEX.tar.gz` inside it. The client doesn't pick a release, component or architecture from a mirror root. It reads v2 `APKINDEX.tar.gz` indexes. When a directory serves a v3 `Packages.adb`, the client returns an error rather than reading the v2 index. 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. diff --git a/all/all.go b/all/all.go index 82299a4..b1d36ba 100644 --- a/all/all.go +++ b/all/all.go @@ -9,10 +9,11 @@ // // // Now all ecosystems are available // ecosystems := registries.SupportedEcosystems() -// // ["apk", "apm", "brew", "cargo", "clojars", "cocoapods", "composer", "conda", "cpan", "cran", "deb", "deno", "dub", "elm", "gem", "githubactions", "golang", "hackage", "haxelib", "helm", "hex", "julia", "luarocks", "maven", "nimble", "npm", "nuget", "pub", "pypi", "rpm", "swift", "terraform", "vscode-extension"] +// // ["alpm", "apk", "apm", "brew", "cargo", "clojars", "cocoapods", "composer", "conda", "cpan", "cran", "deb", "deno", "dub", "elm", "gem", "githubactions", "golang", "hackage", "haxelib", "helm", "hex", "julia", "luarocks", "maven", "nimble", "npm", "nuget", "pub", "pypi", "rpm", "swift", "terraform", "vscode-extension"] package all import ( + _ "github.com/git-pkgs/registries/internal/alpm" _ "github.com/git-pkgs/registries/internal/apk" _ "github.com/git-pkgs/registries/internal/apm" _ "github.com/git-pkgs/registries/internal/cargo" diff --git a/fetch/alpm_resolver_test.go b/fetch/alpm_resolver_test.go new file mode 100644 index 0000000..b435110 --- /dev/null +++ b/fetch/alpm_resolver_test.go @@ -0,0 +1,78 @@ +//go:build !tinygo + +package fetch + +import ( + "archive/tar" + "bytes" + "compress/gzip" + "context" + "errors" + "net/http" + "net/http/httptest" + "testing" + + "github.com/git-pkgs/registries" + _ "github.com/git-pkgs/registries/internal/alpm" + "github.com/git-pkgs/registries/safehttp" +) + +// alpmDatabase serves a sync database holding pacman for x86_64, over TLS: +// the resolver only hands out https download URLs. +func alpmDatabase(t *testing.T) (string, *registries.Client) { + t.Helper() + desc := "%FILENAME%\npacman-7.1.0-4-x86_64.pkg.tar.zst\n\n%NAME%\npacman\n\n%VERSION%\n7.1.0-4\n\n" + + "%CSIZE%\n993248\n\n%SHA256SUM%\ne7b847d2989de38ec17ce9e2ca2a7b585ca61604dda0c73bc285b44005b234b1\n\n%ARCH%\nx86_64\n" + var buf bytes.Buffer + gz := gzip.NewWriter(&buf) + tw := tar.NewWriter(gz) + _ = tw.WriteHeader(&tar.Header{Name: "pacman-7.1.0-4/desc", Mode: 0o644, Size: int64(len(desc))}) + _, _ = tw.Write([]byte(desc)) + _ = tw.Close() + _ = gz.Close() + + server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/core/os/x86_64/core.db" { + http.NotFound(w, r) + return + } + _, _ = w.Write(buf.Bytes()) + })) + t.Cleanup(server.Close) + client := registries.DefaultClient() + client.HTTPClient = server.Client() + return server.URL + "/core/os/x86_64", client +} + +func TestResolveALPM(t *testing.T) { + dir, client := alpmDatabase(t) + reg, err := registries.New("alpm", dir+"/core.db", client) + if err != nil { + t.Fatal(err) + } + r := NewResolver(WithAddressPolicy(safehttp.Options{AllowLoopback: true})) + r.RegisterRegistry(reg) + + for _, qualifiers := range []map[string]string{nil, {"arch": "x86_64"}} { + info, err := r.ResolveWithOptions(context.Background(), "alpm", "arch/pacman", "7.1.0-4", + ResolveOptions{Qualifiers: qualifiers}) + if err != nil { + t.Fatalf("Resolve with %v: %v", qualifiers, err) + } + want := ArtifactInfo{ + URL: dir + "/pacman-7.1.0-4-x86_64.pkg.tar.zst", + Filename: "pacman-7.1.0-4-x86_64.pkg.tar.zst", + Integrity: "sha256-e7b847d2989de38ec17ce9e2ca2a7b585ca61604dda0c73bc285b44005b234b1", + Size: 993248, + } + if *info != want { + t.Errorf("info with %v = %+v, want %+v", qualifiers, info, want) + } + } + + _, err = r.ResolveWithOptions(context.Background(), "alpm", "arch/pacman", "7.1.0-4", + ResolveOptions{Qualifiers: map[string]string{"arch": "aarch64"}}) + if !errors.Is(err, ErrNoMatchingArtifact) { + t.Errorf("aarch64 against x86_64: err = %v, want ErrNoMatchingArtifact", err) + } +} diff --git a/internal/alpm/alpm.go b/internal/alpm/alpm.go new file mode 100644 index 0000000..0ed1a01 --- /dev/null +++ b/internal/alpm/alpm.go @@ -0,0 +1,757 @@ +// Package alpm provides a registry client for pacman sync databases, as +// used by Arch Linux and other users of libalpm. +package alpm + +import ( + "archive/tar" + "bufio" + "bytes" + "compress/gzip" + "context" + "encoding/hex" + "errors" + "fmt" + "io" + "net/url" + "sort" + "strconv" + "strings" + "sync" + "time" + + "github.com/git-pkgs/purl" + "github.com/git-pkgs/registries/internal/core" + "github.com/git-pkgs/registries/internal/xzlimit" + "github.com/git-pkgs/vers" + "github.com/klauspost/compress/zstd" +) + +const ( + DefaultURL = "" + ecosystem = "alpm" + + // maxDatabaseSize bounds the decompressed database. Arch's extra.db is + // about 40 MB as a tar, and a .files database about ten times that. + maxDatabaseSize = 1 << 30 + // maxEntrySize bounds one desc or depends file. pacman reads lines of + // up to 512 KiB. + maxEntrySize = 1 << 20 + // maxZstdWindow bounds the window a zstd frame may ask the decoder to + // allocate. zstd --ultra -22 uses 128 MiB. + maxZstdWindow = 128 << 20 + + archKey = "arch" +) + +var ( + // ErrInvalidConfig is returned when the database URL is missing or does + // not name a file. + ErrInvalidConfig = errors.New("invalid ALPM database configuration") + // ErrMalformedDatabase is returned for sync databases that cannot be + // read, hold unsafe paths, or have inconsistent package records. + ErrMalformedDatabase = errors.New("malformed ALPM sync database") +) + +func init() { + core.Register(ecosystem, DefaultURL, func(baseURL string, client *core.Client) core.Registry { + return New(baseURL, client) + }) +} + +// Registry reads one pacman sync database, such as +// https://geo.mirror.pkgbuild.com/core/os/x86_64/core.db. The URL names the +// repository and architecture; neither is inferred from a mirror root. +// Package files are resolved from each package's FILENAME, relative to the +// database's directory. +// +// The database is downloaded once per Registry and kept for its lifetime, +// so callers looking up many packages should reuse one Registry. +type Registry struct { + dbURL string + dirURL string + configErr error + client *core.Client + urls *URLs + + maxDatabaseSize int64 + + mu sync.Mutex + idx *dbIndex +} + +type dbIndex struct { + packages map[string][]record + // providers maps a name from PROVIDES, such as libalpm.so, to the + // packages providing it, ordered by package name. + providers map[string][]provision +} + +// provision is one PROVIDES entry: the providing package and its version, +// and the version provided, empty when the entry names none. +type provision struct { + pkg string + pkgVersion string + version string +} + +func New(baseURL string, client *core.Client) *Registry { + if client == nil { + client = core.DefaultClient() + } + r := &Registry{client: client, maxDatabaseSize: maxDatabaseSize} + u, err := url.Parse(baseURL) + switch { + case err != nil || u.Scheme == "" || u.Host == "": + r.configErr = fmt.Errorf("%w: %q is not a database URL", ErrInvalidConfig, baseURL) + case u.Path == "" || strings.HasSuffix(u.Path, "/"): + r.configErr = fmt.Errorf("%w: %q names a directory, not a sync database such as core.db", ErrInvalidConfig, baseURL) + default: + r.dbURL = baseURL + u.RawQuery, u.Fragment = "", "" + s := u.String() + r.dirURL = s[:strings.LastIndex(s, "/")] + } + r.urls = &URLs{dbURL: r.dbURL} + return r +} + +func (r *Registry) Ecosystem() string { + return ecosystem +} + +func (r *Registry) URLs() core.URLBuilder { //nolint:ireturn + return r.urls +} + +// record is one package of the sync database, from its desc file and, in +// older databases, its depends file. +type record struct { + name string + version string + base string + filename string + description string + url string + arch string + packager string + md5sum string + sha256sum string + buildTime time.Time + size int64 + installedSize int64 + groups []string + licenses []string + depends []string + optDepends []string + makeDepends []string + checkDepends []string + conflicts []string + provides []string + replaces []string +} + +// splitName strips a PURL vendor namespace: "arch/pacman" looks up "pacman". +func splitName(name string) (namespace, pkg string) { + if i := strings.LastIndex(name, "/"); i >= 0 { + return name[:i], name[i+1:] + } + return "", name +} + +// index reads the database, once. Nothing is kept unless it was read +// whole, so a failed read is tried again next time. +func (r *Registry) index(ctx context.Context) (*dbIndex, error) { + if r.configErr != nil { + return nil, r.configErr + } + r.mu.Lock() + defer r.mu.Unlock() + if r.idx != nil { + return r.idx, nil + } + + var records []record + err := r.client.Stream(ctx, r.dbURL, func(body io.Reader) error { + var err error + records, err = r.readDatabase(body) + return err + }) + if err != nil { + return nil, err + } + + packages := make(map[string][]record) + for _, rec := range records { + packages[rec.name] = append(packages[rec.name], rec) + } + for _, recs := range packages { + sort.SliceStable(recs, func(i, j int) bool { + return vers.CompareWithScheme(recs[i].version, recs[j].version, ecosystem) > 0 + }) + } + r.idx = &dbIndex{packages: packages, providers: buildProviders(records)} + return r.idx, nil +} + +// buildProviders lists the packages providing each name, ordered by +// package name so the choice among them is stable. pacman lists providers +// in that order and takes the first when not asked to choose. +func buildProviders(records []record) map[string][]provision { + providers := make(map[string][]provision) + for _, rec := range records { + for _, p := range rec.provides { + provided, requirement := splitConstraint(p) + // Only "name=version" provides a version; pacman ignores any + // other operator in PROVIDES. + version, ok := strings.CutPrefix(requirement, "=") + if !ok { + version = "" + } + providers[provided] = append(providers[provided], provision{pkg: rec.name, pkgVersion: rec.version, version: version}) + } + } + for _, provs := range providers { + sort.SliceStable(provs, func(i, j int) bool { return provs[i].pkg < provs[j].pkg }) + } + return providers +} + +// provider returns the first package, by name, whose PROVIDES satisfies +// rec's dependency on name, as pacman's _alpm_depcmp_provides decides: any +// provision of the name meets an unversioned dependency, but a versioned +// one needs a provided version that meets its constraint. Other versions +// of rec's own package are passed over, since installing one would +// replace rec. +func (idx *dbIndex) provider(rec record, name, requirement string) (string, bool) { + for _, p := range idx.providers[name] { + if p.pkg == rec.name && p.pkgVersion != rec.version { + continue + } + if requirement == "" || satisfies(p.version, requirement) { + return p.pkg, true + } + } + return "", false +} + +// satisfies reports whether a provided version meets a requirement such as +// ">=17", compared as pacman's dep_vercmp does. A provision without a +// version meets none. +func satisfies(version, requirement string) bool { + if version == "" { + return false + } + for _, op := range []string{">=", "<=", "=", ">", "<"} { + want, ok := strings.CutPrefix(requirement, op) + if !ok { + continue + } + if want == "" { + return false + } + cmp := vers.CompareWithScheme(version, want, ecosystem) + switch op { + case ">=": + return cmp >= 0 + case "<=": + return cmp <= 0 + case "=": + return cmp == 0 + case ">": + return cmp > 0 + case "<": + return cmp < 0 + } + } + return false +} + +// readDatabase decompresses a sync database, detecting the format from its +// first bytes as libarchive does, since core.db names no compression. +func (r *Registry) readDatabase(body io.Reader) ([]record, error) { + br := bufio.NewReader(body) + magic, err := br.Peek(6) + if err != nil && len(magic) == 0 { + if err == io.EOF { + return nil, fmt.Errorf("%w: %s is empty", ErrMalformedDatabase, r.dbURL) + } + return nil, err + } + + var decoded io.Reader + switch { + case bytes.HasPrefix(magic, []byte{0x1f, 0x8b}): + gz, err := gzip.NewReader(br) + if err != nil { + return nil, fmt.Errorf("%w: %w", ErrMalformedDatabase, err) + } + defer func() { _ = gz.Close() }() + decoded = gz + case bytes.HasPrefix(magic, []byte{0x28, 0xb5, 0x2f, 0xfd}): + zr, err := zstd.NewReader(br, zstd.WithDecoderMaxWindow(maxZstdWindow), zstd.WithDecoderConcurrency(1)) + if err != nil { + return nil, fmt.Errorf("%w: %w", ErrMalformedDatabase, err) + } + defer zr.Close() + decoded = zr + case bytes.HasPrefix(magic, []byte{0xfd, '7', 'z', 'X', 'Z', 0x00}): + // Bounded as it decodes: a block asking for more is an error. + decoded = xzlimit.NewReader(br, xzlimit.MaxDict) + default: + decoded = br // an uncompressed tar + } + + limited := &io.LimitedReader{R: decoded, N: r.maxDatabaseSize + 1} + records, err := parseDatabase(limited) + if limited.N == 0 { + return nil, fmt.Errorf("%w: %s decompresses to more than %d bytes", ErrMalformedDatabase, r.dbURL, r.maxDatabaseSize) + } + if err != nil { + return nil, err + } + // tar's end can precede the compressed stream's trailer and checksum. + if _, err := io.Copy(io.Discard, limited); err != nil { + return nil, fmt.Errorf("%w: %w", ErrMalformedDatabase, err) + } + if limited.N == 0 { + return nil, fmt.Errorf("%w: %s decompresses to more than %d bytes", ErrMalformedDatabase, r.dbURL, r.maxDatabaseSize) + } + return records, nil +} + +// parseDatabase reads the tar of a sync database: a directory named +// name-version per package, holding desc and, in older databases, depends. +// files lists are skipped. +func parseDatabase(r io.Reader) ([]record, error) { + tr := tar.NewReader(r) + entries := make(map[string]*record) + var order []string + for { + hdr, err := tr.Next() + if err == io.EOF { + break + } + if err != nil { + return nil, fmt.Errorf("%w: %w", ErrMalformedDatabase, err) + } + dir, file, err := entryPath(hdr.Name) + if err != nil { + return nil, err + } + if hdr.Typeflag != tar.TypeReg || dir == "" || (file != "desc" && file != "depends") { + continue + } + if hdr.Size > maxEntrySize { + return nil, fmt.Errorf("%w: %s is larger than %d bytes", ErrMalformedDatabase, hdr.Name, maxEntrySize) + } + data, err := io.ReadAll(tr) + if err != nil { + return nil, fmt.Errorf("%w: %w", ErrMalformedDatabase, err) + } + rec, ok := entries[dir] + if !ok { + rec = &record{} + entries[dir] = rec + order = append(order, dir) + } + if err := rec.parse(data); err != nil { + return nil, fmt.Errorf("%w: %s: %w", ErrMalformedDatabase, hdr.Name, err) + } + } + + records := make([]record, 0, len(order)) + for _, dir := range order { + rec := entries[dir] + if err := rec.check(dir); err != nil { + return nil, fmt.Errorf("%w: %s: %w", ErrMalformedDatabase, dir, err) + } + records = append(records, *rec) + } + return records, nil +} + +// entryPath splits an archive path into its package directory and file +// name, refusing paths that are absolute, climb out or nest deeper than +// one directory. A file outside any directory has an empty dir. +func entryPath(name string) (dir, file string, err error) { + if strings.HasPrefix(name, "/") || strings.Contains(name, `\`) { + return "", "", fmt.Errorf("%w: unsafe archive path %q", ErrMalformedDatabase, name) + } + clean := strings.TrimSuffix(strings.TrimPrefix(name, "./"), "/") + if clean == "" || clean == "." { + return "", "", nil // the archive's root directory + } + segments := strings.Split(clean, "/") + unsafe := len(segments) > 2 + for _, s := range segments { + if s == "" || s == "." || s == ".." { + unsafe = true + } + } + if unsafe { + return "", "", fmt.Errorf("%w: unsafe archive path %q", ErrMalformedDatabase, name) + } + if len(segments) == 1 { + return "", "", nil + } + return segments[0], segments[1], nil +} + +// parse reads the %KEY% sections of a desc or depends file. A section's +// values run to a blank line, as pacman's be_sync.c reads them, or to the +// next %KEY% line, which alpm-repo-desc(5) also lets end a section. +func (rec *record) parse(data []byte) error { + lines := strings.Split(strings.ReplaceAll(string(data), "\r\n", "\n"), "\n") + for i := 0; i < len(lines); i++ { + key := lines[i] + if key == "" { + continue + } + if !isSectionHeader(key) { + return fmt.Errorf("line %d: %q is not a %%KEY%% line", i+1, key) + } + var values []string + for i+1 < len(lines) && lines[i+1] != "" && !isSectionHeader(lines[i+1]) { + i++ + values = append(values, lines[i]) + } + if err := rec.set(key[1:len(key)-1], values); err != nil { + return fmt.Errorf("%s: %w", key, err) + } + } + return nil +} + +// isSectionHeader reports whether a line is a %KEY% line. +func isSectionHeader(line string) bool { + return len(line) >= 3 && line[0] == '%' && line[len(line)-1] == '%' +} + +func (rec *record) set(key string, values []string) error { + first := "" + if len(values) > 0 { + first = values[0] + } + var err error + switch key { + case "NAME": + rec.name = first + case "VERSION": + rec.version = first + case "BASE": + rec.base = first + case "FILENAME": + rec.filename = first + case "DESC": + rec.description = first + case "URL": + rec.url = first + case "ARCH": + rec.arch = first + case "PACKAGER": + rec.packager = first + case "MD5SUM": + rec.md5sum = strings.ToLower(first) + case "SHA256SUM": + rec.sha256sum = strings.ToLower(first) + case "CSIZE": + rec.size, err = parseSize(first) + case "ISIZE": + rec.installedSize, err = parseSize(first) + case "BUILDDATE": + var secs int64 + if secs, err = strconv.ParseInt(first, 10, 64); err == nil { + rec.buildTime = time.Unix(secs, 0).UTC() + } + case "GROUPS": + rec.groups = values + case "LICENSE": + rec.licenses = values + case "DEPENDS": + rec.depends = values + case "OPTDEPENDS": + rec.optDepends = values + case "MAKEDEPENDS": + rec.makeDepends = values + case "CHECKDEPENDS": + rec.checkDepends = values + case "CONFLICTS": + rec.conflicts = values + case "PROVIDES": + rec.provides = values + case "REPLACES": + rec.replaces = values + } + return err +} + +// parseSize reads CSIZE or ISIZE, a byte count, refusing a sign as +// pacman's _alpm_strtoofft does. +func parseSize(value string) (int64, error) { + n, err := strconv.ParseUint(value, 10, 63) + return int64(n), err +} + +// check holds a record to its directory name, name-pkgver-pkgrel, which +// pacman takes the package's name and version from. +func (rec *record) check(dir string) error { + name, version, ok := splitEntryName(dir) + if !ok { + return errors.New("directory is not named name-version") + } + if rec.name == "" { + rec.name = name + } + if rec.version == "" { + rec.version = version + } + if rec.name != name || rec.version != version { + return fmt.Errorf("NAME %q and VERSION %q do not match the directory", rec.name, rec.version) + } + // pacman refuses a FILENAME with a path, or one starting with a dot. + if rec.filename != "" && !safeFilename(rec.filename) { + return fmt.Errorf("FILENAME %q is not a file name", rec.filename) + } + return nil +} + +// splitEntryName splits a directory name at its second-last hyphen, since +// package names may contain hyphens and versions end in -pkgrel. +func splitEntryName(dir string) (name, version string, ok bool) { + rel := strings.LastIndex(dir, "-") + if rel <= 0 { + return "", "", false + } + ver := strings.LastIndex(dir[:rel], "-") + if ver <= 0 || rel == len(dir)-1 || ver == rel-1 { + return "", "", false + } + return dir[:ver], dir[ver+1:], true +} + +// safeFilename reports whether a FILENAME is a plain file name in the +// database's directory, with nothing a URL would read as a path, query or +// escape. +func safeFilename(name string) bool { + return name != "" && !strings.HasPrefix(name, ".") && !strings.ContainsAny(name, `/\?#%`) +} + +// parseMaintainer parses "Name "; any other value is kept whole as the name. +func parseMaintainer(value string) core.Maintainer { + if open := strings.LastIndex(value, "<"); open >= 0 && strings.HasSuffix(value, ">") { + name := strings.TrimSpace(value[:open]) + email := value[open+1 : len(value)-1] + if email != "" && strings.Contains(email, "@") && !strings.ContainsAny(email, "<> ") { + return core.Maintainer{Name: name, Email: email} + } + } + return core.Maintainer{Name: strings.TrimSpace(value)} +} + +func (r *Registry) lookup(ctx context.Context, name string) (*dbIndex, []record, error) { + idx, err := r.index(ctx) + if err != nil { + return nil, nil, err + } + _, pkg := splitName(name) + recs := idx.packages[pkg] + if len(recs) == 0 { + return nil, nil, &core.NotFoundError{Ecosystem: ecosystem, Name: name} + } + return idx, recs, nil +} + +func (r *Registry) FetchPackage(ctx context.Context, name string) (*core.Package, error) { + _, recs, err := r.lookup(ctx, name) + if err != nil { + return nil, err + } + namespace, _ := splitName(name) + latest := recs[0] + return &core.Package{ + Name: latest.name, + Description: latest.description, + Homepage: latest.url, + Licenses: joinLicenses(latest.licenses), + Namespace: namespace, + LatestVersion: latest.version, + Metadata: map[string]any{ + "base": latest.base, + "groups": latest.groups, + archKey: latest.arch, + }, + }, nil +} + +// joinLicenses joins LICENSE lines, each of which applies to the package. +// A line may itself be an SPDX expression such as "Apache-2.0 OR MIT", so +// when there are several, each such line is wrapped in parentheses first. +func joinLicenses(licenses []string) string { + if len(licenses) == 1 { + return licenses[0] + } + grouped := make([]string, len(licenses)) + for i, l := range licenses { + if strings.Contains(l, " ") { + l = "(" + l + ")" + } + grouped[i] = l + } + return strings.Join(grouped, " AND ") +} + +func (r *Registry) FetchVersions(ctx context.Context, name string) ([]core.Version, error) { + _, recs, err := r.lookup(ctx, name) + if err != nil { + return nil, err + } + versions := make([]core.Version, 0, len(recs)) + for _, rec := range recs { + versions = append(versions, r.version(rec)) + } + return versions, nil +} + +func (r *Registry) version(rec record) core.Version { + metadata := map[string]any{ + archKey: rec.arch, + "base": rec.base, + "description": rec.description, + "url": rec.url, + "packager": rec.packager, + "filename": rec.filename, + "size": rec.size, + "installed_size": rec.installedSize, + "groups": rec.groups, + "licenses": rec.licenses, + "depends": rec.depends, + "optdepends": rec.optDepends, + "makedepends": rec.makeDepends, + "checkdepends": rec.checkDepends, + "conflicts": rec.conflicts, + "provides": rec.provides, + "replaces": rec.replaces, + } + if rec.md5sum != "" { + metadata["md5sum"] = rec.md5sum + } + + v := core.Version{ + Number: rec.version, + PublishedAt: rec.buildTime, + Licenses: joinLicenses(rec.licenses), + Metadata: metadata, + } + // SHA256SUM covers the whole package file, which pacman checks it against. + if raw, err := hex.DecodeString(rec.sha256sum); err == nil && len(raw) == 32 { + v.Integrity = "sha256-" + rec.sha256sum + } + if rec.filename != "" { + v.Artifacts = []core.Artifact{{ + URL: r.dirURL + "/" + rec.filename, + Filename: rec.filename, + Integrity: v.Integrity, + Size: rec.size, + Metadata: map[string]any{archKey: rec.arch}, + }} + } + return v +} + +func (r *Registry) FetchDependencies(ctx context.Context, name, version string) ([]core.Dependency, error) { + idx, recs, err := r.lookup(ctx, name) + if err != nil { + return nil, err + } + for _, rec := range recs { + if rec.version == version { + return idx.dependencies(rec), nil + } + } + return nil, &core.NotFoundError{Ecosystem: ecosystem, Name: name, Version: version} +} + +// dependencies resolves a provided name such as libalpm.so to its provider +// and drops the constraint, which applies to the provided version, not the +// package's. A name nothing in this database satisfies is kept as is. +func (idx *dbIndex) dependencies(rec record) []core.Dependency { + deps := make([]core.Dependency, 0, len(rec.depends)+len(rec.optDepends)) + seen := map[core.Dependency]bool{} + add := func(dep string, scope core.Scope) { + depName, requirement := splitConstraint(dep) + if depName == "" { + return + } + if _, ok := idx.packages[depName]; !ok { + if provider, ok := idx.provider(rec, depName, requirement); ok { + depName, requirement = provider, "" + } + } + if depName == rec.name { + return + } + // "curl libcurl.so=4-64" is one dependency once the soname is resolved. + d := core.Dependency{Name: depName, Requirements: requirement, Scope: scope, Optional: scope == core.Optional} + if seen[d] { + return + } + seen[d] = true + deps = append(deps, d) + } + for _, dep := range rec.depends { + add(dep, core.Runtime) + } + for _, dep := range rec.optDepends { + // "base-devel: required to use makepkg" names base-devel. + dep, _, _ = strings.Cut(dep, ": ") + add(dep, core.Optional) + } + return deps +} + +// splitConstraint splits "glibc>=2.38" into "glibc" and ">=2.38". +func splitConstraint(dep string) (name, requirement string) { + dep = strings.TrimSpace(dep) + if i := strings.IndexAny(dep, "<>="); i >= 0 { + return dep[:i], dep[i:] + } + return dep, "" +} + +func (r *Registry) FetchMaintainers(ctx context.Context, name string) ([]core.Maintainer, error) { + _, recs, err := r.lookup(ctx, name) + if err != nil { + return nil, err + } + if recs[0].packager == "" { + return nil, nil + } + return []core.Maintainer{parseMaintainer(recs[0].packager)}, nil +} + +type URLs struct { + dbURL string +} + +func (u *URLs) Registry(name, version string) string { + return "" +} + +// Download returns "": a package's file name, which carries its +// architecture, is only known from the database. +func (u *URLs) Download(name, version string) string { + return "" +} + +func (u *URLs) Documentation(name, version string) string { + return "" +} + +func (u *URLs) PURL(name, version string) string { + namespace, pkg := splitName(name) + var qualifiers map[string]string + if u.dbURL != "" { + qualifiers = map[string]string{"repository_url": u.dbURL} + } + return purl.New(ecosystem, namespace, pkg, version, qualifiers).String() +} diff --git a/internal/alpm/alpm_test.go b/internal/alpm/alpm_test.go new file mode 100644 index 0000000..fc2fb98 --- /dev/null +++ b/internal/alpm/alpm_test.go @@ -0,0 +1,936 @@ +package alpm + +import ( + "archive/tar" + "bytes" + "compress/gzip" + "context" + "errors" + "net/http" + "net/http/httptest" + "reflect" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/git-pkgs/registries/internal/core" + "github.com/klauspost/compress/zstd" + "github.com/ulikunitz/xz" +) + +// Trimmed from Arch Linux's core.db for x86_64, with PGPSIG values cut and +// glibc>=2.38 and libfoo.so=1-64 added to pacman's dependencies. +const pacmanDesc = `%FILENAME% +pacman-7.1.0.r9.g54d9411-4-x86_64.pkg.tar.zst + +%NAME% +pacman + +%BASE% +pacman + +%VERSION% +7.1.0.r9.g54d9411-4 + +%DESC% +A library-based package manager with dependency support + +%GROUPS% +base-devel + +%CSIZE% +993248 + +%ISIZE% +5284716 + +%SHA256SUM% +e7b847d2989de38ec17ce9e2ca2a7b585ca61604dda0c73bc285b44005b234b1 + +%PGPSIG% +iHUEABYKAB0WIQQ+gMoai4n2nLpX2Yp2pe+QVESaXAUCatyuLQAKCRB2pe+QVESaXO5UAQCA0M7T5AgIjKsxQjJyAhTHt50ufVS4HDbleEWD3JZ9xgEAjISQ4lebJ1SCHTuv0iOW6mpY1ErbeqQ5YLHQECgm4wk= + +%URL% +https://www.archlinux.org/pacman/ + +%LICENSE% +GPL-2.0-or-later + +%ARCH% +x86_64 + +%BUILDDATE% +1792847381 + +%PACKAGER% +Pierre Schmitz + +%PROVIDES% +libalpm.so=16-64 + +%DEPENDS% +bash +curl +libcurl.so=4-64 +glibc>=2.38 +libfoo.so=1-64 + +%OPTDEPENDS% +base-devel: required to use makepkg +perl-locale-gettext: translation support in makepkg-template + +%MAKEDEPENDS% +asciidoc +meson + +%CHECKDEPENDS% +fakechroot +python + +` + +const curlDesc = `%FILENAME% +curl-8.23.0-2-x86_64.pkg.tar.zst + +%NAME% +curl + +%BASE% +curl + +%VERSION% +8.23.0-2 + +%DESC% +command line tool and library for transferring data with URLs + +%CSIZE% +1234567 + +%ISIZE% +2345678 + +%MD5SUM% +0123456789ABCDEF0123456789ABCDEF + +%SHA256SUM% +4d2bbf66b26c6dc7236e505c9d80644d3da6a28473c690365324edf276a68775 + +%URL% +https://curl.se + +%LICENSE% +MIT +curl + +%ARCH% +x86_64 + +%BUILDDATE% +1794000000 + +%PACKAGER% +Arch Build System + +%PROVIDES% +libcurl.so=4-64 + +%DEPENDS% +zlib +libz.so=1-64 + +` + +const zlibDesc = `%FILENAME% +zlib-1:1.4-1-x86_64.pkg.tar.zst + +%NAME% +zlib + +%VERSION% +1:1.4-1 + +%LICENSE% +Zlib + +%ARCH% +x86_64 + +%PROVIDES% +libz.so=1-64 + +%CONFLICTS% +zlib-ng-compat + +%REPLACES% +zlib-ng + +` + +const mirrorlistDesc = `%FILENAME% +pacman-mirrorlist-20260610-1-any.pkg.tar.zst + +%NAME% +pacman-mirrorlist + +%VERSION% +20260610-1 + +%ARCH% +any + +` + +const bashDesc = `%FILENAME% +bash-5.3.20-1-x86_64.pkg.tar.zst + +%NAME% +bash + +%VERSION% +5.3.20-1 + +%PROVIDES% +sh + +` + +// coreEntries is a small sync database: one directory per package. +var coreEntries = []entry{ + {name: "bash-5.3.20-1/", dir: true}, + {name: "bash-5.3.20-1/desc", body: bashDesc}, + {name: "curl-8.23.0-2/", dir: true}, + {name: "curl-8.23.0-2/desc", body: curlDesc}, + {name: "pacman-7.1.0.r9.g54d9411-4/", dir: true}, + {name: "pacman-7.1.0.r9.g54d9411-4/desc", body: pacmanDesc}, + {name: "pacman-mirrorlist-20260610-1/", dir: true}, + {name: "pacman-mirrorlist-20260610-1/desc", body: mirrorlistDesc}, + {name: "zlib-1:1.4-1/", dir: true}, + {name: "zlib-1:1.4-1/desc", body: zlibDesc}, +} + +type entry struct { + name string + body string + dir bool + typeflag byte +} + +func buildTar(t *testing.T, entries []entry) []byte { + t.Helper() + var buf bytes.Buffer + tw := tar.NewWriter(&buf) + for _, e := range entries { + hdr := &tar.Header{Name: e.name, Mode: 0o644, Size: int64(len(e.body)), Typeflag: tar.TypeReg} + switch { + case e.dir: + hdr.Typeflag, hdr.Mode, hdr.Size = tar.TypeDir, 0o755, 0 + case e.typeflag != 0: + hdr.Typeflag, hdr.Size, hdr.Linkname = e.typeflag, 0, "elsewhere" + } + if err := tw.WriteHeader(hdr); err != nil { + t.Fatal(err) + } + if hdr.Size > 0 { + if _, err := tw.Write([]byte(e.body)); err != nil { + t.Fatal(err) + } + } + } + if err := tw.Close(); err != nil { + t.Fatal(err) + } + return buf.Bytes() +} + +func compress(t *testing.T, format string, data []byte) []byte { + t.Helper() + var buf bytes.Buffer + switch format { + case "gzip": + w := gzip.NewWriter(&buf) + _, _ = w.Write(data) + if err := w.Close(); err != nil { + t.Fatal(err) + } + case "zstd": + w, err := zstd.NewWriter(&buf) + if err != nil { + t.Fatal(err) + } + _, _ = w.Write(data) + if err := w.Close(); err != nil { + t.Fatal(err) + } + case "xz": + w, err := xz.NewWriter(&buf) + if err != nil { + t.Fatal(err) + } + _, _ = w.Write(data) + if err := w.Close(); err != nil { + t.Fatal(err) + } + default: + return data + } + return buf.Bytes() +} + +func gzipDB(t *testing.T, entries []entry) []byte { + t.Helper() + return compress(t, "gzip", buildTar(t, entries)) +} + +// dbServer serves body at /core/os/x86_64/core.db and counts requests. +func dbServer(t *testing.T, body []byte) (string, *atomic.Int32) { + t.Helper() + var requests atomic.Int32 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/core/os/x86_64/core.db" { + http.NotFound(w, r) + return + } + requests.Add(1) + _, _ = w.Write(body) + })) + t.Cleanup(server.Close) + return server.URL + "/core/os/x86_64/core.db", &requests +} + +func newCore(t *testing.T) (*Registry, string) { + t.Helper() + dbURL, _ := dbServer(t, gzipDB(t, coreEntries)) + return New(dbURL, core.DefaultClient()), strings.TrimSuffix(dbURL, "/core.db") +} + +func TestFetchVersions(t *testing.T) { + reg, dir := newCore(t) + versions, err := reg.FetchVersions(context.Background(), "arch/pacman") + if err != nil { + t.Fatalf("FetchVersions failed: %v", err) + } + if len(versions) != 1 { + t.Fatalf("got %d versions, want 1", len(versions)) + } + v := versions[0] + if v.Number != "7.1.0.r9.g54d9411-4" || v.Licenses != "GPL-2.0-or-later" { + t.Errorf("version = %+v", v) + } + if !v.PublishedAt.Equal(time.Unix(1792847381, 0)) { + t.Errorf("PublishedAt = %v", v.PublishedAt) + } + const integrity = "sha256-e7b847d2989de38ec17ce9e2ca2a7b585ca61604dda0c73bc285b44005b234b1" + if v.Integrity != integrity { + t.Errorf("Integrity = %q", v.Integrity) + } + wantMeta := map[string]any{ + "arch": "x86_64", + "base": "pacman", + "packager": "Pierre Schmitz ", + "filename": "pacman-7.1.0.r9.g54d9411-4-x86_64.pkg.tar.zst", + "size": int64(993248), + "installed_size": int64(5284716), + "groups": []string{"base-devel"}, + "provides": []string{"libalpm.so=16-64"}, + "makedepends": []string{"asciidoc", "meson"}, + "checkdepends": []string{"fakechroot", "python"}, + "optdepends": []string{"base-devel: required to use makepkg", "perl-locale-gettext: translation support in makepkg-template"}, + } + for k, want := range wantMeta { + if !reflect.DeepEqual(v.Metadata[k], want) { + t.Errorf("Metadata[%s] = %#v, want %#v", k, v.Metadata[k], want) + } + } + if _, ok := v.Metadata["md5sum"]; ok { + t.Errorf("md5sum = %v, want none", v.Metadata["md5sum"]) + } + for k, val := range v.Metadata { + if s, ok := val.(string); ok && strings.HasPrefix(s, "iHUE") { + t.Errorf("Metadata[%s] holds the PGP signature", k) + } + } + + want := []core.Artifact{{ + URL: dir + "/pacman-7.1.0.r9.g54d9411-4-x86_64.pkg.tar.zst", + Filename: "pacman-7.1.0.r9.g54d9411-4-x86_64.pkg.tar.zst", + Integrity: integrity, + Size: 993248, + Metadata: map[string]any{"arch": "x86_64"}, + }} + if !reflect.DeepEqual(v.Artifacts, want) { + t.Errorf("artifacts = %+v, want %+v", v.Artifacts, want) + } + + curl, err := reg.FetchVersions(context.Background(), "curl") + if err != nil { + t.Fatal(err) + } + if curl[0].Licenses != "MIT AND curl" || curl[0].Metadata["md5sum"] != "0123456789abcdef0123456789abcdef" { + t.Errorf("curl = %+v", curl[0]) + } +} + +func TestCompressions(t *testing.T) { + for _, format := range []string{"gzip", "zstd", "xz", "tar"} { + t.Run(format, func(t *testing.T) { + dbURL, _ := dbServer(t, compress(t, format, buildTar(t, coreEntries))) + versions, err := New(dbURL, core.DefaultClient()).FetchVersions(context.Background(), "curl") + if err != nil { + t.Fatalf("FetchVersions: %v", err) + } + if len(versions) != 1 || versions[0].Number != "8.23.0-2" { + t.Errorf("versions = %+v", versions) + } + }) + } +} + +func TestEpochAndReleaseVersions(t *testing.T) { + reg, dir := newCore(t) + versions, err := reg.FetchVersions(context.Background(), "arch/zlib") + if err != nil { + t.Fatal(err) + } + if versions[0].Number != "1:1.4-1" || versions[0].Artifacts[0].URL != dir+"/zlib-1:1.4-1-x86_64.pkg.tar.zst" { + t.Errorf("version = %+v", versions[0]) + } + if !reflect.DeepEqual(versions[0].Metadata["conflicts"], []string{"zlib-ng-compat"}) || + !reflect.DeepEqual(versions[0].Metadata["replaces"], []string{"zlib-ng"}) { + t.Errorf("metadata = %+v", versions[0].Metadata) + } + + // An epoch outranks any version, and pkgrel orders builds of one version. + dbURL, _ := dbServer(t, gzipDB(t, []entry{ + {name: "foo-2.0-1/desc", body: "%NAME%\nfoo\n\n%VERSION%\n2.0-1\n"}, + {name: "foo-1:1.0-1/desc", body: "%NAME%\nfoo\n\n%VERSION%\n1:1.0-1\n"}, + {name: "foo-2.0-10/desc", body: "%NAME%\nfoo\n\n%VERSION%\n2.0-10\n"}, + {name: "foo-2.0-2/desc", body: "%NAME%\nfoo\n\n%VERSION%\n2.0-2\n"}, + })) + versions, err = New(dbURL, core.DefaultClient()).FetchVersions(context.Background(), "foo") + if err != nil { + t.Fatal(err) + } + var got []string + for _, v := range versions { + got = append(got, v.Number) + } + if want := []string{"1:1.0-1", "2.0-10", "2.0-2", "2.0-1"}; !reflect.DeepEqual(got, want) { + t.Errorf("versions = %v, want %v", got, want) + } +} + +func TestArchitectures(t *testing.T) { + reg, dir := newCore(t) + versions, err := reg.FetchVersions(context.Background(), "pacman-mirrorlist") + if err != nil { + t.Fatal(err) + } + a := versions[0].Artifacts[0] + if a.URL != dir+"/pacman-mirrorlist-20260610-1-any.pkg.tar.zst" || a.Metadata["arch"] != "any" || versions[0].Metadata["arch"] != "any" { + t.Errorf("artifact = %+v", a) + } +} + +func TestFetchPackageKeepsNamespace(t *testing.T) { + reg, _ := newCore(t) + pkg, err := reg.FetchPackage(context.Background(), "arch/pacman") + if err != nil { + t.Fatal(err) + } + if pkg.Name != "pacman" || pkg.Namespace != "arch" || pkg.LatestVersion != "7.1.0.r9.g54d9411-4" || + pkg.Homepage != "https://www.archlinux.org/pacman/" || pkg.Licenses != "GPL-2.0-or-later" || + pkg.Description != "A library-based package manager with dependency support" { + t.Errorf("package = %+v", pkg) + } + if pkg.Metadata["base"] != "pacman" || pkg.Metadata["arch"] != "x86_64" || !reflect.DeepEqual(pkg.Metadata["groups"], []string{"base-devel"}) { + t.Errorf("metadata = %+v", pkg.Metadata) + } + + plain, err := reg.FetchPackage(context.Background(), "pacman") + if err != nil || plain.Namespace != "" { + t.Errorf("package without namespace = %+v, %v", plain, err) + } +} + +func TestFetchDependencies(t *testing.T) { + reg, _ := newCore(t) + deps, err := reg.FetchDependencies(context.Background(), "arch/pacman", "7.1.0.r9.g54d9411-4") + if err != nil { + t.Fatal(err) + } + want := []core.Dependency{ + {Name: "bash", Scope: core.Runtime}, + // libcurl.so=4-64 resolves to curl, which is already listed. + {Name: "curl", Scope: core.Runtime}, + {Name: "glibc", Requirements: ">=2.38", Scope: core.Runtime}, + // No package here provides it, so it is kept as written. + {Name: "libfoo.so", Requirements: "=1-64", Scope: core.Runtime}, + {Name: "base-devel", Scope: core.Optional, Optional: true}, + {Name: "perl-locale-gettext", Scope: core.Optional, Optional: true}, + } + if !reflect.DeepEqual(deps, want) { + t.Errorf("deps = %+v\nwant %+v", deps, want) + } + + deps, err = reg.FetchDependencies(context.Background(), "curl", "8.23.0-2") + if err != nil { + t.Fatal(err) + } + if want := []core.Dependency{{Name: "zlib", Scope: core.Runtime}}; !reflect.DeepEqual(deps, want) { + t.Errorf("curl deps = %+v, want %+v", deps, want) + } + + deps, err = reg.FetchDependencies(context.Background(), "pacman-mirrorlist", "20260610-1") + if err != nil || len(deps) != 0 { + t.Errorf("no dependencies = %+v, %v", deps, err) + } +} + +func TestProviderChoice(t *testing.T) { + dbURL, _ := dbServer(t, gzipDB(t, []entry{ + {name: "app-1.0-1/desc", body: "%NAME%\napp\n\n%VERSION%\n1.0-1\n\n%DEPENDS%\nsh\njava-runtime>=17\n\n%OPTDEPENDS%\nsh: for scripts\n"}, + {name: "legacy-1.0-1/desc", body: "%NAME%\nlegacy\n\n%VERSION%\n1.0-1\n\n%DEPENDS%\njava-runtime=11\njava-runtime<11\nsh>=5\n"}, + {name: "zsh-5.9-1/desc", body: "%NAME%\nzsh\n\n%VERSION%\n5.9-1\n\n%PROVIDES%\nsh\n"}, + {name: "bash-5.3-1/desc", body: "%NAME%\nbash\n\n%VERSION%\n5.3-1\n\n%PROVIDES%\nsh\n"}, + {name: "jre-openjdk-21-1/desc", body: "%NAME%\njre-openjdk\n\n%VERSION%\n21-1\n\n%PROVIDES%\njava-runtime=21\n"}, + {name: "jre11-openjdk-11-1/desc", body: "%NAME%\njre11-openjdk\n\n%VERSION%\n11-1\n\n%PROVIDES%\njava-runtime=11\n"}, + })) + reg := New(dbURL, core.DefaultClient()) + deps, err := reg.FetchDependencies(context.Background(), "app", "1.0-1") + if err != nil { + t.Fatal(err) + } + want := []core.Dependency{ + {Name: "bash", Scope: core.Runtime}, + {Name: "jre-openjdk", Scope: core.Runtime}, + {Name: "bash", Scope: core.Optional, Optional: true}, + } + if !reflect.DeepEqual(deps, want) { + t.Errorf("deps = %+v, want %+v", deps, want) + } + + // Only a provided version meeting the constraint counts: jre-openjdk + // sorts first but provides 21, and an unversioned sh meets no >=5. + deps, err = reg.FetchDependencies(context.Background(), "legacy", "1.0-1") + if err != nil { + t.Fatal(err) + } + want = []core.Dependency{ + {Name: "jre11-openjdk", Scope: core.Runtime}, + {Name: "java-runtime", Requirements: "<11", Scope: core.Runtime}, + {Name: "sh", Requirements: ">=5", Scope: core.Runtime}, + } + if !reflect.DeepEqual(deps, want) { + t.Errorf("constrained deps = %+v, want %+v", deps, want) + } +} + +func TestProviderSkipsOtherVersions(t *testing.T) { + dbURL, _ := dbServer(t, gzipDB(t, []entry{ + {name: "app-1-1/desc", body: "%NAME%\napp\n\n%VERSION%\n1-1\n\n%DEPENDS%\napi>=2\nsdk\n"}, + {name: "app-2-1/desc", body: "%NAME%\napp\n\n%VERSION%\n2-1\n\n%DEPENDS%\napi>=2\n\n%PROVIDES%\napi=2\nsdk\n"}, + {name: "lib-2-1/desc", body: "%NAME%\nlib\n\n%VERSION%\n2-1\n\n%PROVIDES%\napi=2\n"}, + })) + reg := New(dbURL, core.DefaultClient()) + + // app-2-1 can't be installed beside app-1-1, so what it provides + // doesn't count: api resolves to lib, and sdk is kept as written. + deps, err := reg.FetchDependencies(context.Background(), "app", "1-1") + if err != nil { + t.Fatal(err) + } + want := []core.Dependency{ + {Name: "lib", Scope: core.Runtime}, + {Name: "sdk", Scope: core.Runtime}, + } + if !reflect.DeepEqual(deps, want) { + t.Errorf("deps = %+v, want %+v", deps, want) + } + + // app-2-1 provides api itself, so it needs nothing else. + deps, err = reg.FetchDependencies(context.Background(), "app", "2-1") + if err != nil || len(deps) != 0 { + t.Errorf("self-provided deps = %+v, %v", deps, err) + } +} + +func TestSatisfies(t *testing.T) { + tests := []struct { + version, requirement string + want bool + }{ + {"21", ">=17", true}, + {"11", ">=17", false}, + {"17", ">17", false}, + {"17", "<=17", true}, + {"11", "<11", false}, + {"4-64", "=4-64", true}, + {"4-64", "=4", true}, // a requirement without pkgrel ignores it + {"4-64", "=5-64", false}, + {"1:1.0", ">=2.0", true}, + {"", ">=1", false}, + {"1", ">=", false}, + } + for _, tt := range tests { + if got := satisfies(tt.version, tt.requirement); got != tt.want { + t.Errorf("satisfies(%q, %q) = %v, want %v", tt.version, tt.requirement, got, tt.want) + } + } +} + +func TestJoinLicenses(t *testing.T) { + tests := []struct { + licenses []string + want string + }{ + {nil, ""}, + {[]string{"Apache-2.0 OR MIT"}, "Apache-2.0 OR MIT"}, + {[]string{"MIT", "curl"}, "MIT AND curl"}, + {[]string{"Apache-2.0 OR MIT", "Unicode-3.0"}, "(Apache-2.0 OR MIT) AND Unicode-3.0"}, + {[]string{"GPL-2.0-only WITH Classpath-exception-2.0", "MIT"}, "(GPL-2.0-only WITH Classpath-exception-2.0) AND MIT"}, + } + for _, tt := range tests { + if got := joinLicenses(tt.licenses); got != tt.want { + t.Errorf("joinLicenses(%q) = %q, want %q", tt.licenses, got, tt.want) + } + } +} + +func TestFetchMaintainers(t *testing.T) { + reg, _ := newCore(t) + maintainers, err := reg.FetchMaintainers(context.Background(), "arch/pacman") + if err != nil { + t.Fatal(err) + } + if want := []core.Maintainer{{Name: "Pierre Schmitz", Email: "pierre@archlinux.org"}}; !reflect.DeepEqual(maintainers, want) { + t.Errorf("maintainers = %+v", maintainers) + } + + maintainers, err = reg.FetchMaintainers(context.Background(), "curl") + if err != nil { + t.Fatal(err) + } + if want := []core.Maintainer{{Name: "Arch Build System"}}; !reflect.DeepEqual(maintainers, want) { + t.Errorf("unstructured maintainers = %+v", maintainers) + } + + maintainers, err = reg.FetchMaintainers(context.Background(), "bash") + if err != nil || maintainers != nil { + t.Errorf("no packager = %+v, %v", maintainers, err) + } +} + +func TestParseMaintainer(t *testing.T) { + tests := map[string]core.Maintainer{ + "Pierre Schmitz ": {Name: "Pierre Schmitz", Email: "pierre@archlinux.org"}, + "": {Email: "pierre@archlinux.org"}, + "Unknown Packager": {Name: "Unknown Packager"}, + "Someone ": {Name: "Someone "}, + "Someone <>": {Name: "Someone <>"}, + } + for in, want := range tests { + if got := parseMaintainer(in); got != want { + t.Errorf("parseMaintainer(%q) = %+v, want %+v", in, got, want) + } + } +} + +func TestMissingOptionalFields(t *testing.T) { + dbURL, _ := dbServer(t, gzipDB(t, []entry{{name: "bare-1.0-1/desc", body: "%NAME%\nbare\n\n%VERSION%\n1.0-1\n"}})) + reg := New(dbURL, core.DefaultClient()) + versions, err := reg.FetchVersions(context.Background(), "bare") + if err != nil { + t.Fatal(err) + } + v := versions[0] + if v.Number != "1.0-1" || v.Integrity != "" || v.Licenses != "" || !v.PublishedAt.IsZero() || len(v.Artifacts) != 0 { + t.Errorf("version = %+v", v) + } + pkg, err := reg.FetchPackage(context.Background(), "bare") + if err != nil || pkg.Description != "" || pkg.Homepage != "" { + t.Errorf("package = %+v, %v", pkg, err) + } +} + +func TestSectionsWithoutBlankLines(t *testing.T) { + // Blank lines between sections are optional; a %KEY% line ends the + // section before it. + body := "%NAME%\nfoo\n%VERSION%\n1.0-1\n%GROUPS%\n%CSIZE%\n42\n%DEPENDS%\nbar\nbaz>=2\n" + dbURL, _ := dbServer(t, gzipDB(t, []entry{{name: "foo-1.0-1/desc", body: body}})) + reg := New(dbURL, core.DefaultClient()) + versions, err := reg.FetchVersions(context.Background(), "foo") + if err != nil { + t.Fatal(err) + } + if v := versions[0]; v.Number != "1.0-1" || v.Metadata["size"] != int64(42) || !reflect.DeepEqual(v.Metadata["groups"], []string(nil)) { + t.Errorf("version = %+v", v) + } + deps, err := reg.FetchDependencies(context.Background(), "foo", "1.0-1") + if err != nil { + t.Fatal(err) + } + want := []core.Dependency{ + {Name: "bar", Scope: core.Runtime}, + {Name: "baz", Requirements: ">=2", Scope: core.Runtime}, + } + if !reflect.DeepEqual(deps, want) { + t.Errorf("deps = %+v, want %+v", deps, want) + } +} + +func TestOlderDatabaseLayout(t *testing.T) { + // Older databases keep dependencies in a depends file, and .files + // databases add a files list; top-level files are not packages. + dbURL, _ := dbServer(t, gzipDB(t, []entry{ + {name: "./", dir: true}, + {name: "./old-1.0-1/", dir: true}, + {name: "./old-1.0-1/desc", body: "%FILENAME%\nold-1.0-1-x86_64.pkg.tar.xz\n\n%NAME%\nold\n\n%VERSION%\n1.0-1\n\n%SHA256SUM%\nnot hex\n"}, + {name: "./old-1.0-1/depends", body: "%DEPENDS%\nglibc\n"}, + {name: "./old-1.0-1/files", body: "%FILES%\nusr/\nusr/bin/old\n"}, + {name: "./old-1.0-1/link", typeflag: tar.TypeSymlink}, + {name: "README", body: "not a package"}, + })) + reg := New(dbURL, core.DefaultClient()) + deps, err := reg.FetchDependencies(context.Background(), "old", "1.0-1") + if err != nil { + t.Fatal(err) + } + if want := []core.Dependency{{Name: "glibc", Scope: core.Runtime}}; !reflect.DeepEqual(deps, want) { + t.Errorf("deps = %+v", deps) + } + versions, err := reg.FetchVersions(context.Background(), "old") + if err != nil { + t.Fatal(err) + } + if versions[0].Integrity != "" || versions[0].Artifacts[0].Integrity != "" { + t.Errorf("a SHA256SUM that is not one gives no integrity: %+v", versions[0]) + } +} + +func TestMalformedDatabases(t *testing.T) { + desc := func(name, version string) string { + return "%NAME%\n" + name + "\n\n%VERSION%\n" + version + "\n" + } + tarOf := func(entries ...entry) func(t *testing.T) []byte { + return func(t *testing.T) []byte { return gzipDB(t, entries) } + } + tests := []struct { + name string + body func(t *testing.T) []byte + }{ + {"empty body", func(t *testing.T) []byte { return nil }}, + {"not an archive", func(t *testing.T) []byte { return []byte("not found") }}, + {"truncated gzip", func(t *testing.T) []byte { + db := gzipDB(t, coreEntries) + return db[:len(db)/2] + }}, + {"corrupt gzip trailer", func(t *testing.T) []byte { + db := gzipDB(t, coreEntries) + db[len(db)-5] ^= 0xff + return db + }}, + {"truncated zstd", func(t *testing.T) []byte { + db := compress(t, "zstd", buildTar(t, coreEntries)) + return db[:len(db)/2] + }}, + {"truncated xz", func(t *testing.T) []byte { + db := compress(t, "xz", buildTar(t, coreEntries)) + return db[:len(db)/2] + }}, + {"parent path", tarOf(entry{name: "../foo-1.0-1/desc", body: desc("foo", "1.0-1")})}, + {"inner parent path", tarOf(entry{name: "foo-1.0-1/../../desc", body: desc("foo", "1.0-1")})}, + {"absolute path", tarOf(entry{name: "/foo-1.0-1/desc", body: desc("foo", "1.0-1")})}, + {"backslash path", tarOf(entry{name: `foo-1.0-1\..\desc`, body: desc("foo", "1.0-1")})}, + {"nested path", tarOf(entry{name: "foo-1.0-1/sub/desc", body: desc("foo", "1.0-1")})}, + {"directory without version", tarOf(entry{name: "foo/desc", body: desc("foo", "1.0-1")})}, + {"directory without pkgrel", tarOf(entry{name: "foo-1.0/desc", body: desc("foo", "1.0")})}, + {"name mismatch", tarOf(entry{name: "foo-1.0-1/desc", body: desc("bar", "1.0-1")})}, + {"version mismatch", tarOf(entry{name: "foo-1.0-1/desc", body: desc("foo", "1.0-2")})}, + {"filename with a path", tarOf(entry{name: "foo-1.0-1/desc", body: desc("foo", "1.0-1") + "\n%FILENAME%\n../foo-1.0-1-any.pkg.tar.zst\n"})}, + {"hidden filename", tarOf(entry{name: "foo-1.0-1/desc", body: desc("foo", "1.0-1") + "\n%FILENAME%\n.foo-1.0-1-any.pkg.tar.zst\n"})}, + {"filename with a query", tarOf(entry{name: "foo-1.0-1/desc", body: desc("foo", "1.0-1") + "\n%FILENAME%\nfoo.pkg.tar.zst?x=1\n"})}, + {"line outside a key", tarOf(entry{name: "foo-1.0-1/desc", body: "foo\n\n" + desc("foo", "1.0-1")})}, + {"bad size", tarOf(entry{name: "foo-1.0-1/desc", body: desc("foo", "1.0-1") + "\n%CSIZE%\nlarge\n"})}, + {"negative size", tarOf(entry{name: "foo-1.0-1/desc", body: desc("foo", "1.0-1") + "\n%CSIZE%\n-1\n"})}, + {"signed installed size", tarOf(entry{name: "foo-1.0-1/desc", body: desc("foo", "1.0-1") + "\n%ISIZE%\n+1\n"})}, + {"bad build date", tarOf(entry{name: "foo-1.0-1/desc", body: desc("foo", "1.0-1") + "\n%BUILDDATE%\nyesterday\n"})}, + {"oversized desc", tarOf(entry{name: "foo-1.0-1/desc", body: desc("foo", "1.0-1") + "\n%DESC%\n" + strings.Repeat("x", maxEntrySize) + "\n"})}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + dbURL, _ := dbServer(t, tt.body(t)) + _, err := New(dbURL, core.DefaultClient()).FetchVersions(context.Background(), "foo") + if !errors.Is(err, ErrMalformedDatabase) { + t.Errorf("err = %v, want ErrMalformedDatabase", err) + } + }) + } +} + +func TestDecompressedLimit(t *testing.T) { + plain := buildTar(t, coreEntries) + for _, format := range []string{"gzip", "zstd", "xz", "tar"} { + t.Run(format, func(t *testing.T) { + dbURL, _ := dbServer(t, compress(t, format, plain)) + for _, limit := range []int64{int64(len(plain)) - 1, int64(len(plain)) / 2} { + r := New(dbURL, core.DefaultClient()) + r.maxDatabaseSize = limit + if _, err := r.FetchVersions(context.Background(), "curl"); !errors.Is(err, ErrMalformedDatabase) || !strings.Contains(err.Error(), "decompresses to more than") { + t.Errorf("limit %d: err = %v, want ErrMalformedDatabase naming the limit", limit, err) + } + } + r := New(dbURL, core.DefaultClient()) + r.maxDatabaseSize = int64(len(plain)) + if _, err := r.FetchVersions(context.Background(), "curl"); err != nil { + t.Errorf("at the limit: %v", err) + } + }) + } +} + +func TestInvalidConfiguration(t *testing.T) { + for _, u := range []string{"", "core.db", "https://geo.mirror.pkgbuild.com", "https://geo.mirror.pkgbuild.com/core/os/x86_64/"} { + _, err := New(u, nil).FetchPackage(context.Background(), "pacman") + if !errors.Is(err, ErrInvalidConfig) { + t.Errorf("New(%q): err = %v, want ErrInvalidConfig", u, err) + } + } +} + +func TestDatabaseURLWithQuery(t *testing.T) { + var gotQuery string + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + gotQuery = r.URL.RawQuery + _, _ = w.Write(gzipDB(t, coreEntries)) + })) + defer server.Close() + + versions, err := New(server.URL+"/core/os/x86_64/core.db?v=2", core.DefaultClient()).FetchVersions(context.Background(), "curl") + if err != nil { + t.Fatal(err) + } + if gotQuery != "v=2" { + t.Errorf("query = %q, want the database URL's", gotQuery) + } + if want := server.URL + "/core/os/x86_64/curl-8.23.0-2-x86_64.pkg.tar.zst"; versions[0].Artifacts[0].URL != want { + t.Errorf("artifact URL = %q, want %q", versions[0].Artifacts[0].URL, want) + } +} + +func TestNotFoundAndCaching(t *testing.T) { + dbURL, requests := dbServer(t, gzipDB(t, coreEntries)) + reg := New(dbURL, core.DefaultClient()) + ctx := context.Background() + + var nf *core.NotFoundError + if _, err := reg.FetchPackage(ctx, "arch/missing"); !errors.As(err, &nf) || nf.Name != "arch/missing" { + t.Errorf("missing package: err = %v", err) + } + if _, err := reg.FetchVersions(ctx, "missing"); !errors.As(err, &nf) { + t.Errorf("missing versions: err = %v", err) + } + if _, err := reg.FetchDependencies(ctx, "curl", "1.0-1"); !errors.As(err, &nf) || nf.Version != "1.0-1" { + t.Errorf("missing version: err = %v", err) + } + if _, err := reg.FetchMaintainers(ctx, "missing"); !errors.As(err, &nf) { + t.Errorf("missing maintainers: err = %v", err) + } + if n := requests.Load(); n != 1 { + t.Errorf("database fetched %d times, want 1", n) + } + + _, err := New(strings.Replace(dbURL, "core.db", "extra.db", 1), core.DefaultClient()).FetchPackage(ctx, "curl") + var httpErr *core.HTTPError + if !errors.As(err, &httpErr) || !httpErr.IsNotFound() { + t.Errorf("missing database: err = %v", err) + } +} + +func TestFailedReadIsRetried(t *testing.T) { + var requests atomic.Int32 + good := gzipDB(t, coreEntries) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if requests.Add(1) == 1 { + _, _ = w.Write(good[:len(good)/2]) + return + } + _, _ = w.Write(good) + })) + defer server.Close() + + reg := New(server.URL+"/core.db", core.DefaultClient()) + if _, err := reg.FetchPackage(context.Background(), "curl"); !errors.Is(err, ErrMalformedDatabase) { + t.Fatalf("first read: err = %v, want ErrMalformedDatabase", err) + } + if _, err := reg.FetchPackage(context.Background(), "curl"); err != nil { + t.Errorf("second read: %v", err) + } +} + +type tokenTransport struct{ base http.RoundTripper } + +func (t tokenTransport) RoundTrip(req *http.Request) (*http.Response, error) { + req = req.Clone(req.Context()) + req.Header.Set("Authorization", "Bearer secret") + return t.base.RoundTrip(req) +} + +func TestUsesSuppliedHTTPClient(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Header.Get("Authorization") != "Bearer secret" { + w.WriteHeader(http.StatusUnauthorized) + return + } + _, _ = w.Write(gzipDB(t, coreEntries)) + })) + defer server.Close() + + if _, err := New(server.URL+"/core.db", core.DefaultClient()).FetchVersions(context.Background(), "curl"); err == nil { + t.Error("FetchVersions without credentials succeeded") + } + client := core.DefaultClient() + client.HTTPClient = &http.Client{Transport: tokenTransport{base: http.DefaultTransport}} + if _, err := New(server.URL+"/core.db", client).FetchVersions(context.Background(), "curl"); err != nil { + t.Errorf("FetchVersions through authenticated client: %v", err) + } +} + +func TestSplitEntryName(t *testing.T) { + tests := []struct { + dir, name, version string + ok bool + }{ + {"pacman-7.1.0.r9.g54d9411-4", "pacman", "7.1.0.r9.g54d9411-4", true}, + {"pacman-mirrorlist-20260610-1", "pacman-mirrorlist", "20260610-1", true}, + {"zlib-1:1.4-1", "zlib", "1:1.4-1", true}, + {"foo-1.0", "", "", false}, + {"foo", "", "", false}, + {"-1.0-1", "", "", false}, + {"foo--1", "", "", false}, + {"foo-1.0-", "", "", false}, + } + for _, tt := range tests { + name, version, ok := splitEntryName(tt.dir) + if name != tt.name || version != tt.version || ok != tt.ok { + t.Errorf("splitEntryName(%q) = %q, %q, %v", tt.dir, name, version, ok) + } + } +} + +func TestURLs(t *testing.T) { + u := New("https://geo.mirror.pkgbuild.com/core/os/x86_64/core.db", nil).URLs() + tests := [][2]string{ + {u.PURL("arch/pacman", "7.1.0.r9.g54d9411-4"), "pkg:alpm/arch/pacman@7.1.0.r9.g54d9411-4?repository_url=https:%2F%2Fgeo.mirror.pkgbuild.com%2Fcore%2Fos%2Fx86_64%2Fcore.db"}, + {u.PURL("arch/zlib", "1:1.4-1"), "pkg:alpm/arch/zlib@1:1.4-1?repository_url=https:%2F%2Fgeo.mirror.pkgbuild.com%2Fcore%2Fos%2Fx86_64%2Fcore.db"}, + {u.Download("arch/pacman", "7.1.0.r9.g54d9411-4"), ""}, + {u.Registry("arch/pacman", ""), ""}, + {u.Documentation("arch/pacman", ""), ""}, + } + for _, tt := range tests { + if tt[0] != tt[1] { + t.Errorf("got %q, want %q", tt[0], tt[1]) + } + } +} diff --git a/registries_test.go b/registries_test.go index 1fdc450..6b93543 100644 --- a/registries_test.go +++ b/registries_test.go @@ -20,7 +20,7 @@ import ( func TestSupportedEcosystems(t *testing.T) { ecosystems := registries.SupportedEcosystems() - expected := []string{"apk", "apm", "brew", "cargo", "clojars", "cocoapods", "composer", "conda", "cpan", "cran", "deb", "deno", "dub", "elm", "gem", "githubactions", "golang", "hackage", "haxelib", "helm", "hex", "julia", "luarocks", "maven", "nimble", "npm", "nuget", "pub", "pypi", "rpm", "swift", "terraform", "vscode-extension"} + expected := []string{"alpm", "apk", "apm", "brew", "cargo", "clojars", "cocoapods", "composer", "conda", "cpan", "cran", "deb", "deno", "dub", "elm", "gem", "githubactions", "golang", "hackage", "haxelib", "helm", "hex", "julia", "luarocks", "maven", "nimble", "npm", "nuget", "pub", "pypi", "rpm", "swift", "terraform", "vscode-extension"} sort.Strings(ecosystems) if len(ecosystems) != len(expected) { @@ -69,6 +69,7 @@ func TestNew(t *testing.T) { {"helm", true}, {"swift", true}, {"apm", true}, + {"alpm", true}, {"apk", true}, {"deb", true}, {"rpm", true}, @@ -120,6 +121,7 @@ func TestDefaultURL(t *testing.T) { {"helm", ""}, {"swift", ""}, {"apm", ""}, + {"alpm", ""}, {"apk", ""}, {"deb", ""}, {"rpm", ""}, @@ -349,3 +351,53 @@ func apkIndex(t *testing.T, index string) []byte { } return out.Bytes() } + +func TestALPMFromPURL(t *testing.T) { + desc := "%FILENAME%\npacman-7.1.0-4-x86_64.pkg.tar.zst\n\n%NAME%\npacman\n\n%VERSION%\n7.1.0-4\n\n%ARCH%\nx86_64\n\n%DEPENDS%\ncurl\n" + var buf bytes.Buffer + gz := gzip.NewWriter(&buf) + tw := tar.NewWriter(gz) + if err := tw.WriteHeader(&tar.Header{Name: "pacman-7.1.0-4/desc", Mode: 0o644, Size: int64(len(desc))}); err != nil { + t.Fatal(err) + } + if _, err := tw.Write([]byte(desc)); err != nil { + t.Fatal(err) + } + if err := tw.Close(); err != nil { + t.Fatal(err) + } + if err := gz.Close(); err != nil { + t.Fatal(err) + } + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/core/os/x86_64/core.db" { + http.NotFound(w, r) + return + } + _, _ = w.Write(buf.Bytes()) + })) + defer srv.Close() + + purl := "pkg:alpm/arch/pacman@7.1.0-4?arch=x86_64&repository_url=" + srv.URL + "/core/os/x86_64/core.db" + v, err := registries.FetchVersionFromPURL(context.Background(), purl, nil) + if err != nil { + t.Fatalf("FetchVersionFromPURL failed: %v", err) + } + if v.Number != "7.1.0-4" || v.Artifacts[0].URL != srv.URL+"/core/os/x86_64/pacman-7.1.0-4-x86_64.pkg.tar.zst" { + t.Errorf("version = %+v", v) + } + + pkg, err := registries.FetchPackageFromPURL(context.Background(), purl, nil) + if err != nil || pkg.Namespace != "arch" || pkg.Name != "pacman" { + t.Errorf("package = %+v, %v", pkg, err) + } + + deps, err := registries.FetchDependenciesFromPURL(context.Background(), purl, nil) + if err != nil || len(deps) != 1 || deps[0].Name != "curl" { + t.Errorf("deps = %+v, %v", deps, err) + } + + if _, err := registries.FetchVersionFromPURL(context.Background(), "pkg:alpm/arch/pacman@7.1.0-4?arch=x86_64", nil); err == nil || !strings.Contains(err.Error(), "no registry URL configured") { + t.Errorf("missing URL err = %v", err) + } +}