internal/deps/resolved.go

300 lines · 8788 bytes

  1package deps
  2
  3import (
  4	"encoding/json"
  5	"sort"
  6	"strings"
  7
  8	"github.com/BurntSushi/toml"
  9)
 10
 11// EcoSwift is reported for advisories only. Scan has no Swift reader: a
 12// SwiftPM dependency is a git URL on any host, and finding its latest
 13// release would mean listing tags on hosts the repository names.
 14const EcoSwift = "swift"
 15
 16// MaxResolved bounds the resolved set one repository sends for advisory
 17// matching. A lockfile lists the whole graph, so it is larger than MaxDeps.
 18const MaxResolved = 3000
 19
 20// swiftResolvedDirs are where Xcode keeps Package.resolved inside a project
 21// or workspace bundle at the repository root.
 22var swiftResolvedDirs = map[string]string{
 23	".xcodeproj":   "/project.xcworkspace/xcshareddata/swiftpm/Package.resolved",
 24	".xcworkspace": "/xcshareddata/swiftpm/Package.resolved",
 25}
 26
 27// Resolved returns every dependency whose exact version is known, for
 28// advisory matching: lockfiles where they exist, exact pins in manifests
 29// where they do not. A range is left out rather than reduced to its floor,
 30// since the floor is rarely what is installed and would match advisories
 31// the build does not have. root lists the names at the top of the tree,
 32// which is where Xcode bundles are looked for.
 33func Resolved(read ReadFile, root []string) []Dep {
 34	var out []Dep
 35	out = append(out, goRequires(read, true)...)
 36	out = append(out, npmResolved(read)...)
 37	out = append(out, cargoResolved(read)...)
 38	out = append(out, pythonResolved(read)...)
 39	out = append(out, swiftResolved(read, root)...)
 40	sort.Slice(out, func(i, j int) bool {
 41		if out[i].Ecosystem != out[j].Ecosystem {
 42			return out[i].Ecosystem < out[j].Ecosystem
 43		}
 44		if out[i].Name != out[j].Name {
 45			return out[i].Name < out[j].Name
 46		}
 47		return out[i].Current < out[j].Current
 48	})
 49	out = dedupe(out)
 50	if len(out) > MaxResolved {
 51		out = out[:MaxResolved]
 52	}
 53	return out
 54}
 55
 56func dedupe(sorted []Dep) []Dep {
 57	var out []Dep
 58	for i, d := range sorted {
 59		if i > 0 && d == sorted[i-1] {
 60			continue
 61		}
 62		out = append(out, d)
 63	}
 64	return out
 65}
 66
 67// exact is pin restricted to a requirement that names one release: bare,
 68// or after `==` or `=`. `^1.2` is a range in npm and Cargo, and so is a bare
 69// `1.2` in Cargo, which is why Cargo callers check for `=` themselves.
 70func exact(spec string) string {
 71	s := strings.TrimSpace(spec)
 72	s = strings.TrimPrefix(s, "==")
 73	s = strings.TrimPrefix(s, "=")
 74	if s == "" || strings.ContainsAny(s[:1], "^~<>!") {
 75		return ""
 76	}
 77	return pin(s)
 78}
 79
 80// npmResolved reads every install in package-lock.json, nested copies
 81// included, or the exact pins in package.json when there is no lockfile.
 82func npmResolved(read ReadFile) []Dep {
 83	if raw, err := read("package-lock.json"); err == nil {
 84		var lock struct {
 85			Packages map[string]struct {
 86				Version string `json:"version"`
 87				Link    bool   `json:"link"`
 88			} `json:"packages"`
 89		}
 90		if json.Unmarshal(raw, &lock) != nil {
 91			return nil
 92		}
 93		var out []Dep
 94		for path, entry := range lock.Packages {
 95			i := strings.LastIndex(path, "node_modules/")
 96			if i < 0 || entry.Link {
 97				continue
 98			}
 99			if v := pin(entry.Version); v != "" {
100				out = append(out, Dep{Ecosystem: EcoNPM, Name: path[i+len("node_modules/"):], Current: v})
101			}
102		}
103		return out
104	}
105	raw, err := read("package.json")
106	if err != nil {
107		return nil
108	}
109	var pkg struct {
110		Dependencies    map[string]string `json:"dependencies"`
111		DevDependencies map[string]string `json:"devDependencies"`
112	}
113	if json.Unmarshal(raw, &pkg) != nil {
114		return nil
115	}
116	var out []Dep
117	for _, set := range []map[string]string{pkg.Dependencies, pkg.DevDependencies} {
118		for name, spec := range set {
119			if v := exact(spec); v != "" {
120				out = append(out, Dep{Ecosystem: EcoNPM, Name: name, Current: v})
121			}
122		}
123	}
124	return out
125}
126
127// cargoResolved reads the crates.io packages in Cargo.lock, or the `=`
128// pins in Cargo.toml when there is no lockfile.
129func cargoResolved(read ReadFile) []Dep {
130	if raw, err := read("Cargo.lock"); err == nil {
131		var lock struct {
132			Package []struct {
133				Name    string `toml:"name"`
134				Version string `toml:"version"`
135				Source  string `toml:"source"`
136			} `toml:"package"`
137		}
138		if toml.Unmarshal(raw, &lock) != nil {
139			return nil
140		}
141		var out []Dep
142		for _, p := range lock.Package {
143			// No source is a workspace member; a git source is not on
144			// crates.io.
145			if !strings.HasPrefix(p.Source, "registry+") && !strings.HasPrefix(p.Source, "sparse+") {
146				continue
147			}
148			if v := pin(p.Version); v != "" {
149				out = append(out, Dep{Ecosystem: EcoCargo, Name: p.Name, Current: v})
150			}
151		}
152		return out
153	}
154	raw, err := read("Cargo.toml")
155	if err != nil {
156		return nil
157	}
158	var manifest struct {
159		Dependencies      map[string]any `toml:"dependencies"`
160		DevDependencies   map[string]any `toml:"dev-dependencies"`
161		BuildDependencies map[string]any `toml:"build-dependencies"`
162	}
163	if toml.Unmarshal(raw, &manifest) != nil {
164		return nil
165	}
166	var out []Dep
167	for _, set := range []map[string]any{manifest.Dependencies, manifest.DevDependencies, manifest.BuildDependencies} {
168		for name, spec := range set {
169			req, ok := cargoRequirement(spec)
170			if !ok || !strings.HasPrefix(strings.TrimSpace(req), "=") {
171				continue
172			}
173			if v := exact(req); v != "" {
174				out = append(out, Dep{Ecosystem: EcoCargo, Name: name, Current: v})
175			}
176		}
177	}
178	return out
179}
180
181// pythonResolved reads uv.lock or poetry.lock, or the `==` pins in
182// requirements.txt and pyproject.toml when there is neither.
183func pythonResolved(read ReadFile) []Dep {
184	for _, lockfile := range []string{"uv.lock", "poetry.lock"} {
185		raw, err := read(lockfile)
186		if err != nil {
187			continue
188		}
189		var lock struct {
190			Package []struct {
191				Name    string         `toml:"name"`
192				Version string         `toml:"version"`
193				Source  map[string]any `toml:"source"`
194			} `toml:"package"`
195		}
196		if toml.Unmarshal(raw, &lock) != nil {
197			return nil
198		}
199		var out []Dep
200		for _, p := range lock.Package {
201			if !fromPyPI(p.Source) {
202				continue
203			}
204			if v := pin(p.Version); v != "" {
205				out = append(out, Dep{Ecosystem: EcoPyPI, Name: normalizePyPI(p.Name), Current: v})
206			}
207		}
208		return out
209	}
210	return pythonDeps(read, exact)
211}
212
213// fromPyPI reads a lockfile package's source. uv records
214// `source = { registry = "..." }` for an index and `editable`, `virtual`,
215// `path`, `directory` or `git` otherwise; poetry records no source for PyPI
216// and a typed one otherwise.
217func fromPyPI(source map[string]any) bool {
218	if len(source) == 0 {
219		return true
220	}
221	if _, ok := source["registry"]; ok {
222		return true
223	}
224	typ, _ := source["type"].(string)
225	return typ == "legacy"
226}
227
228// swiftResolved reads Package.resolved at the root and inside any Xcode
229// project or workspace at the root. Version 1 files nest the pins under
230// `object` and name the URL `repositoryURL`; versions 2 and 3 use `pins`
231// and `location`. A pin to a branch or a revision has no version and is
232// left out.
233func swiftResolved(read ReadFile, root []string) []Dep {
234	paths := []string{"Package.resolved"}
235	for _, name := range root {
236		for suffix, inside := range swiftResolvedDirs {
237			if strings.HasSuffix(name, suffix) {
238				paths = append(paths, name+inside)
239			}
240		}
241	}
242	sort.Strings(paths[1:])
243	var out []Dep
244	for _, path := range paths {
245		raw, err := read(path)
246		if err != nil {
247			continue
248		}
249		type pinned struct {
250			Location      string `json:"location"`
251			RepositoryURL string `json:"repositoryURL"`
252			State         struct {
253				Version string `json:"version"`
254			} `json:"state"`
255		}
256		var doc struct {
257			Pins   []pinned `json:"pins"`
258			Object struct {
259				Pins []pinned `json:"pins"`
260			} `json:"object"`
261		}
262		if json.Unmarshal(raw, &doc) != nil {
263			continue
264		}
265		for _, p := range append(doc.Pins, doc.Object.Pins...) {
266			url := p.Location
267			if url == "" {
268				url = p.RepositoryURL
269			}
270			name := swiftURLName(url)
271			if v := pin(p.State.Version); v != "" && name != "" {
272				out = append(out, Dep{Ecosystem: EcoSwift, Name: name, Current: v})
273			}
274		}
275	}
276	return out
277}
278
279// swiftURLName reduces a package URL to the form OSV's SwiftURL ecosystem
280// keys on: host and path, no scheme, user or .git suffix.
281// `https://github.com/vapor/vapor.git` and `git@github.com:vapor/vapor`
282// both become `github.com/vapor/vapor`. A local path has no name.
283func swiftURLName(url string) string {
284	u := strings.TrimSpace(url)
285	if i := strings.Index(u, "://"); i >= 0 {
286		u = u[i+3:]
287	} else if at := strings.Index(u, "@"); at >= 0 && strings.Contains(u[at:], ":") {
288		u = strings.Replace(u[at+1:], ":", "/", 1)
289	} else {
290		return ""
291	}
292	if at := strings.Index(u, "@"); at >= 0 && at < strings.Index(u+"/", "/") {
293		u = u[at+1:]
294	}
295	u = strings.TrimSuffix(strings.TrimSuffix(u, "/"), ".git")
296	if !strings.Contains(u, "/") || strings.HasPrefix(u, "/") {
297		return ""
298	}
299	return u
300}