From 42dc1c90c5ab63f14899d8241fdf7efaa04a518a Mon Sep 17 00:00:00 2001 From: Simon Chrzanowski Date: Mon, 23 Nov 2026 17:07:48 +0100 Subject: [PATCH] Extract portable Swift registry metadata transformations The Swift registry rewrites, the source archive lookup in release metadata, the checksum helpers and the package identifier checks move from internal/handler into internal/metadata/swift, which takes the proxy and upstream URLs explicitly and builds for wasip1. The handler keeps fetching, caching, routes and downloads, with its functions as thin wrappers. --- internal/handler/swift.go | 181 +++------------- internal/metadata/swift/imports_test.go | 38 ++++ internal/metadata/swift/metadata.go | 249 +++++++++++++++++++++++ internal/metadata/swift/metadata_test.go | 203 ++++++++++++++++++ 4 files changed, 513 insertions(+), 158 deletions(-) create mode 100644 internal/metadata/swift/imports_test.go create mode 100644 internal/metadata/swift/metadata.go create mode 100644 internal/metadata/swift/metadata_test.go diff --git a/internal/handler/swift.go b/internal/handler/swift.go index cdef1682..40ba7358 100644 --- a/internal/handler/swift.go +++ b/internal/handler/swift.go @@ -3,7 +3,6 @@ package handler import ( "context" "crypto/sha256" - "encoding/base64" "encoding/hex" "encoding/json" "errors" @@ -14,6 +13,7 @@ import ( "strings" "github.com/git-pkgs/proxy/internal/config" + "github.com/git-pkgs/proxy/internal/metadata/swift" "github.com/git-pkgs/proxy/internal/packageurl" "github.com/git-pkgs/proxy/internal/retention" "github.com/git-pkgs/purl" @@ -24,8 +24,6 @@ const ( swiftAcceptManifest = "application/vnd.swift.registry.v1+swift" swiftAcceptArchive = "application/vnd.swift.registry.v1+zip" swiftContentVersion = "1" - swiftMaxScopeLength = 39 - swiftMaxNameLength = 100 ) // Source archives are stored under the registry identity, @@ -417,18 +415,6 @@ func (h *SwiftHandler) fetchMetadataWithHeaders( return body, contentType, resp.Header.Clone(), nil } -type swiftReleaseMetadata struct { - Resources []struct { - Name string `json:"name"` - Type string `json:"type"` - Checksum string `json:"checksum"` - Signing *struct { - Signature string `json:"signatureBase64Encoded"` - Format string `json:"signatureFormat"` - } `json:"signing"` - } `json:"resources"` -} - type swiftArchiveInfo struct { checksum string signature string @@ -444,38 +430,15 @@ func (h *SwiftHandler) fetchArchiveInfo(ctx context.Context, scope, name, versio return swiftArchiveInfo{}, err } - var metadata swiftReleaseMetadata - if err := json.Unmarshal(body, &metadata); err != nil { - return swiftArchiveInfo{}, fmt.Errorf("parsing release metadata: %w", err) - } - for _, resource := range metadata.Resources { - if resource.Name != "source-archive" || resource.Type != "application/zip" { - continue - } - checksum, err := normalizeSwiftChecksum(resource.Checksum) - if err != nil { - return swiftArchiveInfo{}, err - } - info := swiftArchiveInfo{checksum: checksum} - if resource.Signing != nil { - if resource.Signing.Signature == "" || resource.Signing.Format == "" { - return swiftArchiveInfo{}, errors.New("source archive signing metadata is incomplete") - } - info.signature = resource.Signing.Signature - info.signatureFormat = resource.Signing.Format - } - return info, nil - } - - return swiftArchiveInfo{}, errors.New("source archive is missing from release metadata") -} - -func normalizeSwiftChecksum(checksum string) (string, error) { - digest, err := hex.DecodeString(checksum) - if err != nil || len(digest) != sha256.Size { - return "", errors.New("source archive checksum is not a SHA-256 digest") + archive, err := swift.SourceArchive(body) + if err != nil { + return swiftArchiveInfo{}, err } - return hex.EncodeToString(digest), nil + return swiftArchiveInfo{ + checksum: archive.Checksum, + signature: archive.Signature, + signatureFormat: archive.SignatureFormat, + }, nil } func setSwiftArchiveHeaders(header http.Header, name, version, contentHash string, info swiftArchiveInfo) { @@ -497,96 +460,23 @@ func setSwiftArchiveHeaders(header http.Header, name, version, contentHash strin } func swiftDigestHeader(checksum string) string { - digest, err := hex.DecodeString(checksum) - if err != nil || len(digest) != sha256.Size { - return "" - } - return "sha-256=" + base64.StdEncoding.EncodeToString(digest) + return swift.DigestHeader(checksum) } +// rewriteLinkHeader points the upstream URLs in a Link header at the proxy +// (see swift.RewriteLinkHeader). func (h *SwiftHandler) rewriteLinkHeader(value, upstreamRequestURL string) string { - var result strings.Builder - for len(value) > 0 { - start := strings.IndexByte(value, '<') - if start < 0 { - result.WriteString(value) - break - } - endOffset := strings.IndexByte(value[start+1:], '>') - if endOffset < 0 { - result.WriteString(value) - break - } - end := start + 1 + endOffset - result.WriteString(value[:start+1]) - result.WriteString(h.rewriteRegistryURL(value[start+1:end], upstreamRequestURL)) - result.WriteByte('>') - value = value[end+1:] - } - return result.String() -} - -func (h *SwiftHandler) rewriteRegistryURL(rawURL, upstreamRequestURL string) string { - base, err := url.Parse(h.upstreamURL) - if err != nil { - return rawURL - } - requestURL, err := url.Parse(upstreamRequestURL) - if err != nil { - return rawURL - } - reference, err := url.Parse(rawURL) - if err != nil { - return rawURL - } - absolute := requestURL.ResolveReference(reference) - if !strings.EqualFold(absolute.Scheme, base.Scheme) || !strings.EqualFold(absolute.Host, base.Host) { - return rawURL - } - - basePath := strings.TrimSuffix(base.EscapedPath(), "/") - absolutePath := absolute.EscapedPath() - if absolutePath != basePath && !strings.HasPrefix(absolutePath, basePath+"/") { - return rawURL - } - suffix := strings.TrimPrefix(absolutePath, basePath) - rewritten := h.proxyURL + "/swift" + suffix - if absolute.RawQuery != "" { - rewritten += "?" + absolute.RawQuery - } - if absolute.Fragment != "" { - rewritten += "#" + absolute.Fragment - } - return rewritten + return swift.RewriteLinkHeader(value, upstreamRequestURL, h.rewriteOptions()) } +// rewriteReleaseURLs points a release list's release URLs at the proxy (see +// swift.RewriteReleaseURLs). func (h *SwiftHandler) rewriteReleaseURLs(scope, name string, body []byte) ([]byte, error) { - var metadata map[string]any - if err := json.Unmarshal(body, &metadata); err != nil { - return nil, err - } - releases, ok := metadata["releases"].(map[string]any) - if !ok { - return body, nil - } + return swift.RewriteReleaseURLs(scope, name, body, h.rewriteOptions()) +} - for version, value := range releases { - release, ok := value.(map[string]any) - if !ok { - continue - } - if _, hasURL := release["url"]; !hasURL { - continue - } - release["url"] = fmt.Sprintf( - "%s/swift/%s/%s/%s", - h.proxyURL, - url.PathEscape(scope), - url.PathEscape(name), - url.PathEscape(version), - ) - } - return json.Marshal(metadata) +func (h *SwiftHandler) rewriteOptions() swift.Options { + return swift.Options{ProxyURL: h.proxyURL, UpstreamURL: h.upstreamURL} } func (h *SwiftHandler) buildUpstreamURL(scope, name, version, resource, rawQuery string) string { @@ -702,42 +592,17 @@ func writeSwiftProblem(w http.ResponseWriter, status int, detail string) { } func validSwiftPackageReference(scope, name, version string) bool { - return validSwiftScope(scope) && validSwiftPackageName(name) && version != "" && version != "." && version != ".." && !strings.ContainsAny(version, "/\\") + return swift.ValidPackageReference(scope, name, version) } func canonicalSwiftPackage(scope, name string) (string, string) { - return strings.ToLower(scope), strings.ToLower(name) + return swift.CanonicalPackage(scope, name) } func validSwiftScope(scope string) bool { - return validSwiftIdentifier(scope, swiftMaxScopeLength, "-") + return swift.ValidScope(scope) } func validSwiftPackageName(name string) bool { - return validSwiftIdentifier(name, swiftMaxNameLength, "-_") -} - -func validSwiftIdentifier(value string, maxLength int, separators string) bool { - if value == "" || len(value) > maxLength { - return false - } - previousSeparator := false - for i := 0; i < len(value); i++ { - character := value[i] - separator := strings.ContainsRune(separators, rune(character)) - if separator { - if i == 0 || i == len(value)-1 || previousSeparator { - return false - } - previousSeparator = true - continue - } - if (character < 'a' || character > 'z') && - (character < 'A' || character > 'Z') && - (character < '0' || character > '9') { - return false - } - previousSeparator = false - } - return true + return swift.ValidPackageName(name) } diff --git a/internal/metadata/swift/imports_test.go b/internal/metadata/swift/imports_test.go new file mode 100644 index 00000000..c2519ad0 --- /dev/null +++ b/internal/metadata/swift/imports_test.go @@ -0,0 +1,38 @@ +package swift + +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/proxy/internal/metadata/swift", + } + 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/swift/metadata.go b/internal/metadata/swift/metadata.go new file mode 100644 index 00000000..4152cd40 --- /dev/null +++ b/internal/metadata/swift/metadata.go @@ -0,0 +1,249 @@ +// Package swift holds the Swift Package Registry metadata transformations +// the proxy applies, with their inputs passed explicitly so the package +// builds without the proxy's handler, storage or database. +package swift + +import ( + "crypto/sha256" + "encoding/base64" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "net/url" + "strings" +) + +const ( + // MaxScopeLength and MaxNameLength bound a package scope and name, as + // the registry specification does. + MaxScopeLength = 39 + MaxNameLength = 100 +) + +// Options are the URLs the rewrites map between. +type Options struct { + // ProxyURL is the proxy's public base URL, without a trailing slash. + ProxyURL string + // UpstreamURL is the registry's base URL, without a trailing slash. + // Only URLs under it are rewritten. + UpstreamURL string +} + +// RewriteLinkHeader rewrites each in a Link header value with +// RewriteRegistryURL, resolving relative ones against upstreamRequestURL, +// and leaves the rest of the value as it is. +func RewriteLinkHeader(value, upstreamRequestURL string, o Options) string { + var result strings.Builder + for len(value) > 0 { + start := strings.IndexByte(value, '<') + if start < 0 { + result.WriteString(value) + break + } + endOffset := strings.IndexByte(value[start+1:], '>') + if endOffset < 0 { + result.WriteString(value) + break + } + end := start + 1 + endOffset + result.WriteString(value[:start+1]) + result.WriteString(RewriteRegistryURL(value[start+1:end], upstreamRequestURL, o)) + result.WriteByte('>') + value = value[end+1:] + } + return result.String() +} + +// RewriteRegistryURL points rawURL, resolved against upstreamRequestURL, +// at the proxy's /swift path when it is under the upstream URL. Other URLs, +// and any that don't parse, are returned as they are. +func RewriteRegistryURL(rawURL, upstreamRequestURL string, o Options) string { + base, err := url.Parse(o.UpstreamURL) + if err != nil { + return rawURL + } + requestURL, err := url.Parse(upstreamRequestURL) + if err != nil { + return rawURL + } + reference, err := url.Parse(rawURL) + if err != nil { + return rawURL + } + absolute := requestURL.ResolveReference(reference) + if !strings.EqualFold(absolute.Scheme, base.Scheme) || !strings.EqualFold(absolute.Host, base.Host) { + return rawURL + } + + basePath := strings.TrimSuffix(base.EscapedPath(), "/") + absolutePath := absolute.EscapedPath() + if absolutePath != basePath && !strings.HasPrefix(absolutePath, basePath+"/") { + return rawURL + } + suffix := strings.TrimPrefix(absolutePath, basePath) + rewritten := o.ProxyURL + "/swift" + suffix + if absolute.RawQuery != "" { + rewritten += "?" + absolute.RawQuery + } + if absolute.Fragment != "" { + rewritten += "#" + absolute.Fragment + } + return rewritten +} + +// RewriteReleaseURLs points the url of each release in a package's release +// list at the proxy. A document without a releases object is returned as +// it is. +func RewriteReleaseURLs(scope, name string, body []byte, o Options) ([]byte, error) { + var metadata map[string]any + if err := json.Unmarshal(body, &metadata); err != nil { + return nil, err + } + releases, ok := metadata["releases"].(map[string]any) + if !ok { + return body, nil + } + + for version, value := range releases { + release, ok := value.(map[string]any) + if !ok { + continue + } + if _, hasURL := release["url"]; !hasURL { + continue + } + release["url"] = ReleaseURL(o.ProxyURL, scope, name, version) + } + return json.Marshal(metadata) +} + +// ReleaseURL is where the proxy serves a release's metadata. +func ReleaseURL(proxyURL, scope, name, version string) string { + return fmt.Sprintf( + "%s/swift/%s/%s/%s", + proxyURL, + url.PathEscape(scope), + url.PathEscape(name), + url.PathEscape(version), + ) +} + +// ArchiveInfo is what a release's metadata says about its source archive. +type ArchiveInfo struct { + // Checksum is the archive's SHA-256, lowercase hex. + Checksum string + // Signature and SignatureFormat are set when the archive is signed. + Signature string + SignatureFormat string +} + +type releaseMetadata struct { + Resources []struct { + Name string `json:"name"` + Type string `json:"type"` + Checksum string `json:"checksum"` + Signing *struct { + Signature string `json:"signatureBase64Encoded"` + Format string `json:"signatureFormat"` + } `json:"signing"` + } `json:"resources"` +} + +// SourceArchive reads the source-archive resource from a release's +// metadata: its checksum, and its signature when it is signed. +func SourceArchive(body []byte) (ArchiveInfo, error) { + var metadata releaseMetadata + if err := json.Unmarshal(body, &metadata); err != nil { + return ArchiveInfo{}, fmt.Errorf("parsing release metadata: %w", err) + } + for _, resource := range metadata.Resources { + if resource.Name != "source-archive" || resource.Type != "application/zip" { + continue + } + checksum, err := NormalizeChecksum(resource.Checksum) + if err != nil { + return ArchiveInfo{}, err + } + info := ArchiveInfo{Checksum: checksum} + if resource.Signing != nil { + if resource.Signing.Signature == "" || resource.Signing.Format == "" { + return ArchiveInfo{}, errors.New("source archive signing metadata is incomplete") + } + info.Signature = resource.Signing.Signature + info.SignatureFormat = resource.Signing.Format + } + return info, nil + } + return ArchiveInfo{}, errors.New("source archive is missing from release metadata") +} + +// NormalizeChecksum returns a hex SHA-256 checksum in lowercase. +func NormalizeChecksum(checksum string) (string, error) { + digest, err := hex.DecodeString(checksum) + if err != nil || len(digest) != sha256.Size { + return "", errors.New("source archive checksum is not a SHA-256 digest") + } + return hex.EncodeToString(digest), nil +} + +// DigestHeader is the Digest header value for a hex SHA-256 checksum, +// empty when checksum isn't one. +func DigestHeader(checksum string) string { + digest, err := hex.DecodeString(checksum) + if err != nil || len(digest) != sha256.Size { + return "" + } + return "sha-256=" + base64.StdEncoding.EncodeToString(digest) +} + +// ValidPackageReference reports whether scope, name and version name a +// release: a valid scope and name, and a version that is a single path +// segment. +func ValidPackageReference(scope, name, version string) bool { + return ValidScope(scope) && ValidPackageName(name) && version != "" && version != "." && version != ".." && !strings.ContainsAny(version, "/\\") +} + +// CanonicalPackage is a package's scope and name as the registry compares +// them, lowercased. +func CanonicalPackage(scope, name string) (string, string) { + return strings.ToLower(scope), strings.ToLower(name) +} + +// ValidScope reports whether scope is a valid package scope: alphanumeric +// with single inner hyphens, at most MaxScopeLength long. +func ValidScope(scope string) bool { + return validIdentifier(scope, MaxScopeLength, "-") +} + +// ValidPackageName reports whether name is a valid package name: +// alphanumeric with single inner hyphens or underscores, at most +// MaxNameLength long. +func ValidPackageName(name string) bool { + return validIdentifier(name, MaxNameLength, "-_") +} + +func validIdentifier(value string, maxLength int, separators string) bool { + if value == "" || len(value) > maxLength { + return false + } + previousSeparator := false + for i := 0; i < len(value); i++ { + character := value[i] + separator := strings.ContainsRune(separators, rune(character)) + if separator { + if i == 0 || i == len(value)-1 || previousSeparator { + return false + } + previousSeparator = true + continue + } + if (character < 'a' || character > 'z') && + (character < 'A' || character > 'Z') && + (character < '0' || character > '9') { + return false + } + previousSeparator = false + } + return true +} diff --git a/internal/metadata/swift/metadata_test.go b/internal/metadata/swift/metadata_test.go new file mode 100644 index 00000000..feec4eb8 --- /dev/null +++ b/internal/metadata/swift/metadata_test.go @@ -0,0 +1,203 @@ +package swift + +import ( + "encoding/json" + "strings" + "testing" +) + +var testOptions = Options{ProxyURL: "https://proxy.example", UpstreamURL: "https://registry.example/base"} + +func TestRewriteRegistryURL(t *testing.T) { + request := "https://registry.example/base/apple/swift-nio" + tests := []struct { + name, raw, want string + }{ + {"absolute under upstream", "https://registry.example/base/apple/swift-nio?page=2", "https://proxy.example/swift/apple/swift-nio?page=2"}, + {"relative", "/base/apple/swift-nio/1.0.0#frag", "https://proxy.example/swift/apple/swift-nio/1.0.0#frag"}, + {"upstream root", "https://registry.example/base", "https://proxy.example/swift"}, + {"host case", "https://REGISTRY.example/base/a/b", "https://proxy.example/swift/a/b"}, + {"other host", "https://other.example/base/a/b", "https://other.example/base/a/b"}, + {"other scheme", "http://registry.example/base/a/b", "http://registry.example/base/a/b"}, + {"outside base path", "https://registry.example/basement/a", "https://registry.example/basement/a"}, + {"unparseable", "https://registry.example/%zz", "https://registry.example/%zz"}, + {"escaped path kept", "https://registry.example/base/a%2Fb/c", "https://proxy.example/swift/a%2Fb/c"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := RewriteRegistryURL(tt.raw, request, testOptions); got != tt.want { + t.Errorf("RewriteRegistryURL(%q) = %q, want %q", tt.raw, got, tt.want) + } + }) + } +} + +func TestRewriteRegistryURLBadInputs(t *testing.T) { + raw := "https://registry.example/base/a/b" + if got := RewriteRegistryURL(raw, "%zz://", testOptions); got != raw { + t.Errorf("bad request URL: got %q", got) + } + bad := Options{ProxyURL: "https://proxy.example", UpstreamURL: "%zz://"} + if got := RewriteRegistryURL(raw, raw, bad); got != raw { + t.Errorf("bad upstream URL: got %q", got) + } +} + +func TestRewriteLinkHeader(t *testing.T) { + request := "https://registry.example/base/apple/swift-nio" + value := `; rel="next", ; rel="alternate", ; rel="next", ; rel="alternate",