File: query.go

package info (click to toggle)
golang-golang-x-vuln 1.0.4-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 4,400 kB
  • sloc: sh: 161; asm: 40; makefile: 7
file content (74 lines) | stat: -rw-r--r-- 1,893 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
// Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package scan

import (
	"context"
	"fmt"
	"regexp"

	"golang.org/x/vuln/internal/client"
	"golang.org/x/vuln/internal/govulncheck"
	isem "golang.org/x/vuln/internal/semver"
)

// runQuery reports vulnerabilities that apply to the queries in the config.
func runQuery(ctx context.Context, handler govulncheck.Handler, cfg *config, c *client.Client) error {
	reqs := make([]*client.ModuleRequest, len(cfg.patterns))
	for i, query := range cfg.patterns {
		mod, ver, err := parseModuleQuery(query)
		if err != nil {
			return err
		}
		if err := handler.Progress(queryProgressMessage(mod, ver)); err != nil {
			return err
		}
		reqs[i] = &client.ModuleRequest{
			Path: mod, Version: ver,
		}
	}

	resps, err := c.ByModules(ctx, reqs)
	if err != nil {
		return err
	}

	ids := make(map[string]bool)
	for _, resp := range resps {
		for _, entry := range resp.Entries {
			if _, ok := ids[entry.ID]; !ok {
				err := handler.OSV(entry)
				if err != nil {
					return err
				}
				ids[entry.ID] = true
			}
		}
	}

	return nil
}

func queryProgressMessage(module, version string) *govulncheck.Progress {
	return &govulncheck.Progress{
		Message: fmt.Sprintf("Looking up vulnerabilities in %s at %s...", module, version),
	}
}

var modQueryRegex = regexp.MustCompile(`(.+)@(.+)`)

func parseModuleQuery(pattern string) (_ string, _ string, err error) {
	matches := modQueryRegex.FindStringSubmatch(pattern)
	// matches should be [module@version, module, version]
	if len(matches) != 3 {
		return "", "", fmt.Errorf("invalid query %s: must be of the form module@version", pattern)
	}
	mod, ver := matches[1], matches[2]
	if !isem.Valid(ver) {
		return "", "", fmt.Errorf("version %s is not valid semver", ver)
	}

	return mod, ver, nil
}