From 36e6014678ccfb91bf854683e7f66a8df14da8eb Mon Sep 17 00:00:00 2001 From: Simon Chrzanowski Date: Mon, 23 Nov 2026 17:16:36 +0100 Subject: [PATCH] Extract portable Conda metadata transformations The repodata.json cooldown filter, the publish-time index, the sharded repodata index rewrite and shard filter, the timestamp rule and the filename parser move from internal/handler to internal/metadata/conda, which takes its inputs explicitly and doesn't depend on handler.Proxy. The repodata filter still streams. Fetching, caches, ETag reuse, size bounds and the zstd framing of shards stay in the handler, whose function names remain as thin wrappers. Shards are now checked with Evaluate at one EvaluatedAt per shard instead of IsAllowed per record, as repodata already was. --- internal/handler/conda.go | 191 ++------ internal/handler/conda_shards.go | 310 +------------ internal/handler/cooldown_supported_test.go | 7 + internal/metadata/conda/imports_test.go | 49 ++ internal/metadata/conda/metadata.go | 69 +++ internal/metadata/conda/metadata_test.go | 489 ++++++++++++++++++++ internal/metadata/conda/repodata.go | 150 ++++++ internal/metadata/conda/shards.go | 335 ++++++++++++++ 8 files changed, 1151 insertions(+), 449 deletions(-) create mode 100644 internal/metadata/conda/imports_test.go create mode 100644 internal/metadata/conda/metadata.go create mode 100644 internal/metadata/conda/metadata_test.go create mode 100644 internal/metadata/conda/repodata.go create mode 100644 internal/metadata/conda/shards.go diff --git a/internal/handler/conda.go b/internal/handler/conda.go index a609f0fc..6bc27f4b 100644 --- a/internal/handler/conda.go +++ b/internal/handler/conda.go @@ -5,12 +5,9 @@ import ( "bytes" "compress/gzip" "context" - "crypto/sha256" "encoding/hex" - "encoding/json" "errors" "fmt" - "hash" "io" "net/http" "slices" @@ -18,15 +15,12 @@ import ( "sync" "time" - "github.com/git-pkgs/proxy/internal/jsonstream" + "github.com/git-pkgs/proxy/internal/metadata/conda" "github.com/git-pkgs/proxy/internal/retention" "github.com/git-pkgs/purl" ) -const ( - condaUpstream = "https://conda.anaconda.org" - minCondaParts = 3 // name-version-build requires at least 3 hyphen-separated parts -) +const condaUpstream = "https://conda.anaconda.org" // Packages are stored under the name {channel}/{name}, which purl writes as // pkg:conda/{channel}%2F{name}. Package rules name the channel as the @@ -175,41 +169,10 @@ func (h *CondaHandler) parseFilename(filename string) (name, version string) { } // CondaFilenameIdentity returns the name and version a download of filename -// is cached under, or empty strings when it is not a package file name. -// Conda filenames are: {name}-{version}-{build}.{ext} -// e.g., "numpy-1.24.0-py311h64a7726_0.conda" +// is cached under, or empty strings when it is not a package file name (see +// conda.FilenameIdentity). func CondaFilenameIdentity(filename string) (name, version string) { - // Remove extension - base := filename - for _, ext := range []string{".conda", ".tar.bz2"} { - if strings.HasSuffix(base, ext) { - base = strings.TrimSuffix(base, ext) - break - } - } - - // Split by hyphens, the format is name-version-build - // The name can contain hyphens, so we need to find version-build at the end - parts := strings.Split(base, "-") - if len(parts) < minCondaParts { - return "", "" - } - - // Build is the last part, version is second to last - // Everything before is the name - build := parts[len(parts)-1] - version = parts[len(parts)-2] - name = strings.Join(parts[:len(parts)-2], "-") - - // Version should start with a digit - if len(version) == 0 || version[0] < '0' || version[0] > '9' { - return "", "" - } - - // Include build in version for uniqueness - _ = build - - return name, version + return conda.FilenameIdentity(filename) } // isCondaRepodataVariant reports whether filename is a form of a subdir's @@ -407,17 +370,18 @@ func (h *CondaHandler) repodataNotModified(w http.ResponseWriter, r *http.Reques // identified by digest. The copy depends only on the document, the startup // configuration and which entries were left out, and those stay left out // until the first of them leaves cooldown. -func (h *CondaHandler) rememberRepodata(cacheKey, digest string, filter *repodataFilter) { - if filter.unknownUntil { +func (h *CondaHandler) rememberRepodata(cacheKey, digest string, filter *conda.Filter) { + until, known := filter.Until() + if !known { return } - etag := keptVersionsETag(digest, "", cacheKey, []string{hex.EncodeToString(filter.withheld.Sum(nil))}) + etag := keptVersionsETag(digest, "", cacheKey, []string{hex.EncodeToString(filter.Withheld())}) h.repodataMu.Lock() defer h.repodataMu.Unlock() if h.repodataStates == nil { h.repodataStates = make(map[string]repodataState) } - h.repodataStates[cacheKey] = repodataState{digest: digest, etag: etag, until: filter.until} + h.repodataStates[cacheKey] = repodataState{digest: digest, etag: etag, until: until} } // countingWriter counts the bytes written through it, such as whether @@ -433,19 +397,6 @@ func (c *countingWriter) Write(p []byte) (int, error) { return n, err } -// condaMaxSecondsTimestamp is the last second of year 9999. Like conda, a -// larger repodata timestamp is read as milliseconds and a smaller one as -// seconds, which some older entries use. -const condaMaxSecondsTimestamp = 253402300799 - -// condaTime returns the time a repodata timestamp names. -func condaTime(timestamp float64) time.Time { - if timestamp > condaMaxSecondsTimestamp { - return time.UnixMilli(int64(timestamp)).Truncate(time.Second) - } - return time.Unix(int64(timestamp), 0) -} - const ( repodataWriteBuffer = 64 << 10 // maxRepodataSize stops a runaway upstream body. It is well above the @@ -461,90 +412,29 @@ func (h *CondaHandler) filterRepodata(r io.Reader, w io.Writer) error { } // filterRepodataWith is filterRepodata deciding by filter. -func (h *CondaHandler) filterRepodataWith(r io.Reader, w io.Writer, filter *repodataFilter) error { - return jsonstream.CopyObject(r, w, func(m *jsonstream.Member) error { - if m.Key != "packages" && m.Key != "packages.conda" { - return m.Copy() - } - return m.Object(func(entry *jsonstream.Member) error { - raw, err := entry.Raw() - if err != nil { - return err - } - if filter.inCooldown(entry.Key, raw) { - return nil - } - return entry.Write(raw) - }) - }) -} - -type repodataEntry struct { - Name string `json:"name"` - Version string `json:"version"` - Timestamp float64 `json:"timestamp"` +func (h *CondaHandler) filterRepodataWith(r io.Reader, w io.Writer, filter *conda.Filter) error { + return filter.Copy(r, w) } -// repodataFilter decides which repodata entries cooldown leaves out, all as -// of one time, and records what it left out, which with the document fixes -// the filtered copy. -type repodataFilter struct { - h *CondaHandler - now time.Time - // withheld hashes the filenames left out. - withheld hash.Hash - // until is when the first entry left out leaves cooldown. - until time.Time - // unknownUntil is set when an entry was left out without a time it - // leaves cooldown, so until can't be relied on. - unknownUntil bool -} - -func (h *CondaHandler) newRepodataFilter(now time.Time) *repodataFilter { - return &repodataFilter{h: h, now: now, withheld: sha256.New()} +// newRepodataFilter returns a filter deciding which repodata entries +// cooldown leaves out as of now (see conda.Filter). +func (h *CondaHandler) newRepodataFilter(now time.Time) *conda.Filter { + return conda.NewFilter(h.cooldownOptions(now)) } -// inCooldown reports whether a repodata entry was published too recently. -// Entries without a name or timestamp are kept. -func (f *repodataFilter) inCooldown(filename string, raw []byte) bool { - var entry repodataEntry - if err := json.Unmarshal(raw, &entry); err != nil { - return false - } - if entry.Name == "" || entry.Timestamp == 0 { - return false +// cooldownOptions is how repodata and shards are filtered as of now. +func (h *CondaHandler) cooldownOptions(now time.Time) conda.Options { + return conda.Options{ + Cooldown: h.proxy.cooldown(), + EvaluatedAt: now, + OnCooldownFilter: h.cooldownFiltered, } - publishedAt := condaTime(entry.Timestamp) - decision := f.h.proxy.cooldown().Evaluate("conda", canonicalPackagePURL("conda", entry.Name), publishedAt, f.now) - if decision.Allowed { - return false - } - f.h.proxy.Logger.Info("cooldown: filtering conda package", - "name", entry.Name, "version", entry.Version, "filename", filename) - _, _ = fmt.Fprintf(f.withheld, "%d:%s", len(filename), filename) - switch { - case decision.AvailableAt.IsZero(): - f.unknownUntil = true - case f.until.IsZero() || decision.AvailableAt.Before(f.until): - f.until = decision.AvailableAt - } - return true } -// recordInCooldown reports whether a package record with a repodata -// timestamp was published too recently. Records without a name or -// timestamp are kept. -func (h *CondaHandler) recordInCooldown(filename, name, version string, timestamp float64) bool { - if name == "" || timestamp == 0 { - return false - } - publishedAt := condaTime(timestamp) - if h.proxy.cooldown().IsAllowed("conda", canonicalPackagePURL("conda", name), publishedAt) { - return false - } +// cooldownFiltered logs a package file cooldown leaves out. +func (h *CondaHandler) cooldownFiltered(filename, name, version string) { h.proxy.Logger.Info("cooldown: filtering conda package", "name", name, "version", version, "filename", filename) - return true } // metadataCacheKey is the metadata cache key of a request path. @@ -628,35 +518,12 @@ func (h *CondaHandler) streamRepodataIndex(ctx context.Context, upstreamURL stri } // readRepodataIndex maps each package file in a repodata.json to its -// timestamp, or the zero time for a file without one. It reads the document as it -// streams, under the same bound as filterRepodata, so the decompressed size -// is not limited by metadata_max_size. +// timestamp, or the zero time for a file without one (see conda.ReadIndex). +// It reads the document as it streams, under the same bound as +// filterRepodata, so the decompressed size is not limited by +// metadata_max_size. func readRepodataIndex(r io.Reader) (map[string]time.Time, error) { - index := make(map[string]time.Time) - err := jsonstream.CopyObject(io.LimitReader(r, maxRepodataSize), io.Discard, func(m *jsonstream.Member) error { - if m.Key != "packages" && m.Key != "packages.conda" { - return m.Copy() - } - return m.Object(func(entry *jsonstream.Member) error { - raw, err := entry.Raw() - if err != nil { - return err - } - var e repodataEntry - if json.Unmarshal(raw, &e) != nil { - return nil - } - index[entry.Key] = time.Time{} - if e.Timestamp != 0 { - index[entry.Key] = condaTime(e.Timestamp) - } - return nil - }) - }) - if err != nil { - return nil, err - } - return index, nil + return conda.ReadIndex(io.LimitReader(r, maxRepodataSize)) } // proxyCached forwards a metadata request with caching. diff --git a/internal/handler/conda_shards.go b/internal/handler/conda_shards.go index dbfaee2b..040f1497 100644 --- a/internal/handler/conda_shards.go +++ b/internal/handler/conda_shards.go @@ -1,45 +1,34 @@ package handler import ( - "bytes" - "crypto/sha256" "encoding/hex" - "errors" "fmt" "net/http" - "net/url" "path" "strconv" "strings" "sync" "time" + "github.com/git-pkgs/proxy/internal/metadata/conda" "github.com/klauspost/compress/zstd" - "github.com/vmihailenco/msgpack/v5" ) -// Sharded repodata (CEP 16) maps each package name to the sha256 of its -// shard. With cooldown the proxy filters shards, which changes their bytes, -// but clients cache shards by hash and never fetch the same hash again. So -// the rewritten index XORs every hash with a mask that changes each hour: -// filtered shards get hashes of their own, and clients fetch them again once -// versions have left cooldown. +// Sharded repodata (CEP 16): with cooldown the index is rewritten to point +// at filtered shards under hashes masked per hour (see conda.ShardMask). const ( condaShardIndexFile = "repodata_shards.msgpack.zst" - condaShardSuffix = ".msgpack.zst" - condaCooldownShardDir = "cooldown-shards" - condaShardsSubdir = "shards/" + condaShardSuffix = conda.ShardSuffix + condaCooldownShardDir = conda.CooldownShardDir + condaShardsSubdir = conda.ShardsSubdir condaShardBucket = time.Hour - condaShardIndexFormat = 1 - condaShardHashLen = sha256.Size + condaShardHashLen = conda.ShardHashLen // maxCondaShardSize bounds a decompressed index or shard. conda-forge's // largest index is a few MB. maxCondaShardSize = 256 << 20 ) var ( - errCondaShardLayout = errors.New("unsupported sharded repodata layout") - condaZstd = sync.OnceValues(func() (*zstd.Decoder, error) { return zstd.NewReader(nil, zstd.WithDecoderMaxMemory(maxCondaShardSize), zstd.WithDecoderConcurrency(0)) }) @@ -68,7 +57,7 @@ func (h *CondaHandler) handleShardIndex(w http.ResponseWriter, r *http.Request) if !h.cooldownEnabled() { index, err := decodeCondaShardIndex(body) if err == nil { - _, err = index.shardsLayout(upstreamURL) + _, err = index.ShardsLayout(upstreamURL) } if err != nil { h.proxy.Logger.Info("serving no sharded repodata", "url", upstreamURL, "error", err) @@ -141,76 +130,13 @@ func (h *CondaHandler) handleCooldownShard(w http.ResponseWriter, r *http.Reques } func isCondaShardFile(name string) bool { - hash, ok := strings.CutSuffix(name, condaShardSuffix) - if !ok || len(hash) != 2*condaShardHashLen { - return false - } - _, err := hex.DecodeString(hash) - return err == nil && strings.ToLower(hash) == hash + return conda.IsShardFile(name) } -// condaShardMask is XORed with shard hashes in a rewritten index. It keeps -// filtered shards apart from upstream ones in client caches, which are keyed -// by hash alone. +// condaShardMask is XORed with shard hashes in a rewritten index (see +// conda.ShardMask). func condaShardMask(channel, arch, bucket string) [condaShardHashLen]byte { - return sha256.Sum256([]byte("git-pkgs proxy conda cooldown shard\x00" + channel + "\x00" + arch + "\x00" + bucket)) -} - -// msgpackEntry is one member of a msgpack map, kept in its upstream order -// with its value undecoded. -type msgpackEntry struct { - key string - value msgpack.RawMessage -} - -func decodeMsgpackMap(b []byte) ([]msgpackEntry, error) { - dec := msgpack.NewDecoder(bytes.NewReader(b)) - n, err := dec.DecodeMapLen() - if err != nil { - return nil, err - } - if n < 0 { - return nil, errors.New("expected a msgpack map") - } - entries := make([]msgpackEntry, 0, n) - for range n { - key, err := dec.DecodeString() - if err != nil { - return nil, err - } - value, err := dec.DecodeRaw() - if err != nil { - return nil, err - } - entries = append(entries, msgpackEntry{key: key, value: value}) - } - return entries, nil -} - -func encodeMsgpackMap(entries []msgpackEntry) ([]byte, error) { - var buf bytes.Buffer - enc := msgpack.NewEncoder(&buf) - if err := enc.EncodeMapLen(len(entries)); err != nil { - return nil, err - } - for _, e := range entries { - if err := enc.EncodeString(e.key); err != nil { - return nil, err - } - if err := enc.Encode(e.value); err != nil { - return nil, err - } - } - return buf.Bytes(), nil -} - -func lookupMsgpackEntry(entries []msgpackEntry, key string) (int, bool) { - for i, e := range entries { - if e.key == key { - return i, true - } - } - return -1, false + return conda.ShardMask(channel, arch, bucket) } func decompressCondaShard(body []byte) ([]byte, error) { @@ -229,230 +155,40 @@ func compressCondaShard(body []byte) ([]byte, error) { return enc.EncodeAll(body, nil), nil } -// condaShardIndex is a decoded repodata_shards.msgpack.zst. -type condaShardIndex struct { - top []msgpackEntry - info []msgpackEntry -} - -func decodeCondaShardIndex(body []byte) (*condaShardIndex, error) { +// decodeCondaShardIndex decodes a repodata_shards.msgpack.zst. +func decodeCondaShardIndex(body []byte) (*conda.ShardIndex, error) { raw, err := decompressCondaShard(body) if err != nil { return nil, err } - top, err := decodeMsgpackMap(raw) - if err != nil { - return nil, err - } - i, ok := lookupMsgpackEntry(top, "version") - if !ok { - return nil, errors.New("sharded index has no version") - } - var version int - if err := msgpack.Unmarshal(top[i].value, &version); err != nil || version != condaShardIndexFormat { - return nil, fmt.Errorf("unsupported sharded index version %v", top[i].value) - } - i, ok = lookupMsgpackEntry(top, "info") - if !ok { - return nil, errors.New("sharded index has no info") - } - info, err := decodeMsgpackMap(top[i].value) - if err != nil { - return nil, err - } - return &condaShardIndex{top: top, info: info}, nil -} - -func (idx *condaShardIndex) infoString(key string) (string, error) { - i, ok := lookupMsgpackEntry(idx.info, key) - if !ok { - return "", nil - } - var s string - err := msgpack.Unmarshal(idx.info[i].value, &s) - return s, err -} - -// shardsLayout checks that packages and shards sit where the proxy routes -// them, below the subdir of indexURL, and returns the shards directory -// relative to the subdir: "" or "shards/". Clients resolve base_url and -// shards_base_url against the proxy's URL, so only relative paths stay on -// the proxy: a scheme or host leads clients around it, a leading / outside -// its mount. -func (idx *condaShardIndex) shardsLayout(indexURL string) (string, error) { - base, err := url.Parse(indexURL) - if err != nil { - return "", err - } - subdir := base.ResolveReference(&url.URL{Path: "./"}).String() - resolve := func(ref string) (string, error) { - if ref == "" { - return subdir, nil - } - u, err := url.Parse(ref) - if err != nil { - return "", err - } - if u.Scheme != "" || u.Host != "" || strings.HasPrefix(u.Path, "/") { - return "", errCondaShardLayout - } - return base.ResolveReference(u).String(), nil - } - - baseURL, err := idx.infoString("base_url") - if err != nil { - return "", err - } - if resolved, err := resolve(baseURL); err != nil || resolved != subdir { - return "", fmt.Errorf("%w: base_url %q", errCondaShardLayout, baseURL) - } - - shardsBaseURL, err := idx.infoString("shards_base_url") - if err != nil { - return "", err - } - resolved, err := resolve(shardsBaseURL) - rel, ok := strings.CutPrefix(resolved, subdir) - if err != nil || !ok || (rel != "" && rel != condaShardsSubdir) { - return "", fmt.Errorf("%w: shards_base_url %q", errCondaShardLayout, shardsBaseURL) - } - return rel, nil + return conda.DecodeShardIndex(raw) } // rewriteCondaShardIndex masks every shard hash and points shards_base_url -// at the cooldown shard route for bucket. +// at the cooldown shard route for bucket (see conda.RewriteShardIndex). func rewriteCondaShardIndex(body []byte, indexURL string, mask [condaShardHashLen]byte, bucket string) ([]byte, error) { - idx, err := decodeCondaShardIndex(body) - if err != nil { - return nil, err - } - layout, err := idx.shardsLayout(indexURL) - if err != nil { - return nil, err - } - - shardsBase, err := msgpack.Marshal("./" + condaCooldownShardDir + "/" + bucket + "/" + layout) - if err != nil { - return nil, err - } - if i, ok := lookupMsgpackEntry(idx.info, "shards_base_url"); ok { - idx.info[i].value = shardsBase - } else { - idx.info = append(idx.info, msgpackEntry{key: "shards_base_url", value: shardsBase}) - } - info, err := encodeMsgpackMap(idx.info) - if err != nil { - return nil, err - } - i, _ := lookupMsgpackEntry(idx.top, "info") - idx.top[i].value = info - - i, ok := lookupMsgpackEntry(idx.top, "shards") - if !ok { - return nil, errors.New("sharded index has no shards") - } - shards, err := decodeMsgpackMap(idx.top[i].value) + raw, err := decompressCondaShard(body) if err != nil { return nil, err } - for j := range shards { - var hash []byte - if err := msgpack.Unmarshal(shards[j].value, &hash); err != nil || len(hash) != condaShardHashLen { - return nil, fmt.Errorf("shard hash for %q is not a sha256", shards[j].key) - } - for k := range hash { - hash[k] ^= mask[k] - } - if shards[j].value, err = msgpack.Marshal(hash); err != nil { - return nil, err - } - } - if idx.top[i].value, err = encodeMsgpackMap(shards); err != nil { - return nil, err - } - - raw, err := encodeMsgpackMap(idx.top) + rewritten, err := conda.RewriteShardIndex(raw, indexURL, mask, bucket) if err != nil { return nil, err } - return compressCondaShard(raw) -} - -// condaShardRecord holds the fields cooldown needs from a shard record. -// Timestamps are an integer or a float, in seconds or milliseconds as -// condaTime reads them. -type condaShardRecord struct { - Name string `msgpack:"name"` - Version string `msgpack:"version"` - Timestamp any `msgpack:"timestamp"` + return compressCondaShard(rewritten) } // filterCondaShard leaves out records in packages and packages.conda that -// are still inside their cooldown. Kept records keep their upstream bytes. +// are still inside their cooldown (see conda.FilterShard). Kept records +// keep their upstream bytes. func (h *CondaHandler) filterCondaShard(body []byte) ([]byte, error) { raw, err := decompressCondaShard(body) if err != nil { return nil, err } - top, err := decodeMsgpackMap(raw) + filtered, err := conda.FilterShard(raw, h.cooldownOptions(time.Now())) if err != nil { return nil, err } - for i := range top { - if top[i].key != "packages" && top[i].key != "packages.conda" { - continue - } - records, err := decodeMsgpackMap(top[i].value) - if err != nil { - return nil, err - } - kept := records[:0] - for _, rec := range records { - var fields condaShardRecord - if err := msgpack.Unmarshal(rec.value, &fields); err != nil { - return nil, fmt.Errorf("record %q: %w", rec.key, err) - } - if h.recordInCooldown(rec.key, fields.Name, fields.Version, msgpackNumber(fields.Timestamp)) { - continue - } - kept = append(kept, rec) - } - if top[i].value, err = encodeMsgpackMap(kept); err != nil { - return nil, err - } - } - out, err := encodeMsgpackMap(top) - if err != nil { - return nil, err - } - return compressCondaShard(out) -} - -// msgpackNumber returns a decoded msgpack integer or float as float64, and 0 -// for anything else. -func msgpackNumber(v any) float64 { - switch n := v.(type) { - case int8: - return float64(n) - case int16: - return float64(n) - case int32: - return float64(n) - case int64: - return float64(n) - case uint8: - return float64(n) - case uint16: - return float64(n) - case uint32: - return float64(n) - case uint64: - return float64(n) - case float32: - return float64(n) - case float64: - return n - default: - return 0 - } + return compressCondaShard(filtered) } diff --git a/internal/handler/cooldown_supported_test.go b/internal/handler/cooldown_supported_test.go index 7187edeb..372d78d3 100644 --- a/internal/handler/cooldown_supported_test.go +++ b/internal/handler/cooldown_supported_test.go @@ -10,10 +10,17 @@ import ( func TestCooldownSupportedCoversHandlers(t *testing.T) { calls := regexp.MustCompile(`(?:IsAllowed|Evaluate)\("([a-z]+)"|withheld\(h\.proxy, "([a-z]+)"|IsAllowed\((helmMetadataEcosystem)`) + // Metadata rewrites moved out of the handlers (#501) check cooldown in + // internal/metadata. files, err := filepath.Glob("*.go") if err != nil { t.Fatal(err) } + extracted, err := filepath.Glob("../metadata/*/*.go") + if err != nil { + t.Fatal(err) + } + files = append(files, extracted...) found := map[string]bool{} for _, f := range files { if strings.HasSuffix(f, "_test.go") { diff --git a/internal/metadata/conda/imports_test.go b/internal/metadata/conda/imports_test.go new file mode 100644 index 00000000..211bd15f --- /dev/null +++ b/internal/metadata/conda/imports_test.go @@ -0,0 +1,49 @@ +package conda + +import ( + "os/exec" + "slices" + "strings" + "testing" +) + +// TestPortableImports keeps the package free of the proxy's infrastructure: +// no handler, database, storage, metrics, HTTP or logging, so it builds for +// targets such as WASI where those are not available. +func TestPortableImports(t *testing.T) { + goTool, err := exec.LookPath("go") + if err != nil { + t.Skip("go tool not found") + } + out, err := exec.Command(goTool, "list", "-deps", "-f", "{{.Standard}} {{.ImportPath}}", ".").Output() + if err != nil { + t.Fatalf("go list: %v", err) + } + allowed := []string{ + "github.com/git-pkgs/cooldown", + "github.com/git-pkgs/proxy/internal/jsonstream", + "github.com/git-pkgs/proxy/internal/metadata/conda", + "github.com/git-pkgs/proxy/internal/packageurl", + "github.com/git-pkgs/purl", + "github.com/git-pkgs/vers", + "github.com/package-url/packageurl-go", + "github.com/vmihailenco/msgpack/v5", + "github.com/vmihailenco/msgpack/v5/msgpcode", + "github.com/vmihailenco/tagparser/v2", + "github.com/vmihailenco/tagparser/v2/internal", + "github.com/vmihailenco/tagparser/v2/internal/parser", + } + forbiddenStd := []string{"database/sql", "log/slog", "net", "net/http"} + for line := range strings.Lines(string(out)) { + standard, path, _ := strings.Cut(strings.TrimSpace(line), " ") + if standard == "true" { + if slices.Contains(forbiddenStd, path) { + t.Errorf("imports %s", path) + } + continue + } + if !slices.Contains(allowed, path) { + t.Errorf("imports %s, which is not on the portable list", path) + } + } +} diff --git a/internal/metadata/conda/metadata.go b/internal/metadata/conda/metadata.go new file mode 100644 index 00000000..76a58c64 --- /dev/null +++ b/internal/metadata/conda/metadata.go @@ -0,0 +1,69 @@ +// Package conda transforms conda channel metadata, repodata.json and +// sharded repodata (CEP 16), without storage or network access. +package conda + +import ( + "strings" + "time" + + "github.com/git-pkgs/cooldown" +) + +const ( + ecosystem = "conda" + // minFilenameParts: name-version-build needs at least three + // hyphen-separated parts. + minFilenameParts = 3 + // MaxSecondsTimestamp is the last second of year 9999. Like conda, a + // larger repodata timestamp is read as milliseconds and a smaller one + // as seconds, which some older entries use. + MaxSecondsTimestamp = 253402300799 +) + +// CooldownPolicy evaluates version age at the caller's supplied time. +type CooldownPolicy interface { + Enabled() bool + Evaluate(ecosystem, packagePURL string, publishedAt, evaluatedAt time.Time) cooldown.Decision +} + +// Options supplies the policy for a filter. EvaluatedAt is used as given; +// the transformations never read the clock. +type Options struct { + Cooldown CooldownPolicy + EvaluatedAt time.Time + // OnCooldownFilter is called synchronously for each package file + // cooldown leaves out. + OnCooldownFilter func(filename, name, version string) +} + +// Time returns the time a repodata timestamp names. +func Time(timestamp float64) time.Time { + if timestamp > MaxSecondsTimestamp { + return time.UnixMilli(int64(timestamp)).Truncate(time.Second) + } + return time.Unix(int64(timestamp), 0) +} + +// FilenameIdentity returns the name and version a download of filename is +// cached under, or empty strings when it is not a package file name. Conda +// filenames are {name}-{version}-{build}.{ext}, such as +// numpy-1.24.0-py311h64a7726_0.conda; the name can contain hyphens. +func FilenameIdentity(filename string) (name, version string) { + base := filename + for _, ext := range []string{".conda", ".tar.bz2"} { + if strings.HasSuffix(base, ext) { + base = strings.TrimSuffix(base, ext) + break + } + } + parts := strings.Split(base, "-") + if len(parts) < minFilenameParts { + return "", "" + } + version = parts[len(parts)-2] + name = strings.Join(parts[:len(parts)-2], "-") + if len(version) == 0 || version[0] < '0' || version[0] > '9' { + return "", "" + } + return name, version +} diff --git a/internal/metadata/conda/metadata_test.go b/internal/metadata/conda/metadata_test.go new file mode 100644 index 00000000..51529a3e --- /dev/null +++ b/internal/metadata/conda/metadata_test.go @@ -0,0 +1,489 @@ +package conda + +import ( + "bytes" + "encoding/json" + "errors" + "strings" + "testing" + "time" + + "github.com/git-pkgs/cooldown" + "github.com/vmihailenco/msgpack/v5" +) + +var evaluatedAt = time.Date(2026, 11, 20, 12, 0, 0, 0, time.UTC) + +// policy holds back what was published within age of the evaluation time. +type policy struct { + disabled bool + age time.Duration + // noAvailableAt leaves Decision.AvailableAt zero. + noAvailableAt bool + purls []string + at []time.Time +} + +func (p *policy) Enabled() bool { return !p.disabled } + +func (p *policy) Evaluate(eco, packagePURL string, publishedAt, at time.Time) cooldown.Decision { + if eco != "conda" { + panic("ecosystem " + eco) + } + p.purls = append(p.purls, packagePURL) + p.at = append(p.at, at) + available := publishedAt.Add(p.age) + d := cooldown.Decision{Allowed: !at.Before(available)} + if !p.noAvailableAt { + d.AvailableAt = available + } + return d +} + +func TestTime(t *testing.T) { + cases := []struct { + in float64 + want time.Time + }{ + {1_700_000_000, time.Unix(1_700_000_000, 0)}, + {1_700_000_000_123, time.Unix(1_700_000_000, 0)}, + {MaxSecondsTimestamp, time.Unix(MaxSecondsTimestamp, 0)}, + {MaxSecondsTimestamp + 1, time.UnixMilli(MaxSecondsTimestamp + 1).Truncate(time.Second)}, + } + for _, c := range cases { + if got := Time(c.in); !got.Equal(c.want) { + t.Errorf("Time(%v) = %v, want %v", c.in, got, c.want) + } + } +} + +func TestFilenameIdentity(t *testing.T) { + cases := []struct{ in, name, version string }{ + {"numpy-1.24.0-py311h64a7726_0.conda", "numpy", "1.24.0"}, + {"python-dateutil-2.8.2-pyhd8ed1ab_0.tar.bz2", "python-dateutil", "2.8.2"}, + {"ca-certificates-2024.2.2-hbcca054_0.conda", "ca-certificates", "2024.2.2"}, + {"numpy-1.24.0.conda", "", ""}, + {"numpy-v1-0.conda", "", ""}, + {"numpy--0.conda", "", ""}, + {"numpy-1.0-0.conda.tar.bz2", "numpy", "1.0"}, + {"1.0-0.conda", "", ""}, + } + for _, c := range cases { + name, version := FilenameIdentity(c.in) + if name != c.name || version != c.version { + t.Errorf("FilenameIdentity(%q) = %q, %q, want %q, %q", c.in, name, version, c.name, c.version) + } + } +} + +func repodata(t *testing.T) string { + t.Helper() + old := evaluatedAt.Add(-30 * 24 * time.Hour) + recent := evaluatedAt.Add(-time.Hour) + doc := `{"info":{"subdir":"noarch"},"packages":{` + + `"old-1.0-0.tar.bz2":{"name":"old","version":"1.0","timestamp":` + ms(old) + `},` + + `"new-2.0-0.tar.bz2":{"name":"new","version":"2.0","timestamp":` + ms(recent) + `},` + + `"untimed-1.0-0.tar.bz2":{"name":"untimed","version":"1.0"},` + + `"nameless-1.0-0.tar.bz2":{"version":"1.0","timestamp":` + ms(recent) + `}` + + `},"packages.conda":{` + + `"newer-3.0-0.conda":{"name":"newer","version":"3.0","timestamp":` + secs(evaluatedAt.Add(-2*time.Hour)) + `}` + + `},"removed":["x-1-0.tar.bz2"]}` + return doc +} + +func ms(t time.Time) string { b, _ := json.Marshal(t.UnixMilli()); return string(b) } +func secs(t time.Time) string { b, _ := json.Marshal(t.Unix()); return string(b) } + +func TestFilterLeavesOutEntriesInCooldown(t *testing.T) { + p := &policy{age: 24 * time.Hour} + var filtered []string + f := NewFilter(Options{Cooldown: p, EvaluatedAt: evaluatedAt, OnCooldownFilter: func(filename, name, version string) { + filtered = append(filtered, filename+" "+name+" "+version) + }}) + var out bytes.Buffer + if err := f.Copy(strings.NewReader(repodata(t)), &out); err != nil { + t.Fatal(err) + } + var doc struct { + Info json.RawMessage `json:"info"` + Packages map[string]json.RawMessage `json:"packages"` + PackagesConda map[string]json.RawMessage `json:"packages.conda"` + Removed []string `json:"removed"` + } + if err := json.Unmarshal(out.Bytes(), &doc); err != nil { + t.Fatalf("output is not JSON: %v\n%s", err, out.String()) + } + for _, kept := range []string{"old-1.0-0.tar.bz2", "untimed-1.0-0.tar.bz2", "nameless-1.0-0.tar.bz2"} { + if _, ok := doc.Packages[kept]; !ok { + t.Errorf("%s left out", kept) + } + } + if _, ok := doc.Packages["new-2.0-0.tar.bz2"]; ok { + t.Error("new-2.0-0.tar.bz2 kept") + } + if len(doc.PackagesConda) != 0 { + t.Errorf("packages.conda = %v, want empty", doc.PackagesConda) + } + if string(doc.Info) != `{"subdir":"noarch"}` || len(doc.Removed) != 1 { + t.Errorf("other members changed: info %s removed %v", doc.Info, doc.Removed) + } + want := []string{"new-2.0-0.tar.bz2 new 2.0", "newer-3.0-0.conda newer 3.0"} + if strings.Join(filtered, "|") != strings.Join(want, "|") { + t.Errorf("filtered %v, want %v", filtered, want) + } + for _, at := range p.at { + if !at.Equal(evaluatedAt) { + t.Errorf("evaluated at %v, want %v", at, evaluatedAt) + } + } + if p.purls[0] != "pkg:conda/old" { + t.Errorf("purl %q", p.purls[0]) + } + until, known := f.Until() + if !known || !until.Equal(evaluatedAt.Add(-2*time.Hour).Add(24*time.Hour)) { + t.Errorf("Until = %v, %v, want the earliest entry's", until, known) + } +} + +func TestFilterKeepsUpstreamBytes(t *testing.T) { + in := `{"packages":{"a-1-0.tar.bz2":{"name":"a", "timestamp":1, "depends":["b >=1"]}},"x": [1, 2]}` + var out bytes.Buffer + if err := NewFilter(Options{Cooldown: &policy{}, EvaluatedAt: evaluatedAt}).Copy(strings.NewReader(in), &out); err != nil { + t.Fatal(err) + } + if !strings.Contains(out.String(), `{"name":"a", "timestamp":1, "depends":["b >=1"]}`) || !strings.Contains(out.String(), `[1, 2]`) { + t.Errorf("bytes changed: %s", out.String()) + } +} + +func TestFilterWithheldDigest(t *testing.T) { + run := func(age time.Duration) *Filter { + f := NewFilter(Options{Cooldown: &policy{age: age}, EvaluatedAt: evaluatedAt}) + if err := f.Copy(strings.NewReader(repodata(t)), &bytes.Buffer{}); err != nil { + t.Fatal(err) + } + return f + } + if !bytes.Equal(run(24*time.Hour).Withheld(), run(24*time.Hour).Withheld()) { + t.Error("same entries left out give different digests") + } + if bytes.Equal(run(24*time.Hour).Withheld(), run(90*time.Minute).Withheld()) { + t.Error("different entries left out give the same digest") + } + none := run(0) + if until, known := none.Until(); !until.IsZero() || !known { + t.Errorf("nothing left out: Until = %v, %v", until, known) + } +} + +func TestFilterKeepsEntriesWithoutTimestamp(t *testing.T) { + // Everything published so far is held back, but entries without a + // timestamp or a name have nothing to decide by. + f := NewFilter(Options{Cooldown: &policy{age: 100 * 365 * 24 * time.Hour}, EvaluatedAt: evaluatedAt}) + var out bytes.Buffer + if err := f.Copy(strings.NewReader(repodata(t)), &out); err != nil { + t.Fatal(err) + } + for _, kept := range []string{"untimed-1.0-0.tar.bz2", "nameless-1.0-0.tar.bz2"} { + if !strings.Contains(out.String(), kept) { + t.Errorf("%s left out", kept) + } + } + if strings.Contains(out.String(), "old-1.0-0.tar.bz2") { + t.Error("old-1.0-0.tar.bz2 kept") + } +} + +func TestFilterUntilUnknown(t *testing.T) { + f := NewFilter(Options{Cooldown: &policy{age: 24 * time.Hour, noAvailableAt: true}, EvaluatedAt: evaluatedAt}) + if err := f.Copy(strings.NewReader(repodata(t)), &bytes.Buffer{}); err != nil { + t.Fatal(err) + } + if _, known := f.Until(); known { + t.Error("Until known without an AvailableAt") + } +} + +func TestFilterWithoutPolicy(t *testing.T) { + for name, p := range map[string]CooldownPolicy{"nil": nil, "disabled": &policy{disabled: true, age: 24 * time.Hour}} { + var out bytes.Buffer + if err := NewFilter(Options{Cooldown: p, EvaluatedAt: evaluatedAt}).Copy(strings.NewReader(repodata(t)), &out); err != nil { + t.Fatal(err) + } + if !strings.Contains(out.String(), "new-2.0-0.tar.bz2") { + t.Errorf("%s policy left entries out", name) + } + } +} + +func TestFilterRefusesInvalidDocument(t *testing.T) { + if err := NewFilter(Options{}).Copy(strings.NewReader(`{"packages":`), &bytes.Buffer{}); err == nil { + t.Error("truncated document copied") + } +} + +func TestReadIndex(t *testing.T) { + index, err := ReadIndex(strings.NewReader(repodata(t) + ``)) + if err != nil { + t.Fatal(err) + } + if got := index["old-1.0-0.tar.bz2"]; !got.Equal(evaluatedAt.Add(-30 * 24 * time.Hour).Truncate(time.Second)) { + t.Errorf("old = %v", got) + } + if got := index["newer-3.0-0.conda"]; !got.Equal(evaluatedAt.Add(-2 * time.Hour)) { + t.Errorf("newer = %v", got) + } + if got, ok := index["untimed-1.0-0.tar.bz2"]; !ok || !got.IsZero() { + t.Errorf("untimed = %v, %v", got, ok) + } + if len(index) != 5 { + t.Errorf("index has %d files, want 5", len(index)) + } + index, err = ReadIndex(strings.NewReader(`{"packages":{"bad":[1],"good-1-0.conda":{"timestamp":1}}}`)) + if err != nil { + t.Fatal(err) + } + if _, ok := index["bad"]; ok || len(index) != 1 { + t.Errorf("index = %v, want only the object entry", index) + } + if _, err := ReadIndex(strings.NewReader(`[`)); err == nil { + t.Error("invalid document read") + } +} + +func TestIsShardFile(t *testing.T) { + hash := strings.Repeat("ab", ShardHashLen) + cases := map[string]bool{ + hash + ShardSuffix: true, + strings.ToUpper(hash) + ShardSuffix: false, + hash[2:] + ShardSuffix: false, + hash + ".msgpack": false, + strings.Repeat("zz", 32) + ShardSuffix: false, + } + for name, want := range cases { + if got := IsShardFile(name); got != want { + t.Errorf("IsShardFile(%q) = %v, want %v", name, got, want) + } + } +} + +func TestShardMask(t *testing.T) { + a := ShardMask("conda-forge", "noarch", "1") + if a != ShardMask("conda-forge", "noarch", "1") { + t.Error("mask not stable") + } + for _, other := range [][ShardHashLen]byte{ShardMask("conda-forge", "noarch", "2"), ShardMask("conda-forge", "linux-64", "1"), ShardMask("bioconda", "noarch", "1")} { + if a == other { + t.Error("masks collide") + } + } +} + +func mustMsgpack(t *testing.T, v any) []byte { + t.Helper() + b, err := msgpack.Marshal(v) + if err != nil { + t.Fatal(err) + } + return b +} + +func shardIndex(t *testing.T, info map[string]any, shards map[string]any) []byte { + t.Helper() + top := map[string]any{"version": 1, "info": info} + if shards != nil { + top["shards"] = shards + } + return mustMsgpack(t, top) +} + +const indexURL = "https://proxy.example/conda/conda-forge/noarch/repodata_shards.msgpack.zst" + +func TestDecodeShardIndexRefusesOtherDocuments(t *testing.T) { + cases := map[string][]byte{ + "no version": mustMsgpack(t, map[string]any{"info": map[string]any{}}), + "version 2": mustMsgpack(t, map[string]any{"version": 2, "info": map[string]any{}}), + "no info": mustMsgpack(t, map[string]any{"version": 1}), + "info not map": mustMsgpack(t, map[string]any{"version": 1, "info": "x"}), + "not a map": mustMsgpack(t, []int{1}), + "non-string key": mustMsgpack(t, map[int]int{1: 1}), + } + for name, raw := range cases { + if _, err := DecodeShardIndex(raw); err == nil { + t.Errorf("%s: decoded", name) + } + } +} + +func TestShardsLayout(t *testing.T) { + cases := []struct { + info map[string]any + want string + ok bool + }{ + {map[string]any{}, "", true}, + {map[string]any{"base_url": "./", "shards_base_url": "./shards/"}, ShardsSubdir, true}, + {map[string]any{"shards_base_url": "shards/"}, ShardsSubdir, true}, + {map[string]any{"base_url": "https://conda.anaconda.org/conda-forge/noarch/"}, "", false}, + {map[string]any{"base_url": "/conda-forge/noarch/"}, "", false}, + {map[string]any{"base_url": "/conda/conda-forge/noarch/"}, "", false}, + {map[string]any{"base_url": "../"}, "", false}, + {map[string]any{"shards_base_url": "other/"}, "", false}, + {map[string]any{"shards_base_url": "//cdn.example/x/"}, "", false}, + {map[string]any{"shards_base_url": "../"}, "", false}, + {map[string]any{"base_url": 1}, "", false}, + {map[string]any{"shards_base_url": 1}, "", false}, + } + for _, c := range cases { + idx, err := DecodeShardIndex(shardIndex(t, c.info, nil)) + if err != nil { + t.Fatal(err) + } + got, err := idx.ShardsLayout(indexURL) + if (err == nil) != c.ok || got != c.want { + t.Errorf("info %v: layout %q, %v; want %q, ok %v", c.info, got, err, c.want, c.ok) + } + if err != nil && c.info["base_url"] != 1 && c.info["shards_base_url"] != 1 && !errors.Is(err, ErrShardLayout) { + t.Errorf("info %v: error %v is not ErrShardLayout", c.info, err) + } + } + idx, _ := DecodeShardIndex(shardIndex(t, map[string]any{}, nil)) + if _, err := idx.ShardsLayout("://bad"); err == nil { + t.Error("bad index URL accepted") + } +} + +func TestRewriteShardIndex(t *testing.T) { + hash := bytes.Repeat([]byte{0x11}, ShardHashLen) + mask := ShardMask("conda-forge", "noarch", "7") + for _, c := range []struct { + info map[string]any + base string + }{ + {map[string]any{"base_url": "./", "subdir": "noarch"}, "./cooldown-shards/7/"}, + {map[string]any{"shards_base_url": "./shards/"}, "./cooldown-shards/7/shards/"}, + } { + raw := shardIndex(t, c.info, map[string]any{"numpy": hash}) + out, err := RewriteShardIndex(raw, indexURL, mask, "7") + if err != nil { + t.Fatal(err) + } + var doc struct { + Version int `msgpack:"version"` + Info map[string]any `msgpack:"info"` + Shards map[string][]byte `msgpack:"shards"` + } + if err := msgpack.Unmarshal(out, &doc); err != nil { + t.Fatal(err) + } + if doc.Version != 1 || doc.Info["shards_base_url"] != c.base { + t.Errorf("info %v: version %d, shards_base_url %v, want %q", c.info, doc.Version, doc.Info["shards_base_url"], c.base) + } + for k, v := range c.info { + if k != "shards_base_url" && doc.Info[k] != v { + t.Errorf("info %s = %v, want %v", k, doc.Info[k], v) + } + } + want := make([]byte, ShardHashLen) + for i := range want { + want[i] = hash[i] ^ mask[i] + } + if !bytes.Equal(doc.Shards["numpy"], want) { + t.Errorf("shard hash %x, want %x", doc.Shards["numpy"], want) + } + } +} + +func TestRewriteShardIndexRefuses(t *testing.T) { + mask := ShardMask("c", "a", "1") + cases := map[string][]byte{ + "no shards": shardIndex(t, map[string]any{}, nil), + "short hash": shardIndex(t, map[string]any{}, map[string]any{"x": []byte{1}}), + "string hash": shardIndex(t, map[string]any{}, map[string]any{"x": "abc"}), + "bad layout": shardIndex(t, map[string]any{"base_url": "/x/"}, map[string]any{}), + "not index": mustMsgpack(t, []int{1}), + } + for name, raw := range cases { + if _, err := RewriteShardIndex(raw, indexURL, mask, "1"); err == nil { + t.Errorf("%s: rewritten", name) + } + } +} + +func TestFilterShard(t *testing.T) { + old := evaluatedAt.Add(-30 * 24 * time.Hour) + recent := evaluatedAt.Add(-time.Hour) + raw := mustMsgpack(t, map[string]any{ + "info": map[string]any{"subdir": "noarch"}, + "packages": map[string]any{ + "a-1.0-0.tar.bz2": map[string]any{"name": "a", "version": "1.0", "timestamp": old.UnixMilli()}, + "a-2.0-0.tar.bz2": map[string]any{"name": "a", "version": "2.0", "timestamp": recent.UnixMilli()}, + "a-3.0-0.tar.bz2": map[string]any{"name": "a", "version": "3.0", "timestamp": float64(recent.Unix())}, + "a-4.0-0.tar.bz2": map[string]any{"name": "a", "version": "4.0"}, + }, + "packages.conda": map[string]any{ + "a-5.0-0.conda": map[string]any{"name": "a", "version": "5.0", "timestamp": uint32(recent.Unix())}, + }, + }) + p := &policy{age: 24 * time.Hour} + var filtered []string + out, err := FilterShard(raw, Options{Cooldown: p, EvaluatedAt: evaluatedAt, OnCooldownFilter: func(filename, name, version string) { + filtered = append(filtered, filename) + }}) + if err != nil { + t.Fatal(err) + } + var doc struct { + Info map[string]any `msgpack:"info"` + Packages map[string]map[string]any `msgpack:"packages"` + PackagesConda map[string]map[string]any `msgpack:"packages.conda"` + } + if err := msgpack.Unmarshal(out, &doc); err != nil { + t.Fatal(err) + } + if len(doc.Packages) != 2 || doc.Packages["a-1.0-0.tar.bz2"] == nil || doc.Packages["a-4.0-0.tar.bz2"] == nil { + t.Errorf("packages = %v", doc.Packages) + } + if len(doc.PackagesConda) != 0 || doc.Info["subdir"] != "noarch" { + t.Errorf("packages.conda = %v, info = %v", doc.PackagesConda, doc.Info) + } + if len(filtered) != 3 { + t.Errorf("filtered %v, want 3 files", filtered) + } + for _, at := range p.at { + if !at.Equal(evaluatedAt) { + t.Errorf("evaluated at %v", at) + } + } + same, err := FilterShard(raw, Options{}) + if err != nil { + t.Fatal(err) + } + if err := msgpack.Unmarshal(same, &doc); err != nil || len(doc.Packages) != 4 { + t.Errorf("without a policy: %v, %v", doc.Packages, err) + } +} + +func TestFilterShardRefuses(t *testing.T) { + cases := map[string][]byte{ + "not a map": mustMsgpack(t, []int{1}), + "packages not map": mustMsgpack(t, map[string]any{"packages": 1}), + "record not map": mustMsgpack(t, map[string]any{"packages": map[string]any{"a": 1}}), + } + for name, raw := range cases { + if _, err := FilterShard(raw, Options{}); err == nil { + t.Errorf("%s: filtered", name) + } + } +} + +func TestMsgpackNumber(t *testing.T) { + for _, v := range []any{int8(5), int16(5), int32(5), int64(5), uint8(5), uint16(5), uint32(5), uint64(5), float32(5), float64(5)} { + if got := msgpackNumber(v); got != 5 { + t.Errorf("msgpackNumber(%T) = %v", v, got) + } + } + if got := msgpackNumber("5"); got != 0 { + t.Errorf("msgpackNumber(string) = %v", got) + } +} diff --git a/internal/metadata/conda/repodata.go b/internal/metadata/conda/repodata.go new file mode 100644 index 00000000..de5741e8 --- /dev/null +++ b/internal/metadata/conda/repodata.go @@ -0,0 +1,150 @@ +package conda + +import ( + "crypto/sha256" + "encoding/json" + "fmt" + "hash" + "io" + "time" + + "github.com/git-pkgs/cooldown" + "github.com/git-pkgs/proxy/internal/jsonstream" + "github.com/git-pkgs/proxy/internal/packageurl" +) + +// repodataEntry holds the fields cooldown needs from a repodata.json entry. +type repodataEntry struct { + Name string `json:"name"` + Version string `json:"version"` + Timestamp float64 `json:"timestamp"` +} + +// Filter decides which repodata entries cooldown leaves out, all as of +// Options.EvaluatedAt, and records what it left out, which with the +// document fixes the filtered copy. +type Filter struct { + o Options + // withheld hashes the filenames left out. + withheld hash.Hash + // until is when the first entry left out leaves cooldown. + until time.Time + // unknownUntil is set when an entry was left out without a time it + // leaves cooldown, so until can't be relied on. + unknownUntil bool +} + +// NewFilter returns a filter deciding by o. +func NewFilter(o Options) *Filter { + return &Filter{o: o, withheld: sha256.New()} +} + +// Copy copies repodata.json from r to w as it streams, leaving out entries +// in packages and packages.conda that are still inside their cooldown. +// Kept entries and every other member are written with their upstream +// bytes. The caller bounds r. +func (f *Filter) Copy(r io.Reader, w io.Writer) error { + return jsonstream.CopyObject(r, w, func(m *jsonstream.Member) error { + if !packagesMember(m.Key) { + return m.Copy() + } + return m.Object(func(entry *jsonstream.Member) error { + raw, err := entry.Raw() + if err != nil { + return err + } + if f.inCooldown(entry.Key, raw) { + return nil + } + return entry.Write(raw) + }) + }) +} + +// Withheld is a digest of the filenames the filter left out so far. +func (f *Filter) Withheld() []byte { + return f.withheld.Sum(nil) +} + +// Until is when the first entry left out leaves cooldown, zero when none +// was left out. known is false when an entry was left out without such a +// time, so the filtered copy can't be reused until a given time. +func (f *Filter) Until() (until time.Time, known bool) { + return f.until, !f.unknownUntil +} + +// inCooldown reports whether a repodata entry was published too recently. +// Entries without a name or timestamp are kept. +func (f *Filter) inCooldown(filename string, raw []byte) bool { + var entry repodataEntry + if err := json.Unmarshal(raw, &entry); err != nil { + return false + } + decision, withheld := f.o.decide(entry.Name, entry.Timestamp) + if !withheld { + return false + } + f.o.filtered(filename, entry.Name, entry.Version) + _, _ = fmt.Fprintf(f.withheld, "%d:%s", len(filename), filename) + switch { + case decision.AvailableAt.IsZero(): + f.unknownUntil = true + case f.until.IsZero() || decision.AvailableAt.Before(f.until): + f.until = decision.AvailableAt + } + return true +} + +// decide evaluates a package record's timestamp, reporting whether cooldown +// holds it back. Records without a name or timestamp, and any record +// without an enabled policy, are kept. +func (o Options) decide(name string, timestamp float64) (cooldown.Decision, bool) { + if name == "" || timestamp == 0 || o.Cooldown == nil || !o.Cooldown.Enabled() { + return cooldown.Decision{}, false + } + decision := o.Cooldown.Evaluate("conda", packageurl.MakeString(ecosystem, name, ""), Time(timestamp), o.EvaluatedAt) + return decision, !decision.Allowed +} + +func (o Options) filtered(filename, name, version string) { + if o.OnCooldownFilter != nil { + o.OnCooldownFilter(filename, name, version) + } +} + +// ReadIndex maps each package file in a repodata.json to its timestamp, or +// the zero time for a file without one, reading the document as it +// streams. Entries that aren't objects are left out. The caller bounds r. +func ReadIndex(r io.Reader) (map[string]time.Time, error) { + index := make(map[string]time.Time) + err := jsonstream.CopyObject(r, io.Discard, func(m *jsonstream.Member) error { + if !packagesMember(m.Key) { + return m.Copy() + } + return m.Object(func(entry *jsonstream.Member) error { + raw, err := entry.Raw() + if err != nil { + return err + } + var e repodataEntry + if json.Unmarshal(raw, &e) != nil { + return nil + } + index[entry.Key] = time.Time{} + if e.Timestamp != 0 { + index[entry.Key] = Time(e.Timestamp) + } + return nil + }) + }) + if err != nil { + return nil, err + } + return index, nil +} + +// packagesMember reports whether a top-level repodata member lists package +// files. +func packagesMember(key string) bool { + return key == "packages" || key == "packages.conda" +} diff --git a/internal/metadata/conda/shards.go b/internal/metadata/conda/shards.go new file mode 100644 index 00000000..14b58d20 --- /dev/null +++ b/internal/metadata/conda/shards.go @@ -0,0 +1,335 @@ +package conda + +import ( + "bytes" + "crypto/sha256" + "encoding/hex" + "errors" + "fmt" + "net/url" + "strings" + + "github.com/vmihailenco/msgpack/v5" +) + +// Sharded repodata (CEP 16) maps each package name to the sha256 of its +// shard. With cooldown the proxy filters shards, which changes their bytes, +// but clients cache shards by hash and never fetch the same hash again. So +// the rewritten index XORs every hash with a mask that changes with each +// bucket: filtered shards get hashes of their own, and clients fetch them +// again once versions have left cooldown. +// +// The functions here take and return the decompressed msgpack documents; +// the zstd framing is the caller's. +const ( + // ShardSuffix ends a shard's file name, after its hex hash. + ShardSuffix = ".msgpack.zst" + // CooldownShardDir is the directory, below a subdir, that a rewritten + // index points shards_base_url at. + CooldownShardDir = "cooldown-shards" + // ShardsSubdir is the one shards directory below a subdir the proxy + // routes besides the subdir itself. + ShardsSubdir = "shards/" + // ShardHashLen is the length of a shard hash, a sha256. + ShardHashLen = sha256.Size + shardIndexFormat = 1 + shardMaskDomain = "git-pkgs proxy conda cooldown shard\x00" + shardsBaseURLKey = "shards_base_url" + shardIndexInfoKey = "info" +) + +// ErrShardLayout is returned for a sharded index whose base_url or +// shards_base_url leads outside the proxy's routes. +var ErrShardLayout = errors.New("unsupported sharded repodata layout") + +// IsShardFile reports whether name is a shard file name: a lowercase hex +// sha256 followed by ShardSuffix. +func IsShardFile(name string) bool { + hash, ok := strings.CutSuffix(name, ShardSuffix) + if !ok || len(hash) != 2*ShardHashLen { + return false + } + _, err := hex.DecodeString(hash) + return err == nil && strings.ToLower(hash) == hash +} + +// ShardMask is XORed with shard hashes in a rewritten index. It keeps +// filtered shards apart from upstream ones in client caches, which are +// keyed by hash alone. +func ShardMask(channel, arch, bucket string) [ShardHashLen]byte { + return sha256.Sum256([]byte(shardMaskDomain + channel + "\x00" + arch + "\x00" + bucket)) +} + +// msgpackEntry is one member of a msgpack map, kept in its upstream order +// with its value undecoded. +type msgpackEntry struct { + key string + value msgpack.RawMessage +} + +func decodeMsgpackMap(b []byte) ([]msgpackEntry, error) { + dec := msgpack.NewDecoder(bytes.NewReader(b)) + n, err := dec.DecodeMapLen() + if err != nil { + return nil, err + } + if n < 0 { + return nil, errors.New("expected a msgpack map") + } + entries := make([]msgpackEntry, 0, n) + for range n { + key, err := dec.DecodeString() + if err != nil { + return nil, err + } + value, err := dec.DecodeRaw() + if err != nil { + return nil, err + } + entries = append(entries, msgpackEntry{key: key, value: value}) + } + return entries, nil +} + +func encodeMsgpackMap(entries []msgpackEntry) ([]byte, error) { + var buf bytes.Buffer + enc := msgpack.NewEncoder(&buf) + if err := enc.EncodeMapLen(len(entries)); err != nil { + return nil, err + } + for _, e := range entries { + if err := enc.EncodeString(e.key); err != nil { + return nil, err + } + if err := enc.Encode(e.value); err != nil { + return nil, err + } + } + return buf.Bytes(), nil +} + +func lookupMsgpackEntry(entries []msgpackEntry, key string) (int, bool) { + for i, e := range entries { + if e.key == key { + return i, true + } + } + return -1, false +} + +// ShardIndex is a decoded repodata_shards.msgpack document. +type ShardIndex struct { + top []msgpackEntry + info []msgpackEntry +} + +// DecodeShardIndex decodes a decompressed repodata_shards.msgpack. Only +// format version 1 is read. +func DecodeShardIndex(raw []byte) (*ShardIndex, error) { + top, err := decodeMsgpackMap(raw) + if err != nil { + return nil, err + } + i, ok := lookupMsgpackEntry(top, "version") + if !ok { + return nil, errors.New("sharded index has no version") + } + var version int + if err := msgpack.Unmarshal(top[i].value, &version); err != nil || version != shardIndexFormat { + return nil, fmt.Errorf("unsupported sharded index version %v", top[i].value) + } + i, ok = lookupMsgpackEntry(top, shardIndexInfoKey) + if !ok { + return nil, errors.New("sharded index has no info") + } + info, err := decodeMsgpackMap(top[i].value) + if err != nil { + return nil, err + } + return &ShardIndex{top: top, info: info}, nil +} + +func (idx *ShardIndex) infoString(key string) (string, error) { + i, ok := lookupMsgpackEntry(idx.info, key) + if !ok { + return "", nil + } + var s string + err := msgpack.Unmarshal(idx.info[i].value, &s) + return s, err +} + +// ShardsLayout checks that packages and shards sit where the proxy routes +// them, below the subdir of indexURL, and returns the shards directory +// relative to the subdir: "" or ShardsSubdir. Clients resolve base_url and +// shards_base_url against the proxy's URL, so only relative paths stay on +// the proxy: a scheme or host leads clients around it, a leading / outside +// its mount. +func (idx *ShardIndex) ShardsLayout(indexURL string) (string, error) { + base, err := url.Parse(indexURL) + if err != nil { + return "", err + } + subdir := base.ResolveReference(&url.URL{Path: "./"}).String() + resolve := func(ref string) (string, error) { + if ref == "" { + return subdir, nil + } + u, err := url.Parse(ref) + if err != nil { + return "", err + } + if u.Scheme != "" || u.Host != "" || strings.HasPrefix(u.Path, "/") { + return "", ErrShardLayout + } + return base.ResolveReference(u).String(), nil + } + + baseURL, err := idx.infoString("base_url") + if err != nil { + return "", err + } + if resolved, err := resolve(baseURL); err != nil || resolved != subdir { + return "", fmt.Errorf("%w: base_url %q", ErrShardLayout, baseURL) + } + + shardsBaseURL, err := idx.infoString(shardsBaseURLKey) + if err != nil { + return "", err + } + resolved, err := resolve(shardsBaseURL) + rel, ok := strings.CutPrefix(resolved, subdir) + if err != nil || !ok || (rel != "" && rel != ShardsSubdir) { + return "", fmt.Errorf("%w: shards_base_url %q", ErrShardLayout, shardsBaseURL) + } + return rel, nil +} + +// RewriteShardIndex masks every shard hash in a decompressed sharded index +// and points shards_base_url at the cooldown shard route for bucket. It +// returns the decompressed rewritten index. +func RewriteShardIndex(raw []byte, indexURL string, mask [ShardHashLen]byte, bucket string) ([]byte, error) { + idx, err := DecodeShardIndex(raw) + if err != nil { + return nil, err + } + layout, err := idx.ShardsLayout(indexURL) + if err != nil { + return nil, err + } + + shardsBase, err := msgpack.Marshal("./" + CooldownShardDir + "/" + bucket + "/" + layout) + if err != nil { + return nil, err + } + if i, ok := lookupMsgpackEntry(idx.info, shardsBaseURLKey); ok { + idx.info[i].value = shardsBase + } else { + idx.info = append(idx.info, msgpackEntry{key: shardsBaseURLKey, value: shardsBase}) + } + info, err := encodeMsgpackMap(idx.info) + if err != nil { + return nil, err + } + i, _ := lookupMsgpackEntry(idx.top, shardIndexInfoKey) + idx.top[i].value = info + + i, ok := lookupMsgpackEntry(idx.top, "shards") + if !ok { + return nil, errors.New("sharded index has no shards") + } + shards, err := decodeMsgpackMap(idx.top[i].value) + if err != nil { + return nil, err + } + for j := range shards { + var hash []byte + if err := msgpack.Unmarshal(shards[j].value, &hash); err != nil || len(hash) != ShardHashLen { + return nil, fmt.Errorf("shard hash for %q is not a sha256", shards[j].key) + } + for k := range hash { + hash[k] ^= mask[k] + } + if shards[j].value, err = msgpack.Marshal(hash); err != nil { + return nil, err + } + } + if idx.top[i].value, err = encodeMsgpackMap(shards); err != nil { + return nil, err + } + return encodeMsgpackMap(idx.top) +} + +// shardRecord holds the fields cooldown needs from a shard record. +// Timestamps are an integer or a float, in seconds or milliseconds as Time +// reads them. +type shardRecord struct { + Name string `msgpack:"name"` + Version string `msgpack:"version"` + Timestamp any `msgpack:"timestamp"` +} + +// FilterShard leaves out records in packages and packages.conda of a +// decompressed shard that are still inside their cooldown, as of +// o.EvaluatedAt. Kept records keep their upstream bytes. It returns the +// decompressed filtered shard. +func FilterShard(raw []byte, o Options) ([]byte, error) { + top, err := decodeMsgpackMap(raw) + if err != nil { + return nil, err + } + for i := range top { + if !packagesMember(top[i].key) { + continue + } + records, err := decodeMsgpackMap(top[i].value) + if err != nil { + return nil, err + } + kept := records[:0] + for _, rec := range records { + var fields shardRecord + if err := msgpack.Unmarshal(rec.value, &fields); err != nil { + return nil, fmt.Errorf("record %q: %w", rec.key, err) + } + if _, withheld := o.decide(fields.Name, msgpackNumber(fields.Timestamp)); withheld { + o.filtered(rec.key, fields.Name, fields.Version) + continue + } + kept = append(kept, rec) + } + if top[i].value, err = encodeMsgpackMap(kept); err != nil { + return nil, err + } + } + return encodeMsgpackMap(top) +} + +// msgpackNumber returns a decoded msgpack integer or float as float64, and +// 0 for anything else. +func msgpackNumber(v any) float64 { + switch n := v.(type) { + case int8: + return float64(n) + case int16: + return float64(n) + case int32: + return float64(n) + case int64: + return float64(n) + case uint8: + return float64(n) + case uint16: + return float64(n) + case uint32: + return float64(n) + case uint64: + return float64(n) + case float32: + return float64(n) + case float64: + return n + default: + return 0 + } +}