Commit a30ca59fb3
Verified · cmc ci/build: success ci/quality: success ci/test: success
Layout: unified · split
.gitbay/wiki/Architecture/01-System-Context.org +1
| @@ -39,6 +39,7 @@ do not reimplement logic (=internal/httpd/control.go=, | |||
| 39 | | Webhook endpoints | out | event delivery, user-configured | =internal/webhook/webhook.go= | | 39 | | Webhook endpoints | out | event delivery, user-configured | =internal/webhook/webhook.go= | |
| 40 | | Mirror remotes | out / in | push and pull mirrors, user-configured | =internal/mirror/mirror.go= | | 40 | | Mirror remotes | out / in | push and pull mirrors, user-configured | =internal/mirror/mirror.go= | |
| 41 | | Package registries | out | dependency update checks (opt-in per repo)| =internal/deps/registry.go= | | 41 | | Package registries | out | dependency update checks (opt-in per repo)| =internal/deps/registry.go= | |
| 42 | | OSV | out | dependency advisory checks (same opt-in) | =internal/deps/osv.go= | | ||
| 42 | | Offsite object storage | out | restic backups (host timer, not gitbayd) | documented: Admin wiki | | 43 | | Offsite object storage | out | restic backups (host timer, not gitbayd) | documented: Admin wiki | |
| 43 | 44 | ||
| 44 | gitbayd makes no other outbound connection: no telemetry or update | 45 | gitbayd makes no other outbound connection: no telemetry or update |
.gitbay/wiki/Architecture/03-Deployment.org +1
| @@ -66,6 +66,7 @@ a database check. | |||
| 66 | | Webhook URLs | recorded events | yes when https; certificate verified | private, shared, loopback, link-local and multicast targets refused at save and again at connect time; no redirects (=internal/webhook/webhook.go=) | | 66 | | Webhook URLs | recorded events | yes when https; certificate verified | private, shared, loopback, link-local and multicast targets refused at save and again at connect time; no redirects (=internal/webhook/webhook.go=) | |
| 67 | | Mirror URLs | mirror schedule | per URL | address check at save and before each sync; git pinned to the checked addresses, no redirects (=internal/mirror/mirror.go=) | | 67 | | Mirror URLs | mirror schedule | per URL | address check at save and before each sync; git pinned to the checked addresses, no redirects (=internal/mirror/mirror.go=) | |
| 68 | | Package registries | dependency checks | yes | fixed hosts; only the package name varies (=internal/deps/registry.go=) | | 68 | | Package registries | dependency checks | yes | fixed hosts; only the package name varies (=internal/deps/registry.go=) | |
| 69 | | OSV (=api.osv.dev=) | dependency checks | yes | fixed host; sent ecosystem, package name and version (=internal/deps/osv.go=) | | ||
| 69 | 70 | ||
| 70 | * Host firewall | 71 | * Host firewall |
| 71 | 72 | ||
.gitbay/wiki/Architecture/06-Data-and-Cryptography.org +1 −1
| @@ -19,7 +19,7 @@ content (as confidential as the repository), *O* operational. | |||
| 19 | | Notifications | =notifications= (mail queue), =inbox=, =push_devices= (APNs token), =push_queue=, =mail_replies= (Message-IDs of posted replies) | P | device tokens sealed; looked up by SHA-256 | | 19 | | Notifications | =notifications= (mail queue), =inbox=, =push_devices= (APNs token), =push_queue=, =mail_replies= (Message-IDs of posted replies) | P | device tokens sealed; looked up by SHA-256 | |
| 20 | | Signatures | =commit_signatures=, =settings.key_epoch= | O | verification cache | | 20 | | Signatures | =commit_signatures=, =settings.key_epoch= | O | verification cache | |
| 21 | | Audit and feed | =audit_log=, =events= | O, P | actor ids, pruned argv, fingerprints and IPs in some audit rows, a hash chain (=prev_hash=, =hash=) | | 21 | | Audit and feed | =audit_log=, =events= | O, P | actor ids, pruned argv, fingerprints and IPs in some audit rows, a hash chain (=prev_hash=, =hash=) | |
| 22 | | Dependencies | =dep_checks=, =dep_reports= | O | | | 22 | | Dependencies | =dep_checks=, =dep_reports=, =dep_advisories= | O | | |
| 23 | 23 | ||
| 24 | Outside the database: | 24 | Outside the database: |
| 25 | 25 | ||
.gitbay/wiki/Architecture/07-CI-and-Supply-Chain.org +1 −1
| @@ -78,7 +78,7 @@ Who may do what: | |||
| 78 | |-------------+----------------------+--------------------------------------------------------------------------------| | 78 | |-------------+----------------------+--------------------------------------------------------------------------------| |
| 79 | | Webhooks | recorded events | SSRF checks at save and connect time, no redirects, HMAC-SHA256 signature, 5 attempts with exponential backoff, response body capped at 4 KiB (=internal/webhook/webhook.go=) | | 79 | | Webhooks | recorded events | SSRF checks at save and connect time, no redirects, HMAC-SHA256 signature, 5 attempts with exponential backoff, response body capped at 4 KiB (=internal/webhook/webhook.go=) | |
| 80 | | Mirrors | schedule | address check at save and before each sync, git pinned to the checked addresses, no redirects; token via =GIT_ASKPASS= script (0700); heads and tags only; 10-minute timeout (=internal/mirror/mirror.go=) | | 80 | | Mirrors | schedule | address check at save and before each sync, git pinned to the checked addresses, no redirects; token via =GIT_ASKPASS= script (0700); heads and tags only; 10-minute timeout (=internal/mirror/mirror.go=) | |
| 81 | | Dependency checks | schedule, opt-in | fixed registry hosts; package names restricted (=internal/deps/registry.go=) | | 81 | | Dependency checks | schedule, opt-in | fixed registry hosts and OSV; package names restricted (=internal/deps/registry.go=, =internal/deps/osv.go=) | |
| 82 | 82 | ||
| 83 | * The project's own supply chain | 83 | * The project's own supply chain |
| 84 | 84 | ||
.gitbay/wiki/Parity.org +6 −5
| @@ -280,11 +280,12 @@ The web's watch and pin controls dispatch =repo pin=/=repo unpin= and | |||
| 280 | muted. | 280 | muted. |
| 281 | 281 | ||
| 282 | Dependency checks are off until a repository's admin turns them on: the | 282 | Dependency checks are off until a repository's admin turns them on: the |
| 283 | check tells a public registry what the repository depends on. =repo deps | 283 | check tells a public registry and OSV what the repository depends on. |
| 284 | status= lists what is behind; the repository's settings page renders the | 284 | =repo deps status= lists what is behind and which advisories match the |
| 285 | same report under the toggle — last check, last error, the tracking | 285 | resolved set; the repository's settings page renders the same report |
| 286 | issue, and the rows. The issue the worker opens, rewrites and closes is | 286 | under the toggle — last check, last error, the two tracking issues, and |
| 287 | still the copy every other surface reads. | 287 | the rows. The issues the worker opens, rewrites and closes are still the |
| 288 | copies every other surface reads. | ||
| 288 | 289 | ||
| 289 | The wiki row covers reading. A wiki lives at =.gitbay/wiki/= on the | 290 | The wiki row covers reading. A wiki lives at =.gitbay/wiki/= on the |
| 290 | default branch, so editing one is editing a file in the repository — | 291 | default branch, so editing one is editing a file in the repository — |
cmd/gitbay/summaries_gen.go +1 −1
| @@ -166,7 +166,7 @@ var summaries = map[string]string{ | |||
| 166 | "repo deploy-key list": "list deploy keys", | 166 | "repo deploy-key list": "list deploy keys", |
| 167 | "repo deploy-key remove": "remove a deploy key", | 167 | "repo deploy-key remove": "remove a deploy key", |
| 168 | "repo deps disable": "stop checking dependencies", | 168 | "repo deps disable": "stop checking dependencies", |
| 169 | "repo deps enable": "check dependencies for updates", | 169 | "repo deps enable": "check dependencies for updates and advisories", |
| 170 | "repo deps status": "show dependency check state", | 170 | "repo deps status": "show dependency check state", |
| 171 | "repo diff": "the patch between two refs, from their merge base", | 171 | "repo diff": "the patch between two refs, from their merge base", |
| 172 | "repo domain add": "claim a custom pages domain (verify with a DNS TXT record)", | 172 | "repo domain add": "claim a custom pages domain (verify with a DNS TXT record)", |
internal/control/deps.go +60 −14
| @@ -12,11 +12,11 @@ import ( | |||
| 12 | ) | 12 | ) |
| 13 | 13 | ||
| 14 | func init() { | 14 | func init() { |
| 15 | // Dependency update checks. Opt-in per repository: the check tells a | 15 | // Dependency update and advisory checks. Opt-in per repository: the |
| 16 | // public registry what the repository depends on, which is the owner's | 16 | // check tells a public registry and OSV what the repository depends on, |
| 17 | // disclosure to make, not the instance's. | 17 | // which is the owner's disclosure to make, not the instance's. |
| 18 | register(Command{Path: []string{"repo", "deps", "enable"}, | 18 | register(Command{Path: []string{"repo", "deps", "enable"}, |
| 19 | Summary: "check dependencies for updates", | 19 | Summary: "check dependencies for updates and advisories", |
| 20 | Usage: "repo deps enable <owner/name>", | 20 | Usage: "repo deps enable <owner/name>", |
| 21 | Examples: []string{"repo deps enable krz/gitbay"}, | 21 | Examples: []string{"repo deps enable krz/gitbay"}, |
| 22 | Run: runDepsEnable}) | 22 | Run: runDepsEnable}) |
| @@ -33,14 +33,16 @@ func init() { | |||
| 33 | } | 33 | } |
| 34 | 34 | ||
| 35 | // DepsOut is what `repo deps status` emits: the check's state and what | 35 | // DepsOut is what `repo deps status` emits: the check's state and what |
| 36 | // the last run found behind. Named so the web decodes the same struct | 36 | // the last run found behind or matching an advisory. Named so the web |
| 37 | // the command writes. | 37 | // decodes the same struct the command writes. |
| 38 | type DepsOut struct { | 38 | type DepsOut struct { |
| 39 | Enabled bool `json:"enabled"` | 39 | Enabled bool `json:"enabled"` |
| 40 | LastCheck string `json:"last_check,omitempty"` | 40 | LastCheck string `json:"last_check,omitempty"` |
| 41 | LastError string `json:"last_error,omitempty"` | 41 | LastError string `json:"last_error,omitempty"` |
| 42 | IssueNumber int64 `json:"issue_number,omitempty"` | 42 | IssueNumber int64 `json:"issue_number,omitempty"` |
| 43 | Behind []DepBehind `json:"behind"` | 43 | AdvisoryIssueNumber int64 `json:"advisory_issue_number,omitempty"` |
| 44 | Behind []DepBehind `json:"behind"` | ||
| 45 | Advisories []DepAdvisory `json:"advisories"` | ||
| 44 | } | 46 | } |
| 45 | 47 | ||
| 46 | // DepBehind is one dependency with a newer release than the manifest pins. | 48 | // DepBehind is one dependency with a newer release than the manifest pins. |
| @@ -51,6 +53,17 @@ type DepBehind struct { | |||
| 51 | Latest string `json:"latest"` | 53 | Latest string `json:"latest"` |
| 52 | } | 54 | } |
| 53 | 55 | ||
| 56 | // DepAdvisory is one published advisory matching a resolved dependency. | ||
| 57 | type DepAdvisory struct { | ||
| 58 | Ecosystem string `json:"ecosystem"` | ||
| 59 | Name string `json:"name"` | ||
| 60 | Version string `json:"version"` | ||
| 61 | ID string `json:"id"` | ||
| 62 | Summary string `json:"summary"` | ||
| 63 | Severity string `json:"severity,omitempty"` | ||
| 64 | Fixed string `json:"fixed,omitempty"` | ||
| 65 | } | ||
| 66 | |||
| 54 | func runDepsEnable(c *Ctx, args []string) int { | 67 | func runDepsEnable(c *Ctx, args []string) int { |
| 55 | if len(args) != 1 { | 68 | if len(args) != 1 { |
| 56 | return c.usage() | 69 | return c.usage() |
| @@ -110,22 +123,35 @@ func runDepsStatus(c *Ctx, args []string) int { | |||
| 110 | if err != nil { | 123 | if err != nil { |
| 111 | return c.fail(protocol.ExitFailure, "%v", err) | 124 | return c.fail(protocol.ExitFailure, "%v", err) |
| 112 | } | 125 | } |
| 126 | advisories, err := c.Store.ReportedAdvisories(repo.ID) | ||
| 127 | if err != nil { | ||
| 128 | return c.fail(protocol.ExitFailure, "%v", err) | ||
| 129 | } | ||
| 113 | out := DepsOut{Enabled: true, LastCheck: check.LastCheck, LastError: check.LastError, | 130 | out := DepsOut{Enabled: true, LastCheck: check.LastCheck, LastError: check.LastError, |
| 114 | IssueNumber: check.IssueNumber, Behind: []DepBehind{}} | 131 | IssueNumber: check.IssueNumber, AdvisoryIssueNumber: check.AdvisoryIssueNumber, |
| 132 | Behind: []DepBehind{}, Advisories: []DepAdvisory{}} | ||
| 115 | for _, r := range reports { | 133 | for _, r := range reports { |
| 116 | out.Behind = append(out.Behind, DepBehind{r.Ecosystem, r.Name, r.Current, r.Latest}) | 134 | out.Behind = append(out.Behind, DepBehind{r.Ecosystem, r.Name, r.Current, r.Latest}) |
| 117 | } | 135 | } |
| 136 | for _, a := range advisories { | ||
| 137 | out.Advisories = append(out.Advisories, | ||
| 138 | DepAdvisory{a.Ecosystem, a.Name, a.Version, a.ID, a.Summary, a.Severity, a.Fixed}) | ||
| 139 | } | ||
| 118 | return c.emitView(out, func(w io.Writer) { | 140 | return c.emitView(out, func(w io.Writer) { |
| 119 | tracked := "" | 141 | tracked, advised := "", "" |
| 120 | if check.IssueNumber != 0 { | 142 | if check.IssueNumber != 0 { |
| 121 | tracked = fmt.Sprintf("#%d", check.IssueNumber) | 143 | tracked = fmt.Sprintf("#%d", check.IssueNumber) |
| 122 | } | 144 | } |
| 145 | if check.AdvisoryIssueNumber != 0 { | ||
| 146 | advised = fmt.Sprintf("#%d", check.AdvisoryIssueNumber) | ||
| 147 | } | ||
| 123 | v := c.view(w) | 148 | v := c.view(w) |
| 124 | v.fields( | 149 | v.fields( |
| 125 | "checks", "on", | 150 | "checks", "on", |
| 126 | "last check", c.when(check.LastCheck), | 151 | "last check", c.when(check.LastCheck), |
| 127 | "last error", check.LastError, | 152 | "last error", check.LastError, |
| 128 | "tracked in", tracked, | 153 | "tracked in", tracked, |
| 154 | "advisories in", advised, | ||
| 129 | ) | 155 | ) |
| 130 | if len(out.Behind) > 0 { | 156 | if len(out.Behind) > 0 { |
| 131 | v.section("behind") | 157 | v.section("behind") |
| @@ -135,6 +161,14 @@ func runDepsStatus(c *Ctx, args []string) int { | |||
| 135 | } | 161 | } |
| 136 | tb.flush() | 162 | tb.flush() |
| 137 | } | 163 | } |
| 164 | if len(out.Advisories) > 0 { | ||
| 165 | v.section("advisories") | ||
| 166 | tb := c.table(w, "ECOSYSTEM", "NAME", "VERSION", "ADVISORY", "FIXED") | ||
| 167 | for _, a := range out.Advisories { | ||
| 168 | tb.row(cText(a.Ecosystem), cRef(a.Name), cText(a.Version), cText(a.ID), cText(a.Fixed)) | ||
| 169 | } | ||
| 170 | tb.flush() | ||
| 171 | } | ||
| 138 | }, func() screen { | 172 | }, func() screen { |
| 139 | state := []cell{cGlyph("ok"), cText("on")} | 173 | state := []cell{cGlyph("ok"), cText("on")} |
| 140 | if check.LastError != "" { | 174 | if check.LastError != "" { |
| @@ -149,11 +183,23 @@ func runDepsStatus(c *Ctx, args []string) int { | |||
| 149 | n := strconv.FormatInt(check.IssueNumber, 10) | 183 | n := strconv.FormatInt(check.IssueNumber, 10) |
| 150 | s.fields = append(s.fields, field{"Tracked in", []cell{cLink("#"+n, c.siteURL(repo.Path(), "issues", n))}}) | 184 | s.fields = append(s.fields, field{"Tracked in", []cell{cLink("#"+n, c.siteURL(repo.Path(), "issues", n))}}) |
| 151 | } | 185 | } |
| 186 | if check.AdvisoryIssueNumber != 0 { | ||
| 187 | n := strconv.FormatInt(check.AdvisoryIssueNumber, 10) | ||
| 188 | s.fields = append(s.fields, field{"Advisories in", []cell{cLink("#"+n, c.siteURL(repo.Path(), "issues", n))}}) | ||
| 189 | } | ||
| 152 | behind := section{title: "Behind", n: len(out.Behind)} | 190 | behind := section{title: "Behind", n: len(out.Behind)} |
| 153 | for _, b := range out.Behind { | 191 | for _, b := range out.Behind { |
| 154 | behind.rows = append(behind.rows, rowOf(cRef(b.Name), cText(b.Ecosystem), cMeta(b.Current+" → "+b.Latest))) | 192 | behind.rows = append(behind.rows, rowOf(cRef(b.Name), cText(b.Ecosystem), cMeta(b.Current+" → "+b.Latest))) |
| 155 | } | 193 | } |
| 156 | s.sections = []section{behind} | 194 | advised := section{title: "Advisories", n: len(out.Advisories)} |
| 195 | for _, a := range out.Advisories { | ||
| 196 | fix := a.Version | ||
| 197 | if a.Fixed != "" { | ||
| 198 | fix += " → " + a.Fixed | ||
| 199 | } | ||
| 200 | advised.rows = append(advised.rows, rowOf(cRef(a.Name), cMark(a.ID, sgrRed), cMeta(fix))) | ||
| 201 | } | ||
| 202 | s.sections = []section{behind, advised} | ||
| 157 | s.actions = []action{{"Deps", []string{"repo", "deps", "disable", repo.Path()}}} | 203 | s.actions = []action{{"Deps", []string{"repo", "deps", "disable", repo.Path()}}} |
| 158 | return s | 204 | return s |
| 159 | }) | 205 | }) |
internal/control/stage3repo_test.go +32
| @@ -3,6 +3,7 @@ package control | |||
| 3 | import ( | 3 | import ( |
| 4 | "bytes" | 4 | "bytes" |
| 5 | "crypto/ed25519" | 5 | "crypto/ed25519" |
| 6 | "encoding/json" | ||
| 6 | "os" | 7 | "os" |
| 7 | "os/exec" | 8 | "os/exec" |
| 8 | "path/filepath" | 9 | "path/filepath" |
| @@ -318,3 +319,34 @@ func TestRepoScreensFitSixtyColumns(t *testing.T) { | |||
| 318 | } | 319 | } |
| 319 | } | 320 | } |
| 320 | } | 321 | } |
| 322 | |||
| 323 | func TestRepoDepsStatusAdvisories(t *testing.T) { | ||
| 324 | st, repo, u, root := browseFixture(t) | ||
| 325 | p := repo.Path() | ||
| 326 | dispatchIn(t, st, u, root, "", "repo", "deps", "enable", p) | ||
| 327 | if err := st.ReplaceDepAdvisories(repo.ID, []store.DepAdvisory{{Ecosystem: "go", Name: "golang.org/x/net", | ||
| 328 | Version: "v0.1.0", ID: "GO-2026-1", Summary: "reset flood", Severity: "high", Fixed: "0.7.0"}}); err != nil { | ||
| 329 | t.Fatal(err) | ||
| 330 | } | ||
| 331 | if err := st.SetDepAdvisoryIssue(repo.ID, 7); err != nil { | ||
| 332 | t.Fatal(err) | ||
| 333 | } | ||
| 334 | var got struct { | ||
| 335 | Data DepsOut `json:"data"` | ||
| 336 | } | ||
| 337 | if err := json.Unmarshal([]byte(dispatchIn(t, st, u, root, "", "repo", "deps", "status", p, "--json")), &got); err != nil { | ||
| 338 | t.Fatal(err) | ||
| 339 | } | ||
| 340 | if got.Data.AdvisoryIssueNumber != 7 || len(got.Data.Advisories) != 1 || got.Data.Advisories[0].ID != "GO-2026-1" { | ||
| 341 | t.Errorf("status = %+v", got.Data) | ||
| 342 | } | ||
| 343 | plain := dispatchIn(t, st, u, root, "", "repo", "deps", "status", p) | ||
| 344 | if !strings.Contains(plain, "advisories in #7") || !strings.Contains(plain, "GO-2026-1") { | ||
| 345 | t.Errorf("plain:\n%s", plain) | ||
| 346 | } | ||
| 347 | out := atTerminalIn(t, st, u, root, "repo", "deps", "status", p) | ||
| 348 | if !strings.Contains(out, "Advisories (1)") || !strings.Contains(out, "v0.1.0 → 0.7.0") { | ||
| 349 | t.Errorf("screen:\n%s", out) | ||
| 350 | } | ||
| 351 | checkLegend(t, out) | ||
| 352 | } | ||
internal/deps/gomod.go +7 −2
| @@ -6,7 +6,12 @@ import "strings" | |||
| 6 | // requirements are the module graph's business rather than the maintainer's, | 6 | // requirements are the module graph's business rather than the maintainer's, |
| 7 | // and a replaced module does not come from the proxy at all, so both are | 7 | // and a replaced module does not come from the proxy at all, so both are |
| 8 | // skipped. | 8 | // skipped. |
| 9 | func parseGoMod(read ReadFile) []Dep { | 9 | func parseGoMod(read ReadFile) []Dep { return goRequires(read, false) } |
| 10 | |||
| 11 | // goRequires reads go.mod's requirements, the indirect ones too when asked. | ||
| 12 | // Since Go 1.17 go.mod lists every module the build selects, so with them it | ||
| 13 | // is the resolved set. | ||
| 14 | func goRequires(read ReadFile, withIndirect bool) []Dep { | ||
| 10 | raw, err := read("go.mod") | 15 | raw, err := read("go.mod") |
| 11 | if err != nil { | 16 | if err != nil { |
| 12 | return nil | 17 | return nil |
| @@ -41,7 +46,7 @@ func parseGoMod(read ReadFile) []Dep { | |||
| 41 | } | 46 | } |
| 42 | fields := strings.Fields(line) | 47 | fields := strings.Fields(line) |
| 43 | switch { | 48 | switch { |
| 44 | case directive == "require" && !indirect && len(fields) >= 2: | 49 | case directive == "require" && (withIndirect || !indirect) && len(fields) >= 2: |
| 45 | reqs = append(reqs, [2]string{fields[0], fields[1]}) | 50 | reqs = append(reqs, [2]string{fields[0], fields[1]}) |
| 46 | case directive == "replace" && len(fields) >= 1: | 51 | case directive == "replace" && len(fields) >= 1: |
| 47 | replaced[fields[0]] = true | 52 | replaced[fields[0]] = true |
internal/deps/osv.go added +302
| @@ -0,0 +1,302 @@ | |||
| 1 | package deps | ||
| 2 | |||
| 3 | import ( | ||
| 4 | "bytes" | ||
| 5 | "context" | ||
| 6 | "encoding/json" | ||
| 7 | "fmt" | ||
| 8 | "io" | ||
| 9 | "net/http" | ||
| 10 | "net/url" | ||
| 11 | "sort" | ||
| 12 | "strings" | ||
| 13 | "sync" | ||
| 14 | |||
| 15 | "gitbay.org/gitbay/internal/store" | ||
| 16 | ) | ||
| 17 | |||
| 18 | // osvAPI is OSV's public API, a fixed host like the registries. What it is | ||
| 19 | // sent is the resolved set: ecosystem, package name and version. | ||
| 20 | const osvAPI = "https://api.osv.dev" | ||
| 21 | |||
| 22 | // osvEcosystems are OSV's names for the ecosystems read here. | ||
| 23 | var osvEcosystems = map[string]string{ | ||
| 24 | EcoGo: "Go", | ||
| 25 | EcoNPM: "npm", | ||
| 26 | EcoCargo: "crates.io", | ||
| 27 | EcoPyPI: "PyPI", | ||
| 28 | EcoSwift: "SwiftURL", | ||
| 29 | } | ||
| 30 | |||
| 31 | // osvBatch is the most queries one querybatch request may carry. | ||
| 32 | const osvBatch = 1000 | ||
| 33 | |||
| 34 | // osvPages bounds how far a query with more matches than one response holds | ||
| 35 | // is followed. A package with that many advisories is reported in part. | ||
| 36 | const osvPages = 5 | ||
| 37 | |||
| 38 | // maxAdvisories bounds the advisory records fetched for one repository. | ||
| 39 | const maxAdvisories = 300 | ||
| 40 | |||
| 41 | type osvQuery struct { | ||
| 42 | Package struct { | ||
| 43 | Ecosystem string `json:"ecosystem"` | ||
| 44 | Name string `json:"name"` | ||
| 45 | } `json:"package"` | ||
| 46 | Version string `json:"version"` | ||
| 47 | PageToken string `json:"page_token,omitempty"` | ||
| 48 | } | ||
| 49 | |||
| 50 | // osvVuln is the part of an OSV record the issue reports. | ||
| 51 | type osvVuln struct { | ||
| 52 | ID string `json:"id"` | ||
| 53 | Summary string `json:"summary"` | ||
| 54 | Details string `json:"details"` | ||
| 55 | Aliases []string `json:"aliases"` | ||
| 56 | Withdrawn string `json:"withdrawn"` | ||
| 57 | Affected []struct { | ||
| 58 | Package struct { | ||
| 59 | Ecosystem string `json:"ecosystem"` | ||
| 60 | Name string `json:"name"` | ||
| 61 | } `json:"package"` | ||
| 62 | Ranges []struct { | ||
| 63 | Events []struct { | ||
| 64 | Fixed string `json:"fixed"` | ||
| 65 | } `json:"events"` | ||
| 66 | } `json:"ranges"` | ||
| 67 | } `json:"affected"` | ||
| 68 | DatabaseSpecific struct { | ||
| 69 | Severity string `json:"severity"` | ||
| 70 | } `json:"database_specific"` | ||
| 71 | } | ||
| 72 | |||
| 73 | // Advisories returns the published advisories matching the resolved set. | ||
| 74 | // One record often appears under several IDs (a GHSA and a PYSEC for the | ||
| 75 | // same flaw); each is reported once per dependency, under whichever ID | ||
| 76 | // sorts first. Withdrawn advisories are left out. | ||
| 77 | func (c *Client) Advisories(ctx context.Context, found []Dep) ([]store.DepAdvisory, error) { | ||
| 78 | ids, err := c.matches(ctx, found) | ||
| 79 | if err != nil { | ||
| 80 | return nil, err | ||
| 81 | } | ||
| 82 | records, err := c.records(ctx, ids) | ||
| 83 | if err != nil { | ||
| 84 | return nil, err | ||
| 85 | } | ||
| 86 | var out []store.DepAdvisory | ||
| 87 | for i, d := range found { | ||
| 88 | seen := map[string]bool{} | ||
| 89 | for _, id := range ids[i] { | ||
| 90 | v, ok := records[id] | ||
| 91 | if !ok || seen[id] || v.Withdrawn != "" { | ||
| 92 | continue | ||
| 93 | } | ||
| 94 | seen[id] = true | ||
| 95 | for _, alias := range v.Aliases { | ||
| 96 | seen[alias] = true | ||
| 97 | } | ||
| 98 | out = append(out, store.DepAdvisory{ | ||
| 99 | Ecosystem: d.Ecosystem, Name: d.Name, Version: d.Current, ID: v.ID, | ||
| 100 | Summary: summarize(v), Severity: strings.ToLower(v.DatabaseSpecific.Severity), | ||
| 101 | Fixed: fixedAfter(v, osvEcosystems[d.Ecosystem], d.Name, d.Current), | ||
| 102 | }) | ||
| 103 | } | ||
| 104 | } | ||
| 105 | return out, nil | ||
| 106 | } | ||
| 107 | |||
| 108 | // matches asks OSV which advisory IDs affect each dependency, returning | ||
| 109 | // them sorted, indexed like found. | ||
| 110 | func (c *Client) matches(ctx context.Context, found []Dep) ([][]string, error) { | ||
| 111 | ids := make([][]string, len(found)) | ||
| 112 | var pending []int | ||
| 113 | queries := make([]osvQuery, len(found)) | ||
| 114 | for i, d := range found { | ||
| 115 | queries[i].Package.Ecosystem = osvEcosystems[d.Ecosystem] | ||
| 116 | queries[i].Package.Name = d.Name | ||
| 117 | queries[i].Version = d.Current | ||
| 118 | pending = append(pending, i) | ||
| 119 | } | ||
| 120 | for page := 0; len(pending) > 0 && page < osvPages; page++ { | ||
| 121 | var next []int | ||
| 122 | for start := 0; start < len(pending); start += osvBatch { | ||
| 123 | chunk := pending[start:min(start+osvBatch, len(pending))] | ||
| 124 | batch := make([]osvQuery, len(chunk)) | ||
| 125 | for j, i := range chunk { | ||
| 126 | batch[j] = queries[i] | ||
| 127 | } | ||
| 128 | results, err := c.queryBatch(ctx, batch) | ||
| 129 | if err != nil { | ||
| 130 | return nil, err | ||
| 131 | } | ||
| 132 | for j, i := range chunk { | ||
| 133 | if j >= len(results) { | ||
| 134 | break | ||
| 135 | } | ||
| 136 | for _, v := range results[j].Vulns { | ||
| 137 | ids[i] = append(ids[i], v.ID) | ||
| 138 | } | ||
| 139 | if results[j].NextPageToken != "" { | ||
| 140 | queries[i].PageToken = results[j].NextPageToken | ||
| 141 | next = append(next, i) | ||
| 142 | } | ||
| 143 | } | ||
| 144 | } | ||
| 145 | pending = next | ||
| 146 | } | ||
| 147 | for i := range ids { | ||
| 148 | sort.Strings(ids[i]) | ||
| 149 | } | ||
| 150 | return ids, nil | ||
| 151 | } | ||
| 152 | |||
| 153 | type osvResult struct { | ||
| 154 | Vulns []struct { | ||
| 155 | ID string `json:"id"` | ||
| 156 | } `json:"vulns"` | ||
| 157 | NextPageToken string `json:"next_page_token"` | ||
| 158 | } | ||
| 159 | |||
| 160 | func (c *Client) queryBatch(ctx context.Context, batch []osvQuery) ([]osvResult, error) { | ||
| 161 | payload, err := json.Marshal(map[string]any{"queries": batch}) | ||
| 162 | if err != nil { | ||
| 163 | return nil, err | ||
| 164 | } | ||
| 165 | req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.osv()+"/v1/querybatch", bytes.NewReader(payload)) | ||
| 166 | if err != nil { | ||
| 167 | return nil, err | ||
| 168 | } | ||
| 169 | req.Header.Set("Content-Type", "application/json") | ||
| 170 | body, err := c.do(req) | ||
| 171 | if err != nil { | ||
| 172 | return nil, err | ||
| 173 | } | ||
| 174 | var doc struct { | ||
| 175 | Results []osvResult `json:"results"` | ||
| 176 | } | ||
| 177 | if err := json.Unmarshal(body, &doc); err != nil { | ||
| 178 | return nil, fmt.Errorf("osv querybatch: %w", err) | ||
| 179 | } | ||
| 180 | return doc.Results, nil | ||
| 181 | } | ||
| 182 | |||
| 183 | // records fetches each distinct advisory once. One that fails to fetch is | ||
| 184 | // dropped from this sweep, as a failed registry lookup is; all of them | ||
| 185 | // failing is an error. | ||
| 186 | func (c *Client) records(ctx context.Context, ids [][]string) (map[string]osvVuln, error) { | ||
| 187 | var distinct []string | ||
| 188 | seen := map[string]bool{} | ||
| 189 | for _, list := range ids { | ||
| 190 | for _, id := range list { | ||
| 191 | if !seen[id] && len(distinct) < maxAdvisories { | ||
| 192 | seen[id] = true | ||
| 193 | distinct = append(distinct, id) | ||
| 194 | } | ||
| 195 | } | ||
| 196 | } | ||
| 197 | var ( | ||
| 198 | mu sync.Mutex | ||
| 199 | out = map[string]osvVuln{} | ||
| 200 | failed []error | ||
| 201 | wg sync.WaitGroup | ||
| 202 | tickets = make(chan struct{}, lookups) | ||
| 203 | ) | ||
| 204 | for _, id := range distinct { | ||
| 205 | wg.Add(1) | ||
| 206 | go func(id string) { | ||
| 207 | defer wg.Done() | ||
| 208 | tickets <- struct{}{} | ||
| 209 | defer func() { <-tickets }() | ||
| 210 | v, err := c.record(ctx, id) | ||
| 211 | mu.Lock() | ||
| 212 | defer mu.Unlock() | ||
| 213 | if err != nil { | ||
| 214 | failed = append(failed, err) | ||
| 215 | return | ||
| 216 | } | ||
| 217 | out[id] = v | ||
| 218 | }(id) | ||
| 219 | } | ||
| 220 | wg.Wait() | ||
| 221 | if ctx.Err() != nil { | ||
| 222 | return nil, ctx.Err() | ||
| 223 | } | ||
| 224 | if len(failed) > 0 && len(failed) == len(distinct) { | ||
| 225 | return nil, failed[0] | ||
| 226 | } | ||
| 227 | return out, nil | ||
| 228 | } | ||
| 229 | |||
| 230 | func (c *Client) record(ctx context.Context, id string) (osvVuln, error) { | ||
| 231 | var v osvVuln | ||
| 232 | req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.osv()+"/v1/vulns/"+url.PathEscape(id), nil) | ||
| 233 | if err != nil { | ||
| 234 | return v, err | ||
| 235 | } | ||
| 236 | body, err := c.do(req) | ||
| 237 | if err != nil { | ||
| 238 | return v, err | ||
| 239 | } | ||
| 240 | if err := json.Unmarshal(body, &v); err != nil { | ||
| 241 | return v, fmt.Errorf("osv %s: %w", id, err) | ||
| 242 | } | ||
| 243 | return v, nil | ||
| 244 | } | ||
| 245 | |||
| 246 | func (c *Client) osv() string { | ||
| 247 | if c.OSV != "" { | ||
| 248 | return c.OSV | ||
| 249 | } | ||
| 250 | return osvAPI | ||
| 251 | } | ||
| 252 | |||
| 253 | func (c *Client) do(req *http.Request) ([]byte, error) { | ||
| 254 | req.Header.Set("User-Agent", "gitbay/"+c.Version+" (+https://gitbay.org)") | ||
| 255 | resp, err := c.HTTP.Do(req) | ||
| 256 | if err != nil { | ||
| 257 | return nil, err | ||
| 258 | } | ||
| 259 | defer resp.Body.Close() | ||
| 260 | if resp.StatusCode != http.StatusOK { | ||
| 261 | return nil, fmt.Errorf("%s: %s", req.URL, resp.Status) | ||
| 262 | } | ||
| 263 | return io.ReadAll(io.LimitReader(resp.Body, maxBody)) | ||
| 264 | } | ||
| 265 | |||
| 266 | // summarize is the record's summary, or the first line of its details when | ||
| 267 | // it has none, cut to fit a table cell. | ||
| 268 | func summarize(v osvVuln) string { | ||
| 269 | s := strings.TrimSpace(v.Summary) | ||
| 270 | if s == "" { | ||
| 271 | s, _, _ = strings.Cut(strings.TrimSpace(v.Details), "\n") | ||
| 272 | } | ||
| 273 | s = strings.Join(strings.Fields(s), " ") | ||
| 274 | if r := []rune(s); len(r) > 120 { | ||
| 275 | s = string(r[:119]) + "…" | ||
| 276 | } | ||
| 277 | return s | ||
| 278 | } | ||
| 279 | |||
| 280 | // fixedAfter is the lowest fixed release above current among the record's | ||
| 281 | // ranges for this package, or "" when no fix is published. A record can | ||
| 282 | // carry one range per maintained branch, so the lowest one past current is | ||
| 283 | // the nearest upgrade that clears it. | ||
| 284 | func fixedAfter(v osvVuln, ecosystem, name, current string) string { | ||
| 285 | best := "" | ||
| 286 | for _, a := range v.Affected { | ||
| 287 | if a.Package.Ecosystem != ecosystem || a.Package.Name != name { | ||
| 288 | continue | ||
| 289 | } | ||
| 290 | for _, r := range a.Ranges { | ||
| 291 | for _, e := range r.Events { | ||
| 292 | if e.Fixed == "" || !Newer(current, e.Fixed) { | ||
| 293 | continue | ||
| 294 | } | ||
| 295 | if best == "" || Newer(e.Fixed, best) { | ||
| 296 | best = e.Fixed | ||
| 297 | } | ||
| 298 | } | ||
| 299 | } | ||
| 300 | } | ||
| 301 | return best | ||
| 302 | } | ||
internal/deps/osv_test.go added +99
| @@ -0,0 +1,99 @@ | |||
| 1 | package deps | ||
| 2 | |||
| 3 | import ( | ||
| 4 | "context" | ||
| 5 | "encoding/json" | ||
| 6 | "net/http" | ||
| 7 | "net/http/httptest" | ||
| 8 | "strings" | ||
| 9 | "testing" | ||
| 10 | ) | ||
| 11 | |||
| 12 | // fakeOSV answers querybatch from matches, keyed "ecosystem name version", | ||
| 13 | // and serves records by ID. | ||
| 14 | func fakeOSV(t *testing.T, matches map[string][]string, records map[string]string) *httptest.Server { | ||
| 15 | t.Helper() | ||
| 16 | srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | ||
| 17 | if r.URL.Path == "/v1/querybatch" { | ||
| 18 | var req struct { | ||
| 19 | Queries []osvQuery `json:"queries"` | ||
| 20 | } | ||
| 21 | if err := json.NewDecoder(r.Body).Decode(&req); err != nil { | ||
| 22 | http.Error(w, err.Error(), 400) | ||
| 23 | return | ||
| 24 | } | ||
| 25 | var results []map[string]any | ||
| 26 | for _, q := range req.Queries { | ||
| 27 | var vulns []map[string]string | ||
| 28 | for _, id := range matches[q.Package.Ecosystem+" "+q.Package.Name+" "+q.Version] { | ||
| 29 | vulns = append(vulns, map[string]string{"id": id}) | ||
| 30 | } | ||
| 31 | results = append(results, map[string]any{"vulns": vulns}) | ||
| 32 | } | ||
| 33 | json.NewEncoder(w).Encode(map[string]any{"results": results}) | ||
| 34 | return | ||
| 35 | } | ||
| 36 | body, ok := records[strings.TrimPrefix(r.URL.Path, "/v1/vulns/")] | ||
| 37 | if !ok { | ||
| 38 | http.NotFound(w, r) | ||
| 39 | return | ||
| 40 | } | ||
| 41 | w.Write([]byte(body)) | ||
| 42 | })) | ||
| 43 | t.Cleanup(srv.Close) | ||
| 44 | return srv | ||
| 45 | } | ||
| 46 | |||
| 47 | func TestAdvisories(t *testing.T) { | ||
| 48 | srv := fakeOSV(t, map[string][]string{ | ||
| 49 | "PyPI flask 2.0.0": {"GHSA-aaaa", "PYSEC-1"}, | ||
| 50 | "Go golang.org/x/net v0.1.0": {"GO-2", "GO-withdrawn"}, | ||
| 51 | "SwiftURL github.com/vapor/vapor 4.0.0": {"GHSA-vapor"}, | ||
| 52 | }, map[string]string{ | ||
| 53 | "GHSA-aaaa": `{"id":"GHSA-aaaa","summary":"Session cookie\nleak","aliases":["PYSEC-1"], | ||
| 54 | "database_specific":{"severity":"HIGH"}, | ||
| 55 | "affected":[{"package":{"ecosystem":"PyPI","name":"flask"}, | ||
| 56 | "ranges":[{"events":[{"introduced":"0"},{"fixed":"1.9.0"}]},{"events":[{"introduced":"2.0.0"},{"fixed":"2.3.2"}]},{"events":[{"introduced":"2.0.0"},{"fixed":"2.2.5"}]}]}]}`, | ||
| 57 | "PYSEC-1": `{"id":"PYSEC-1","summary":"duplicate","aliases":["GHSA-aaaa"]}`, | ||
| 58 | "GO-2": `{"id":"GO-2","details":"First line.\nSecond line.","affected":[{"package":{"ecosystem":"Go","name":"golang.org/x/net"},"ranges":[{"events":[{"fixed":"0.7.0"}]}]}]}`, | ||
| 59 | "GO-withdrawn": `{"id":"GO-withdrawn","withdrawn":"2026-01-01T00:00:00Z"}`, | ||
| 60 | "GHSA-vapor": `{"id":"GHSA-vapor","summary":"no fix"}`, | ||
| 61 | }) | ||
| 62 | c := NewClient("test") | ||
| 63 | c.OSV = srv.URL | ||
| 64 | got, err := c.Advisories(context.Background(), []Dep{ | ||
| 65 | {Ecosystem: EcoGo, Name: "golang.org/x/net", Current: "v0.1.0"}, | ||
| 66 | {Ecosystem: EcoPyPI, Name: "flask", Current: "2.0.0"}, | ||
| 67 | {Ecosystem: EcoPyPI, Name: "clean", Current: "1.0.0"}, | ||
| 68 | {Ecosystem: EcoSwift, Name: "github.com/vapor/vapor", Current: "4.0.0"}, | ||
| 69 | }) | ||
| 70 | if err != nil { | ||
| 71 | t.Fatal(err) | ||
| 72 | } | ||
| 73 | if len(got) != 3 { | ||
| 74 | t.Fatalf("advisories = %+v, want GO-2, GHSA-aaaa once, GHSA-vapor", got) | ||
| 75 | } | ||
| 76 | if a := got[0]; a.ID != "GO-2" || a.Summary != "First line." || a.Fixed != "0.7.0" || a.Severity != "" { | ||
| 77 | t.Errorf("go advisory = %+v", a) | ||
| 78 | } | ||
| 79 | // The alias is folded in, the summary's whitespace collapsed, and the | ||
| 80 | // nearest fix past 2.0.0 chosen over the branch fixes either side. | ||
| 81 | if a := got[1]; a.ID != "GHSA-aaaa" || a.Summary != "Session cookie leak" || a.Severity != "high" || a.Fixed != "2.2.5" { | ||
| 82 | t.Errorf("pypi advisory = %+v", a) | ||
| 83 | } | ||
| 84 | if a := got[2]; a.ID != "GHSA-vapor" || a.Fixed != "" { | ||
| 85 | t.Errorf("swift advisory = %+v", a) | ||
| 86 | } | ||
| 87 | } | ||
| 88 | |||
| 89 | func TestAdvisoriesFailWhenOSVIsDown(t *testing.T) { | ||
| 90 | srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | ||
| 91 | http.Error(w, "down", http.StatusServiceUnavailable) | ||
| 92 | })) | ||
| 93 | t.Cleanup(srv.Close) | ||
| 94 | c := NewClient("test") | ||
| 95 | c.OSV = srv.URL | ||
| 96 | if _, err := c.Advisories(context.Background(), []Dep{{Ecosystem: EcoGo, Name: "x", Current: "v1.0.0"}}); err == nil { | ||
| 97 | t.Fatal("an unreachable OSV read as no advisories") | ||
| 98 | } | ||
| 99 | } | ||
internal/deps/python.go +5 −2
| @@ -10,7 +10,10 @@ import ( | |||
| 10 | // that name one release are reported: a bare `requests` or a `>=2,<3` range | 10 | // that name one release are reported: a bare `requests` or a `>=2,<3` range |
| 11 | // says the project accepts whatever is current, so there is nothing to tell | 11 | // says the project accepts whatever is current, so there is nothing to tell |
| 12 | // its maintainer. | 12 | // its maintainer. |
| 13 | func parsePython(read ReadFile) []Dep { | 13 | func parsePython(read ReadFile) []Dep { return pythonDeps(read, pin) } |
| 14 | |||
| 15 | // pythonDeps reads both files, reducing each requirement with pinned. | ||
| 16 | func pythonDeps(read ReadFile, pinned func(string) string) []Dep { | ||
| 14 | seen := map[string]bool{} | 17 | seen := map[string]bool{} |
| 15 | var out []Dep | 18 | var out []Dep |
| 16 | add := func(name, version string) { | 19 | add := func(name, version string) { |
| @@ -18,7 +21,7 @@ func parsePython(read ReadFile) []Dep { | |||
| 18 | if name == "" || name == "python" || seen[name] { | 21 | if name == "" || name == "python" || seen[name] { |
| 19 | return | 22 | return |
| 20 | } | 23 | } |
| 21 | if v := pin(version); v != "" { | 24 | if v := pinned(version); v != "" { |
| 22 | seen[name] = true | 25 | seen[name] = true |
| 23 | out = append(out, Dep{Ecosystem: EcoPyPI, Name: name, Current: v}) | 26 | out = append(out, Dep{Ecosystem: EcoPyPI, Name: name, Current: v}) |
| 24 | } | 27 | } |
internal/deps/registry.go +1
| @@ -34,6 +34,7 @@ var safeName = regexp.MustCompile(`^@?[A-Za-z0-9][A-Za-z0-9._/@+-]*$`) | |||
| 34 | type Client struct { | 34 | type Client struct { |
| 35 | HTTP *http.Client | 35 | HTTP *http.Client |
| 36 | Hosts map[string]string // overridden in tests | 36 | Hosts map[string]string // overridden in tests |
| 37 | OSV string // osvAPI unless overridden in tests | ||
| 37 | Version string // reported in User-Agent | 38 | Version string // reported in User-Agent |
| 38 | } | 39 | } |
| 39 | 40 | ||
internal/deps/report.go +71 −8
| @@ -12,16 +12,20 @@ import ( | |||
| 12 | // across sweeps, in listings, and to the maintainer. | 12 | // across sweeps, in listings, and to the maintainer. |
| 13 | const IssueTitle = "Dependency updates available" | 13 | const IssueTitle = "Dependency updates available" |
| 14 | 14 | ||
| 15 | // AdvisoryTitle is the advisories issue's, fixed for the same reason. | ||
| 16 | const AdvisoryTitle = "Known vulnerabilities in dependencies" | ||
| 17 | |||
| 15 | // ecosystemNames are how the four appear in the issue body. | 18 | // ecosystemNames are how the four appear in the issue body. |
| 16 | var ecosystemNames = map[string]string{ | 19 | var ecosystemNames = map[string]string{ |
| 17 | EcoGo: "Go", | 20 | EcoGo: "Go", |
| 18 | EcoNPM: "npm", | 21 | EcoNPM: "npm", |
| 19 | EcoCargo: "Cargo", | 22 | EcoCargo: "Cargo", |
| 20 | EcoPyPI: "PyPI", | 23 | EcoPyPI: "PyPI", |
| 24 | EcoSwift: "Swift", | ||
| 21 | } | 25 | } |
| 22 | 26 | ||
| 23 | // order is the sequence sections appear in. | 27 | // order is the sequence sections appear in. |
| 24 | var order = []string{EcoGo, EcoNPM, EcoCargo, EcoPyPI} | 28 | var order = []string{EcoGo, EcoNPM, EcoCargo, EcoPyPI, EcoSwift} |
| 25 | 29 | ||
| 26 | // Body renders the issue: one table per ecosystem, sorted, so a diff | 30 | // Body renders the issue: one table per ecosystem, sorted, so a diff |
| 27 | // between sweeps reads as a diff of what is behind. | 31 | // between sweeps reads as a diff of what is behind. |
| @@ -40,21 +44,56 @@ func Body(branch string, reports []store.DepReport) string { | |||
| 40 | } | 44 | } |
| 41 | sort.Slice(rows, func(i, j int) bool { return rows[i].Name < rows[j].Name }) | 45 | sort.Slice(rows, func(i, j int) bool { return rows[i].Name < rows[j].Name }) |
| 42 | fmt.Fprintf(&b, "\n### %s\n\n", ecosystemNames[eco]) | 46 | fmt.Fprintf(&b, "\n### %s\n\n", ecosystemNames[eco]) |
| 43 | cells := [][3]string{{"Package", "Current", "Latest"}} | 47 | cells := [][]string{{"Package", "Current", "Latest"}} |
| 44 | for _, r := range rows { | 48 | for _, r := range rows { |
| 45 | cells = append(cells, [3]string{"`" + r.Name + "`", r.Current, r.Latest}) | 49 | cells = append(cells, []string{"`" + r.Name + "`", r.Current, r.Latest}) |
| 46 | } | 50 | } |
| 47 | b.WriteString(table(cells)) | 51 | b.WriteString(table(cells)) |
| 48 | } | 52 | } |
| 49 | return b.String() | 53 | return b.String() |
| 50 | } | 54 | } |
| 51 | 55 | ||
| 56 | // AdvisoryBody renders the advisories issue: a table per ecosystem, then | ||
| 57 | // each advisory's summary and link, which would make the table too wide to | ||
| 58 | // read as plain text. | ||
| 59 | func AdvisoryBody(branch string, matched []store.DepAdvisory) string { | ||
| 60 | var b strings.Builder | ||
| 61 | fmt.Fprintf(&b, "Dependencies resolved on `%s` match published advisories. "+ | ||
| 62 | "This issue is kept up to date as that changes, and closed once none match.\n", branch) | ||
| 63 | byEco := map[string][]store.DepAdvisory{} | ||
| 64 | for _, a := range matched { | ||
| 65 | byEco[a.Ecosystem] = append(byEco[a.Ecosystem], a) | ||
| 66 | } | ||
| 67 | for _, eco := range order { | ||
| 68 | rows := byEco[eco] | ||
| 69 | if len(rows) == 0 { | ||
| 70 | continue | ||
| 71 | } | ||
| 72 | fmt.Fprintf(&b, "\n### %s\n\n", ecosystemNames[eco]) | ||
| 73 | cells := [][]string{{"Package", "Version", "Advisory", "Severity", "Fixed in"}} | ||
| 74 | for _, a := range rows { | ||
| 75 | cells = append(cells, []string{"`" + a.Name + "`", a.Version, a.ID, a.Severity, a.Fixed}) | ||
| 76 | } | ||
| 77 | b.WriteString(table(cells)) | ||
| 78 | } | ||
| 79 | b.WriteString("\n### Advisories\n\n") | ||
| 80 | seen := map[string]bool{} | ||
| 81 | for _, a := range matched { | ||
| 82 | if seen[a.ID] { | ||
| 83 | continue | ||
| 84 | } | ||
| 85 | seen[a.ID] = true | ||
| 86 | fmt.Fprintf(&b, "- %s: %s https://osv.dev/vulnerability/%s\n", a.ID, a.Summary, a.ID) | ||
| 87 | } | ||
| 88 | return b.String() | ||
| 89 | } | ||
| 90 | |||
| 52 | // table pads every cell to its column, because the body is read twice: as | 91 | // table pads every cell to its column, because the body is read twice: as |
| 53 | // a rendered table on the web, where the padding is ignored, and as the | 92 | // a rendered table on the web, where the padding is ignored, and as the |
| 54 | // plain text of the notification mail, where it is the only thing keeping | 93 | // plain text of the notification mail, where it is the only thing keeping |
| 55 | // the columns readable. Row 0 is the header. | 94 | // the columns readable. Row 0 is the header. |
| 56 | func table(cells [][3]string) string { | 95 | func table(cells [][]string) string { |
| 57 | var w [3]int | 96 | w := make([]int, len(cells[0])) |
| 58 | for _, c := range cells { | 97 | for _, c := range cells { |
| 59 | for i := range w { | 98 | for i := range w { |
| 60 | if n := len(c[i]); n > w[i] { | 99 | if n := len(c[i]); n > w[i] { |
| @@ -63,11 +102,19 @@ func table(cells [][3]string) string { | |||
| 63 | } | 102 | } |
| 64 | } | 103 | } |
| 65 | var b strings.Builder | 104 | var b strings.Builder |
| 66 | row := func(c [3]string) { | 105 | row := func(c []string) { |
| 67 | fmt.Fprintf(&b, "| %-*s | %-*s | %-*s |\n", w[0], c[0], w[1], c[1], w[2], c[2]) | 106 | b.WriteString("|") |
| 107 | for i := range w { | ||
| 108 | fmt.Fprintf(&b, " %-*s |", w[i], c[i]) | ||
| 109 | } | ||
| 110 | b.WriteString("\n") | ||
| 68 | } | 111 | } |
| 69 | row(cells[0]) | 112 | row(cells[0]) |
| 70 | row([3]string{strings.Repeat("-", w[0]), strings.Repeat("-", w[1]), strings.Repeat("-", w[2])}) | 113 | rule := make([]string, len(w)) |
| 114 | for i := range w { | ||
| 115 | rule[i] = strings.Repeat("-", w[i]) | ||
| 116 | } | ||
| 117 | row(rule) | ||
| 71 | for _, c := range cells[1:] { | 118 | for _, c := range cells[1:] { |
| 72 | row(c) | 119 | row(c) |
| 73 | } | 120 | } |
| @@ -88,3 +135,19 @@ func same(a, b []store.DepReport) bool { | |||
| 88 | } | 135 | } |
| 89 | return true | 136 | return true |
| 90 | } | 137 | } |
| 138 | |||
| 139 | // sameAdvisories reports whether two matching sets name the same | ||
| 140 | // advisories against the same versions. A summary or severity edited | ||
| 141 | // upstream does not count as a change worth a notification. | ||
| 142 | func sameAdvisories(a, b []store.DepAdvisory) bool { | ||
| 143 | if len(a) != len(b) { | ||
| 144 | return false | ||
| 145 | } | ||
| 146 | for i := range a { | ||
| 147 | if a[i].Ecosystem != b[i].Ecosystem || a[i].Name != b[i].Name || | ||
| 148 | a[i].Version != b[i].Version || a[i].ID != b[i].ID || a[i].Fixed != b[i].Fixed { | ||
| 149 | return false | ||
| 150 | } | ||
| 151 | } | ||
| 152 | return true | ||
| 153 | } | ||
internal/deps/report_test.go +16
| @@ -41,3 +41,19 @@ func TestBodyAlignsColumns(t *testing.T) { | |||
| 41 | t.Errorf("row not padded to its column:\n%s", body) | 41 | t.Errorf("row not padded to its column:\n%s", body) |
| 42 | } | 42 | } |
| 43 | } | 43 | } |
| 44 | |||
| 45 | func TestAdvisoryBody(t *testing.T) { | ||
| 46 | body := AdvisoryBody("main", []store.DepAdvisory{ | ||
| 47 | {Ecosystem: EcoGo, Name: "golang.org/x/net", Version: "v0.1.0", ID: "GO-2", Summary: "HTTP/2 reset", Severity: "", Fixed: "0.7.0"}, | ||
| 48 | {Ecosystem: EcoPyPI, Name: "flask", Version: "2.0.0", ID: "GHSA-aaaa", Summary: "cookie leak", Severity: "high", Fixed: "2.2.5"}, | ||
| 49 | }) | ||
| 50 | for _, want := range []string{ | ||
| 51 | "| `golang.org/x/net` | v0.1.0 | GO-2 | | 0.7.0 |", | ||
| 52 | "- GHSA-aaaa: cookie leak https://osv.dev/vulnerability/GHSA-aaaa", | ||
| 53 | "### PyPI", | ||
| 54 | } { | ||
| 55 | if !strings.Contains(body, want) { | ||
| 56 | t.Errorf("body missing %q:\n%s", want, body) | ||
| 57 | } | ||
| 58 | } | ||
| 59 | } | ||
internal/deps/resolved.go added +300
| @@ -0,0 +1,300 @@ | |||
| 1 | package deps | ||
| 2 | |||
| 3 | import ( | ||
| 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. | ||
| 14 | const 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. | ||
| 18 | const MaxResolved = 3000 | ||
| 19 | |||
| 20 | // swiftResolvedDirs are where Xcode keeps Package.resolved inside a project | ||
| 21 | // or workspace bundle at the repository root. | ||
| 22 | var 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. | ||
| 33 | func 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 | |||
| 56 | func 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. | ||
| 70 | func 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. | ||
| 82 | func 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. | ||
| 129 | func 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. | ||
| 183 | func 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. | ||
| 217 | func 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. | ||
| 233 | func 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. | ||
| 283 | func 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 | } | ||
internal/deps/resolved_test.go added +112
| @@ -0,0 +1,112 @@ | |||
| 1 | package deps | ||
| 2 | |||
| 3 | import "testing" | ||
| 4 | |||
| 5 | func TestResolvedReadsLockfiles(t *testing.T) { | ||
| 6 | got := found(t, Resolved(tree(map[string]string{ | ||
| 7 | "go.mod": `module x | ||
| 8 | |||
| 9 | require ( | ||
| 10 | github.com/a/direct v1.0.0 | ||
| 11 | github.com/a/indirect v0.2.0 // indirect | ||
| 12 | github.com/a/replaced v1.0.0 | ||
| 13 | ) | ||
| 14 | |||
| 15 | replace github.com/a/replaced => ../replaced | ||
| 16 | `, | ||
| 17 | "package-lock.json": `{"packages":{ | ||
| 18 | "": {"name":"app"}, | ||
| 19 | "node_modules/left-pad": {"version":"1.3.0"}, | ||
| 20 | "node_modules/a/node_modules/nested": {"version":"2.0.0"}, | ||
| 21 | "node_modules/linked": {"link": true} | ||
| 22 | }}`, | ||
| 23 | "package.json": `{"dependencies":{"ignored-when-locked":"1.0.0"}}`, | ||
| 24 | "Cargo.lock": ` | ||
| 25 | [[package]] | ||
| 26 | name = "serde" | ||
| 27 | version = "1.0.197" | ||
| 28 | source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 29 | |||
| 30 | [[package]] | ||
| 31 | name = "member" | ||
| 32 | version = "0.1.0" | ||
| 33 | |||
| 34 | [[package]] | ||
| 35 | name = "from-git" | ||
| 36 | version = "0.3.0" | ||
| 37 | source = "git+https://example.com/x.git#abc" | ||
| 38 | `, | ||
| 39 | "uv.lock": ` | ||
| 40 | [[package]] | ||
| 41 | name = "Requests" | ||
| 42 | version = "2.31.0" | ||
| 43 | source = { registry = "https://pypi.org/simple" } | ||
| 44 | |||
| 45 | [[package]] | ||
| 46 | name = "app" | ||
| 47 | version = "0.1.0" | ||
| 48 | source = { editable = "." } | ||
| 49 | `, | ||
| 50 | "Package.resolved": `{"pins":[ | ||
| 51 | {"identity":"vapor","location":"https://github.com/vapor/vapor.git","state":{"version":"4.0.0"}}, | ||
| 52 | {"identity":"branchy","location":"https://github.com/x/branchy","state":{"branch":"main","revision":"abc"}} | ||
| 53 | ],"version":2}`, | ||
| 54 | "App.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved": `{"object":{"pins":[ | ||
| 55 | {"package":"Sparkle","repositoryURL":"git@github.com:sparkle-project/Sparkle.git","state":{"version":"2.6.0"}} | ||
| 56 | ]},"version":1}`, | ||
| 57 | }), []string{"go.mod", "App.xcodeproj", "Sources"})) | ||
| 58 | |||
| 59 | want := map[string]string{ | ||
| 60 | "go:github.com/a/direct": "v1.0.0", | ||
| 61 | "go:github.com/a/indirect": "v0.2.0", | ||
| 62 | "npm:left-pad": "1.3.0", | ||
| 63 | "npm:nested": "2.0.0", | ||
| 64 | "cargo:serde": "1.0.197", | ||
| 65 | "pypi:requests": "2.31.0", | ||
| 66 | "swift:github.com/vapor/vapor": "4.0.0", | ||
| 67 | "swift:github.com/sparkle-project/Sparkle": "2.6.0", | ||
| 68 | } | ||
| 69 | for k, v := range want { | ||
| 70 | if got[k] != v { | ||
| 71 | t.Errorf("%s = %q, want %q", k, got[k], v) | ||
| 72 | } | ||
| 73 | } | ||
| 74 | if len(got) != len(want) { | ||
| 75 | t.Errorf("resolved %v, want exactly %v", got, want) | ||
| 76 | } | ||
| 77 | } | ||
| 78 | |||
| 79 | // Without a lockfile only exact pins are sent: a range's floor is rarely | ||
| 80 | // what is installed, and would match advisories the build does not have. | ||
| 81 | func TestResolvedWithoutLockfilesKeepsExactPins(t *testing.T) { | ||
| 82 | got := found(t, Resolved(tree(map[string]string{ | ||
| 83 | "package.json": `{"dependencies":{"exact":"1.2.3","caret":"^1.2.3","tilde":"~1.2.3"}}`, | ||
| 84 | "Cargo.toml": "[dependencies]\npinned = \"=1.0.0\"\ncaret = \"1.0\"\n", | ||
| 85 | "requirements.txt": "flask==3.0.0\nrequests>=2.31\nbare\n", | ||
| 86 | }), nil)) | ||
| 87 | want := map[string]string{"npm:exact": "1.2.3", "cargo:pinned": "1.0.0", "pypi:flask": "3.0.0"} | ||
| 88 | for k, v := range want { | ||
| 89 | if got[k] != v { | ||
| 90 | t.Errorf("%s = %q, want %q", k, got[k], v) | ||
| 91 | } | ||
| 92 | } | ||
| 93 | if len(got) != len(want) { | ||
| 94 | t.Errorf("resolved %v, want exactly %v", got, want) | ||
| 95 | } | ||
| 96 | } | ||
| 97 | |||
| 98 | func TestSwiftURLName(t *testing.T) { | ||
| 99 | for in, want := range map[string]string{ | ||
| 100 | "https://github.com/vapor/vapor.git": "github.com/vapor/vapor", | ||
| 101 | "https://github.com/vapor/vapor": "github.com/vapor/vapor", | ||
| 102 | "git@github.com:vapor/vapor.git": "github.com/vapor/vapor", | ||
| 103 | "ssh://git@gitbay.org/krz/org-swift": "gitbay.org/krz/org-swift", | ||
| 104 | "https://user@example.com/a/b.git/": "example.com/a/b", | ||
| 105 | "/Users/me/local-package": "", | ||
| 106 | "../sibling": "", | ||
| 107 | } { | ||
| 108 | if got := swiftURLName(in); got != want { | ||
| 109 | t.Errorf("swiftURLName(%q) = %q, want %q", in, got, want) | ||
| 110 | } | ||
| 111 | } | ||
| 112 | } | ||
internal/deps/worker.go +95 −22
| @@ -23,7 +23,8 @@ const manifestLimit = 1 << 20 | |||
| 23 | const lookups = 4 | 23 | const lookups = 4 |
| 24 | 24 | ||
| 25 | // Worker sweeps repositories that have opted in, comparing their manifests | 25 | // Worker sweeps repositories that have opted in, comparing their manifests |
| 26 | // against the registries and maintaining one issue per repository. | 26 | // against the registries and OSV and maintaining up to two issues per |
| 27 | // repository: one for updates, one for advisories. | ||
| 27 | type Worker struct { | 28 | type Worker struct { |
| 28 | St *store.Store | 29 | St *store.Store |
| 29 | Cfg config.Config | 30 | Cfg config.Config |
| @@ -83,17 +84,32 @@ func (w *Worker) Sweep(ctx context.Context) { | |||
| 83 | } | 84 | } |
| 84 | } | 85 | } |
| 85 | 86 | ||
| 86 | // check compares one repository against the registries and reconciles its | 87 | // check compares one repository against the registries and OSV, and |
| 87 | // issue with the result. | 88 | // reconciles its two issues with the result. A failure on one side leaves |
| 89 | // the other reconciled, and leaves its own issue as it was rather than | ||
| 90 | // closing it on an answer that never came. | ||
| 88 | func (w *Worker) check(ctx context.Context, repo store.Repo) error { | 91 | func (w *Worker) check(ctx context.Context, repo store.Repo) error { |
| 89 | dir := w.RepoDir(repo.OwnerName, repo.Name) | 92 | dir := w.RepoDir(repo.OwnerName, repo.Name) |
| 90 | sha, err := gitutil.ResolveRef(dir, "refs/heads/"+repo.DefaultBranch) | 93 | sha, err := gitutil.ResolveRef(dir, "refs/heads/"+repo.DefaultBranch) |
| 91 | if err != nil { | 94 | if err != nil { |
| 92 | return nil // empty repo, or no default branch yet | 95 | return nil // empty repo, or no default branch yet |
| 93 | } | 96 | } |
| 94 | found := Scan(func(path string) ([]byte, error) { | 97 | read := func(path string) ([]byte, error) { |
| 95 | return gitutil.ReadBlob(dir, sha, path, manifestLimit) | 98 | return gitutil.ReadBlob(dir, sha, path, manifestLimit) |
| 96 | }) | 99 | } |
| 100 | var root []string | ||
| 101 | if entries, err := gitutil.ListTree(dir, sha, ""); err == nil { | ||
| 102 | for _, e := range entries { | ||
| 103 | root = append(root, e.Name) | ||
| 104 | } | ||
| 105 | } | ||
| 106 | return errors.Join( | ||
| 107 | w.checkUpdates(ctx, repo, Scan(read)), | ||
| 108 | w.checkAdvisories(ctx, repo, Resolved(read, root)), | ||
| 109 | ) | ||
| 110 | } | ||
| 111 | |||
| 112 | func (w *Worker) checkUpdates(ctx context.Context, repo store.Repo, found []Dep) error { | ||
| 97 | if len(found) == 0 { | 113 | if len(found) == 0 { |
| 98 | return w.reconcile(repo, nil) | 114 | return w.reconcile(repo, nil) |
| 99 | } | 115 | } |
| @@ -104,6 +120,17 @@ func (w *Worker) check(ctx context.Context, repo store.Repo) error { | |||
| 104 | return w.reconcile(repo, behind) | 120 | return w.reconcile(repo, behind) |
| 105 | } | 121 | } |
| 106 | 122 | ||
| 123 | func (w *Worker) checkAdvisories(ctx context.Context, repo store.Repo, resolved []Dep) error { | ||
| 124 | if len(resolved) == 0 { | ||
| 125 | return w.reconcileAdvisories(repo, nil) | ||
| 126 | } | ||
| 127 | matched, err := w.Client.Advisories(ctx, resolved) | ||
| 128 | if err != nil { | ||
| 129 | return fmt.Errorf("advisories: %w", err) | ||
| 130 | } | ||
| 131 | return w.reconcileAdvisories(repo, matched) | ||
| 132 | } | ||
| 133 | |||
| 107 | // behind queries the registries and keeps the dependencies whose latest | 134 | // behind queries the registries and keeps the dependencies whose latest |
| 108 | // release is greater than what the manifest declares. A lookup that fails | 135 | // release is greater than what the manifest declares. A lookup that fails |
| 109 | // is dropped rather than failing the sweep: one unreachable package should | 136 | // is dropped rather than failing the sweep: one unreachable package should |
| @@ -152,9 +179,7 @@ func (w *Worker) behind(ctx context.Context, found []Dep) ([]store.DepReport, er | |||
| 152 | return out, nil | 179 | return out, nil |
| 153 | } | 180 | } |
| 154 | 181 | ||
| 155 | // reconcile brings the repository's issue in line with what is behind: | 182 | // reconcile brings the updates issue in line with what is behind. |
| 156 | // opened when something first falls behind, rewritten when the set changes, | ||
| 157 | // closed when nothing is behind any more. | ||
| 158 | func (w *Worker) reconcile(repo store.Repo, behind []store.DepReport) error { | 183 | func (w *Worker) reconcile(repo store.Repo, behind []store.DepReport) error { |
| 159 | check, err := w.St.DepCheckFor(repo.ID) | 184 | check, err := w.St.DepCheckFor(repo.ID) |
| 160 | if err != nil { | 185 | if err != nil { |
| @@ -164,32 +189,80 @@ func (w *Worker) reconcile(repo store.Repo, behind []store.DepReport) error { | |||
| 164 | if err != nil { | 189 | if err != nil { |
| 165 | return err | 190 | return err |
| 166 | } | 191 | } |
| 167 | issue, hasIssue := w.openIssue(repo, check.IssueNumber) | 192 | return w.maintain(repo, tracked{ |
| 168 | if len(behind) == 0 { | 193 | title: IssueTitle, |
| 194 | number: check.IssueNumber, | ||
| 195 | record: func(n int64) error { return w.St.SetDepIssue(repo.ID, n) }, | ||
| 196 | empty: len(behind) == 0, | ||
| 197 | changed: !same(previous, behind), | ||
| 198 | save: func() error { return w.St.ReplaceDepReports(repo.ID, behind) }, | ||
| 199 | body: func() string { return Body(repo.DefaultBranch, behind) }, | ||
| 200 | }) | ||
| 201 | } | ||
| 202 | |||
| 203 | // reconcileAdvisories brings the advisories issue in line with what | ||
| 204 | // matches. | ||
| 205 | func (w *Worker) reconcileAdvisories(repo store.Repo, matched []store.DepAdvisory) error { | ||
| 206 | check, err := w.St.DepCheckFor(repo.ID) | ||
| 207 | if err != nil { | ||
| 208 | return err | ||
| 209 | } | ||
| 210 | previous, err := w.St.ReportedAdvisories(repo.ID) | ||
| 211 | if err != nil { | ||
| 212 | return err | ||
| 213 | } | ||
| 214 | return w.maintain(repo, tracked{ | ||
| 215 | title: AdvisoryTitle, | ||
| 216 | number: check.AdvisoryIssueNumber, | ||
| 217 | record: func(n int64) error { return w.St.SetDepAdvisoryIssue(repo.ID, n) }, | ||
| 218 | empty: len(matched) == 0, | ||
| 219 | changed: !sameAdvisories(previous, matched), | ||
| 220 | save: func() error { return w.St.ReplaceDepAdvisories(repo.ID, matched) }, | ||
| 221 | body: func() string { return AdvisoryBody(repo.DefaultBranch, matched) }, | ||
| 222 | }) | ||
| 223 | } | ||
| 224 | |||
| 225 | // tracked is one issue the worker maintains for a repository and the set | ||
| 226 | // it reports. | ||
| 227 | type tracked struct { | ||
| 228 | title string | ||
| 229 | number int64 // the issue last opened, 0 for none | ||
| 230 | record func(number int64) error | ||
| 231 | empty bool // nothing to report | ||
| 232 | changed bool // the set differs from the last report | ||
| 233 | save func() error | ||
| 234 | body func() string | ||
| 235 | } | ||
| 236 | |||
| 237 | // maintain opens the issue when something is first reported, rewrites it | ||
| 238 | // when the set changes, and closes it when nothing is left. | ||
| 239 | func (w *Worker) maintain(repo store.Repo, t tracked) error { | ||
| 240 | issue, hasIssue := w.openIssue(repo, t.number) | ||
| 241 | if t.empty { | ||
| 169 | if hasIssue { | 242 | if hasIssue { |
| 170 | w.St.SetIssueState(issue.ID, "closed") | 243 | w.St.SetIssueState(issue.ID, "closed") |
| 171 | w.St.SetDepIssue(repo.ID, 0) | 244 | t.record(0) |
| 172 | } | 245 | } |
| 173 | if len(previous) > 0 { | 246 | if t.changed { |
| 174 | return w.St.ReplaceDepReports(repo.ID, nil) | 247 | return t.save() |
| 175 | } | 248 | } |
| 176 | return nil | 249 | return nil |
| 177 | } | 250 | } |
| 178 | // Nothing changed since the last report: leave it be, whether the issue | 251 | // Nothing changed since the last report: leave it be, whether the issue |
| 179 | // is still open or the maintainer has closed it. Reopening on an | 252 | // is still open or the maintainer has closed it. Reopening on an |
| 180 | // unchanged set would make closing the issue pointless. | 253 | // unchanged set would make closing the issue pointless. |
| 181 | if same(previous, behind) { | 254 | if !t.changed { |
| 182 | return nil | 255 | return nil |
| 183 | } | 256 | } |
| 184 | if err := w.St.ReplaceDepReports(repo.ID, behind); err != nil { | 257 | if err := t.save(); err != nil { |
| 185 | return err | 258 | return err |
| 186 | } | 259 | } |
| 187 | body := Body(repo.DefaultBranch, behind) | 260 | body := t.body() |
| 188 | if hasIssue { | 261 | if hasIssue { |
| 189 | if err := w.St.UpdateIssueText(issue.ID, nil, &body, nil); err != nil { | 262 | if err := w.St.UpdateIssueText(issue.ID, nil, &body, nil); err != nil { |
| 190 | return err | 263 | return err |
| 191 | } | 264 | } |
| 192 | w.notify(repo, issue.Number, fmt.Sprintf("updated issue #%d", issue.Number), body) | 265 | w.notify(repo, t.title, issue.Number, fmt.Sprintf("updated issue #%d", issue.Number), body) |
| 193 | return nil | 266 | return nil |
| 194 | } | 267 | } |
| 195 | author, err := w.St.UserByUsername(store.BotUsername) | 268 | author, err := w.St.UserByUsername(store.BotUsername) |
| @@ -200,15 +273,15 @@ func (w *Worker) reconcile(repo store.Repo, behind []store.DepReport) error { | |||
| 200 | return fmt.Errorf("no %s account to author the issue (the name was taken when this instance upgraded): %w", | 273 | return fmt.Errorf("no %s account to author the issue (the name was taken when this instance upgraded): %w", |
| 201 | store.BotUsername, err) | 274 | store.BotUsername, err) |
| 202 | } | 275 | } |
| 203 | number, err := w.St.CreateIssue(repo.ID, author.ID, IssueTitle, body, "md") | 276 | number, err := w.St.CreateIssue(repo.ID, author.ID, t.title, body, "md") |
| 204 | if err != nil { | 277 | if err != nil { |
| 205 | return err | 278 | return err |
| 206 | } | 279 | } |
| 207 | if err := w.St.SetDepIssue(repo.ID, number); err != nil { | 280 | if err := t.record(number); err != nil { |
| 208 | return err | 281 | return err |
| 209 | } | 282 | } |
| 210 | w.St.RecordEvent(repo.ID, author.ID, "issue.created", fmt.Sprintf(`{"number":%d}`, number)) | 283 | w.St.RecordEvent(repo.ID, author.ID, "issue.created", fmt.Sprintf(`{"number":%d}`, number)) |
| 211 | w.notify(repo, number, fmt.Sprintf("opened issue #%d", number), body) | 284 | w.notify(repo, t.title, number, fmt.Sprintf("opened issue #%d", number), body) |
| 212 | return nil | 285 | return nil |
| 213 | } | 286 | } |
| 214 | 287 | ||
| @@ -229,7 +302,7 @@ func (w *Worker) openIssue(repo store.Repo, number int64) (store.Issue, bool) { | |||
| 229 | // notify files an inbox row for the repo's owners and watchers and mails | 302 | // notify files an inbox row for the repo's owners and watchers and mails |
| 230 | // them, the same targets and shape as an issue opened over SSH. | 303 | // them, the same targets and shape as an issue opened over SSH. |
| 231 | // Best-effort, like every other notification. | 304 | // Best-effort, like every other notification. |
| 232 | func (w *Worker) notify(repo store.Repo, number int64, action, body string) { | 305 | func (w *Worker) notify(repo store.Repo, title string, number int64, action, body string) { |
| 233 | targets, err := w.St.RepoNotifyTargets(repo) | 306 | targets, err := w.St.RepoNotifyTargets(repo) |
| 234 | if err != nil { | 307 | if err != nil { |
| 235 | return | 308 | return |
| @@ -242,7 +315,7 @@ func (w *Worker) notify(repo store.Repo, number int64, action, body string) { | |||
| 242 | if err != nil { | 315 | if err != nil { |
| 243 | return | 316 | return |
| 244 | } | 317 | } |
| 245 | subject := fmt.Sprintf("[%s] #%d: %s", repo.Path(), number, IssueTitle) | 318 | subject := fmt.Sprintf("[%s] #%d: %s", repo.Path(), number, title) |
| 246 | text := fmt.Sprintf("%s %s\n\n%s\n%s/%s/issues/%d\n", store.BotUsername, action, body, | 319 | text := fmt.Sprintf("%s %s\n\n%s\n%s/%s/issues/%d\n", store.BotUsername, action, body, |
| 247 | strings.TrimSuffix(w.Cfg.Server.SiteURL, "/"), repo.Path(), number) | 320 | strings.TrimSuffix(w.Cfg.Server.SiteURL, "/"), repo.Path(), number) |
| 248 | path := fmt.Sprintf("%s/issues/%d", repo.Path(), number) | 321 | path := fmt.Sprintf("%s/issues/%d", repo.Path(), number) |
internal/deps/worker_test.go +48
| @@ -223,3 +223,51 @@ func TestReconcileLeavesClosedIssueClosedOnUnchangedSet(t *testing.T) { | |||
| 223 | t.Error("the closed issue came back") | 223 | t.Error("the closed issue came back") |
| 224 | } | 224 | } |
| 225 | } | 225 | } |
| 226 | |||
| 227 | func TestReconcileAdvisoriesKeepsItsOwnIssue(t *testing.T) { | ||
| 228 | w, repo := testWorker(t) | ||
| 229 | if err := w.reconcile(repo, reports("github.com/a/b", "v1.0.0", "v1.1.0")); err != nil { | ||
| 230 | t.Fatal(err) | ||
| 231 | } | ||
| 232 | matched := []store.DepAdvisory{{Ecosystem: EcoGo, Name: "github.com/a/b", Version: "v1.0.0", | ||
| 233 | ID: "GO-1", Summary: "bad", Fixed: "1.1.0"}} | ||
| 234 | if err := w.reconcileAdvisories(repo, matched); err != nil { | ||
| 235 | t.Fatal(err) | ||
| 236 | } | ||
| 237 | check, _ := w.St.DepCheckFor(repo.ID) | ||
| 238 | if check.AdvisoryIssueNumber == 0 || check.AdvisoryIssueNumber == check.IssueNumber { | ||
| 239 | t.Fatalf("advisory issue #%d, updates issue #%d", check.AdvisoryIssueNumber, check.IssueNumber) | ||
| 240 | } | ||
| 241 | issue, _ := w.St.IssueByNumber(repo.ID, check.AdvisoryIssueNumber) | ||
| 242 | if issue.Title != AdvisoryTitle || !strings.Contains(issue.Body, "GO-1") { | ||
| 243 | t.Errorf("advisory issue = %q\n%s", issue.Title, issue.Body) | ||
| 244 | } | ||
| 245 | mail, _ := w.St.DueMail(10) | ||
| 246 | if len(mail) != 2 || !strings.Contains(mail[1].Subject, AdvisoryTitle) { | ||
| 247 | t.Fatalf("mail = %+v", mail) | ||
| 248 | } | ||
| 249 | |||
| 250 | // An upstream edit to the summary is not a change worth mailing. | ||
| 251 | edited := []store.DepAdvisory{matched[0]} | ||
| 252 | edited[0].Summary = "reworded" | ||
| 253 | if err := w.reconcileAdvisories(repo, edited); err != nil { | ||
| 254 | t.Fatal(err) | ||
| 255 | } | ||
| 256 | if mail, _ := w.St.DueMail(10); len(mail) != 2 { | ||
| 257 | t.Errorf("summary edit mailed: %d messages", len(mail)) | ||
| 258 | } | ||
| 259 | |||
| 260 | // Fixed: the advisories issue closes, the updates issue stays open. | ||
| 261 | if err := w.reconcileAdvisories(repo, nil); err != nil { | ||
| 262 | t.Fatal(err) | ||
| 263 | } | ||
| 264 | if closed, _ := w.St.IssueByNumber(repo.ID, check.AdvisoryIssueNumber); closed.State != "closed" { | ||
| 265 | t.Errorf("advisory issue state = %q", closed.State) | ||
| 266 | } | ||
| 267 | if open, _ := w.St.IssueByNumber(repo.ID, check.IssueNumber); open.State != "open" { | ||
| 268 | t.Errorf("updates issue state = %q", open.State) | ||
| 269 | } | ||
| 270 | if left, _ := w.St.ReportedAdvisories(repo.ID); len(left) != 0 { | ||
| 271 | t.Errorf("advisories left behind: %v", left) | ||
| 272 | } | ||
| 273 | } | ||
internal/store/deps.go +66 −2
| @@ -17,6 +17,9 @@ type DepCheck struct { | |||
| 17 | LastCheck string | 17 | LastCheck string |
| 18 | LastError string | 18 | LastError string |
| 19 | IssueNumber int64 // 0 until an issue has been opened | 19 | IssueNumber int64 // 0 until an issue has been opened |
| 20 | // AdvisoryIssueNumber is the advisories issue, kept apart from the | ||
| 21 | // updates one. | ||
| 22 | AdvisoryIssueNumber int64 | ||
| 20 | } | 23 | } |
| 21 | 24 | ||
| 22 | // DepReport is one dependency found to be behind, as last reported. | 25 | // DepReport is one dependency found to be behind, as last reported. |
| @@ -27,6 +30,18 @@ type DepReport struct { | |||
| 27 | Latest string | 30 | Latest string |
| 28 | } | 31 | } |
| 29 | 32 | ||
| 33 | // DepAdvisory is one published advisory matching a resolved dependency, | ||
| 34 | // as last reported. | ||
| 35 | type DepAdvisory struct { | ||
| 36 | Ecosystem string | ||
| 37 | Name string | ||
| 38 | Version string | ||
| 39 | ID string | ||
| 40 | Summary string | ||
| 41 | Severity string | ||
| 42 | Fixed string // the first release past Version that fixes it, if any | ||
| 43 | } | ||
| 44 | |||
| 30 | func (s *Store) EnableDepCheck(repoID int64) error { | 45 | func (s *Store) EnableDepCheck(repoID int64) error { |
| 31 | _, err := s.DB.Exec("INSERT OR IGNORE INTO dep_checks (repo_id) VALUES (?)", repoID) | 46 | _, err := s.DB.Exec("INSERT OR IGNORE INTO dep_checks (repo_id) VALUES (?)", repoID) |
| 32 | return err | 47 | return err |
| @@ -43,6 +58,9 @@ func (s *Store) DisableDepCheck(repoID int64) error { | |||
| 43 | if _, err := tx.Exec("DELETE FROM dep_reports WHERE repo_id = ?", repoID); err != nil { | 58 | if _, err := tx.Exec("DELETE FROM dep_reports WHERE repo_id = ?", repoID); err != nil { |
| 44 | return err | 59 | return err |
| 45 | } | 60 | } |
| 61 | if _, err := tx.Exec("DELETE FROM dep_advisories WHERE repo_id = ?", repoID); err != nil { | ||
| 62 | return err | ||
| 63 | } | ||
| 46 | if _, err := tx.Exec("DELETE FROM dep_checks WHERE repo_id = ?", repoID); err != nil { | 64 | if _, err := tx.Exec("DELETE FROM dep_checks WHERE repo_id = ?", repoID); err != nil { |
| 47 | return err | 65 | return err |
| 48 | } | 66 | } |
| @@ -52,8 +70,8 @@ func (s *Store) DisableDepCheck(repoID int64) error { | |||
| 52 | func (s *Store) DepCheckFor(repoID int64) (DepCheck, error) { | 70 | func (s *Store) DepCheckFor(repoID int64) (DepCheck, error) { |
| 53 | var d DepCheck | 71 | var d DepCheck |
| 54 | err := s.DB.QueryRow( | 72 | err := s.DB.QueryRow( |
| 55 | "SELECT repo_id, last_check, last_error, issue_number FROM dep_checks WHERE repo_id = ?", repoID). | 73 | "SELECT repo_id, last_check, last_error, issue_number, advisory_issue_number FROM dep_checks WHERE repo_id = ?", repoID). |
| 56 | Scan(&d.RepoID, &d.LastCheck, &d.LastError, &d.IssueNumber) | 74 | Scan(&d.RepoID, &d.LastCheck, &d.LastError, &d.IssueNumber, &d.AdvisoryIssueNumber) |
| 57 | if errors.Is(err, sql.ErrNoRows) { | 75 | if errors.Is(err, sql.ErrNoRows) { |
| 58 | return d, ErrNotFound | 76 | return d, ErrNotFound |
| 59 | } | 77 | } |
| @@ -101,6 +119,11 @@ func (s *Store) SetDepIssue(repoID, number int64) error { | |||
| 101 | return err | 119 | return err |
| 102 | } | 120 | } |
| 103 | 121 | ||
| 122 | func (s *Store) SetDepAdvisoryIssue(repoID, number int64) error { | ||
| 123 | _, err := s.DB.Exec("UPDATE dep_checks SET advisory_issue_number = ? WHERE repo_id = ?", number, repoID) | ||
| 124 | return err | ||
| 125 | } | ||
| 126 | |||
| 104 | func (s *Store) ReportedDeps(repoID int64) ([]DepReport, error) { | 127 | func (s *Store) ReportedDeps(repoID int64) ([]DepReport, error) { |
| 105 | rows, err := s.DB.Query(` | 128 | rows, err := s.DB.Query(` |
| 106 | SELECT ecosystem, name, current, latest FROM dep_reports | 129 | SELECT ecosystem, name, current, latest FROM dep_reports |
| @@ -140,3 +163,44 @@ func (s *Store) ReplaceDepReports(repoID int64, reports []DepReport) error { | |||
| 140 | } | 163 | } |
| 141 | return tx.Commit() | 164 | return tx.Commit() |
| 142 | } | 165 | } |
| 166 | |||
| 167 | func (s *Store) ReportedAdvisories(repoID int64) ([]DepAdvisory, error) { | ||
| 168 | rows, err := s.DB.Query(` | ||
| 169 | SELECT ecosystem, name, version, advisory_id, summary, severity, fixed FROM dep_advisories | ||
| 170 | WHERE repo_id = ? ORDER BY ecosystem, name, version, advisory_id`, repoID) | ||
| 171 | if err != nil { | ||
| 172 | return nil, err | ||
| 173 | } | ||
| 174 | defer rows.Close() | ||
| 175 | var out []DepAdvisory | ||
| 176 | for rows.Next() { | ||
| 177 | var a DepAdvisory | ||
| 178 | if err := rows.Scan(&a.Ecosystem, &a.Name, &a.Version, &a.ID, &a.Summary, &a.Severity, &a.Fixed); err != nil { | ||
| 179 | return nil, err | ||
| 180 | } | ||
| 181 | out = append(out, a) | ||
| 182 | } | ||
| 183 | return out, rows.Err() | ||
| 184 | } | ||
| 185 | |||
| 186 | // ReplaceDepAdvisories swaps in the current matching set wholesale, as | ||
| 187 | // ReplaceDepReports does for updates. | ||
| 188 | func (s *Store) ReplaceDepAdvisories(repoID int64, advisories []DepAdvisory) error { | ||
| 189 | tx, err := s.DB.Begin() | ||
| 190 | if err != nil { | ||
| 191 | return err | ||
| 192 | } | ||
| 193 | defer tx.Rollback() | ||
| 194 | if _, err := tx.Exec("DELETE FROM dep_advisories WHERE repo_id = ?", repoID); err != nil { | ||
| 195 | return err | ||
| 196 | } | ||
| 197 | for _, a := range advisories { | ||
| 198 | if _, err := tx.Exec(` | ||
| 199 | INSERT INTO dep_advisories (repo_id, ecosystem, name, version, advisory_id, summary, severity, fixed) | ||
| 200 | VALUES (?, ?, ?, ?, ?, ?, ?, ?)`, | ||
| 201 | repoID, a.Ecosystem, a.Name, a.Version, a.ID, a.Summary, a.Severity, a.Fixed); err != nil { | ||
| 202 | return err | ||
| 203 | } | ||
| 204 | } | ||
| 205 | return tx.Commit() | ||
| 206 | } | ||
internal/store/migrations/0080_dep_advisories.down.sql added +2
| @@ -0,0 +1,2 @@ | |||
| 1 | DROP TABLE dep_advisories; | ||
| 2 | ALTER TABLE dep_checks DROP COLUMN advisory_issue_number; | ||
internal/store/migrations/0080_dep_advisories.up.sql added +17
| @@ -0,0 +1,17 @@ | |||
| 1 | -- Known vulnerabilities in dependencies: the same opt-in sweep checks the | ||
| 2 | -- resolved dependency set against OSV and reports matches in an issue of | ||
| 3 | -- its own, so an advisory is not filed among routine updates. | ||
| 4 | ALTER TABLE dep_checks ADD COLUMN advisory_issue_number INTEGER NOT NULL DEFAULT 0; | ||
| 5 | |||
| 6 | -- What each repo was last told about, as dep_reports is for updates. | ||
| 7 | CREATE TABLE dep_advisories ( | ||
| 8 | repo_id INTEGER NOT NULL REFERENCES repos(id) ON DELETE CASCADE, | ||
| 9 | ecosystem TEXT NOT NULL, | ||
| 10 | name TEXT NOT NULL, | ||
| 11 | version TEXT NOT NULL, | ||
| 12 | advisory_id TEXT NOT NULL, | ||
| 13 | summary TEXT NOT NULL DEFAULT '', | ||
| 14 | severity TEXT NOT NULL DEFAULT '', | ||
| 15 | fixed TEXT NOT NULL DEFAULT '', | ||
| 16 | PRIMARY KEY (repo_id, ecosystem, name, version, advisory_id) | ||
| 17 | ); | ||
internal/web/templates/settings.html +12 −2
| @@ -220,12 +220,12 @@ | |||
| 220 | <section id="deps"><h2>Dependencies</h2> | 220 | <section id="deps"><h2>Dependencies</h2> |
| 221 | <form method="post" action="{{$base}}" class="setform"> | 221 | <form method="post" action="{{$base}}" class="setform"> |
| 222 | <input type="hidden" name="field" value="deps"> | 222 | <input type="hidden" name="field" value="deps"> |
| 223 | <div><label for="deps-enabled">Check for updates</label><p class="hint">Evaluates the manifests on <code>{{.Repo.DefaultBranch}}</code> and opens an issue. Go, NPM, Crates, and PyPI only.</p></div> | 223 | <div><label for="deps-enabled">Check for updates and advisories</label><p class="hint">Evaluates the manifests and lockfiles on <code>{{.Repo.DefaultBranch}}</code> against the registries and OSV, and opens an issue for each. Updates for Go, NPM, Crates, and PyPI; advisories for those and SwiftPM.</p></div> |
| 224 | <div class="check"><input type="checkbox" id="deps-enabled" name="deps" value="on"{{if .DepsEnabled}} checked{{end}}></div> | 224 | <div class="check"><input type="checkbox" id="deps-enabled" name="deps" value="on"{{if .DepsEnabled}} checked{{end}}></div> |
| 225 | <div><button type="submit" class="btn">Save</button></div> | 225 | <div><button type="submit" class="btn">Save</button></div> |
| 226 | </form> | 226 | </form> |
| 227 | {{if .DepsEnabled}} | 227 | {{if .DepsEnabled}} |
| 228 | <p class="meta">Last checked {{if .Deps.LastCheck}}{{when .Deps.LastCheck}}{{else}}never{{end}}{{if .Deps.IssueNumber}} · <a href="/{{.Repo.OwnerName}}/{{.Repo.Name}}/issues/{{.Deps.IssueNumber}}">#{{.Deps.IssueNumber}}</a>{{end}}</p> | 228 | <p class="meta">Last checked {{if .Deps.LastCheck}}{{when .Deps.LastCheck}}{{else}}never{{end}}{{if .Deps.IssueNumber}} · <a href="/{{.Repo.OwnerName}}/{{.Repo.Name}}/issues/{{.Deps.IssueNumber}}">#{{.Deps.IssueNumber}}</a>{{end}}{{if .Deps.AdvisoryIssueNumber}} · advisories <a href="/{{.Repo.OwnerName}}/{{.Repo.Name}}/issues/{{.Deps.AdvisoryIssueNumber}}">#{{.Deps.AdvisoryIssueNumber}}</a>{{end}}</p> |
| 229 | {{if .Deps.LastError}}<p class="error" role="alert">{{.Deps.LastError}}</p>{{end}} | 229 | {{if .Deps.LastError}}<p class="error" role="alert">{{.Deps.LastError}}</p>{{end}} |
| 230 | {{if .Deps.Behind}}<div class="tablewrap"><table class="keys"> | 230 | {{if .Deps.Behind}}<div class="tablewrap"><table class="keys"> |
| 231 | <tr class="cols"><th scope="col">dependency</th><th scope="col">pinned</th><th scope="col">latest</th></tr> | 231 | <tr class="cols"><th scope="col">dependency</th><th scope="col">pinned</th><th scope="col">latest</th></tr> |
| @@ -236,6 +236,16 @@ | |||
| 236 | </tr> | 236 | </tr> |
| 237 | {{end}}</table></div> | 237 | {{end}}</table></div> |
| 238 | {{else}}<p class="none">Nothing behind{{if not .Deps.LastCheck}} — the first check has not run yet{{end}}.</p>{{end}} | 238 | {{else}}<p class="none">Nothing behind{{if not .Deps.LastCheck}} — the first check has not run yet{{end}}.</p>{{end}} |
| 239 | {{if .Deps.Advisories}}<div class="tablewrap"><table class="keys"> | ||
| 240 | <tr class="cols"><th scope="col">dependency</th><th scope="col">version</th><th scope="col">advisory</th><th scope="col">fixed in</th></tr> | ||
| 241 | {{range .Deps.Advisories}}<tr> | ||
| 242 | <td class="mono">{{.Ecosystem}} {{.Name}}</td> | ||
| 243 | <td class="mono">{{.Version}}</td> | ||
| 244 | <td class="mono"><a href="https://osv.dev/vulnerability/{{.ID}}">{{.ID}}</a></td> | ||
| 245 | <td class="mono">{{.Fixed}}</td> | ||
| 246 | </tr> | ||
| 247 | {{end}}</table></div> | ||
| 248 | {{else if .Deps.LastCheck}}<p class="none">No known advisories.</p>{{end}} | ||
| 239 | {{end}} | 249 | {{end}} |
| 240 | </section> | 250 | </section> |
| 241 | 251 | ||