mirror of
https://github.com/aquasecurity/trivy.git
synced 2026-12-02 01:40:33 +00:00
feat(java): include all 429 rate-limited URLs in POM resolution error (#11527)
This commit is contained in:
1 parent
a7b0d649ea
commit
c8885e9575
6 files changed
+153
-34
No files matched your search
@@ -126,8 +126,9 @@ When scanning Java projects, Trivy resolves transitive dependencies by downloadi
|
||||
|
||||
!!! error
|
||||
```
|
||||
FATAL Error remote Maven repository returned 429 Too Many Requests for https://repo.maven.apache.org/maven2/.../<artifact>-<version>.pom. Retry-After: 1800.
|
||||
The repository blocks all subsequent requests from this IP until the block clears.
|
||||
FATAL Error remote Maven repositories returned 429 Too Many Requests for:
|
||||
- https://repo.maven.apache.org/maven2/.../<artifact>-<version>.pom (Retry-After: 1800)
|
||||
The repositories block all subsequent requests from this IP until the block clears.
|
||||
To avoid this, populate the local Maven cache before scanning (e.g. run `mvn dependency:resolve`, or `mvn install` for a multi-module project, and cache ~/.m2 in CI).
|
||||
```
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package pom
|
||||
|
||||
import (
|
||||
"cmp"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
@@ -717,6 +718,23 @@ func Test_fetchPOMFromRemoteRepositories_mirror(t *testing.T) {
|
||||
wantHits: map[string]int{"limited": 1},
|
||||
wantErr: "429",
|
||||
},
|
||||
{
|
||||
// Multiple mirrors are rate-limited; all are queried and the 429 is returned.
|
||||
name: "multiple mirrors rate-limited: all are queried and 429 is returned",
|
||||
mirrorPatterns: []string{"*"},
|
||||
configMirrors: map[string][]string{"mirror": {"limited", "limit2"}},
|
||||
wantHits: map[string]int{"limited": 1, "limit2": 1},
|
||||
wantErr: `429 Too Many Requests for:\n - http://.*/example-api-1\.0\.0\.pom\n - http://.*/example-api-1\.0\.0\.pom`,
|
||||
},
|
||||
{
|
||||
// The first mirror returns 429, the second one serves a broken POM: the failure
|
||||
// is returned together with the 429, which is not lost.
|
||||
name: "429 followed by a failure: both are reported",
|
||||
mirrorPatterns: []string{"*"},
|
||||
configMirrors: map[string][]string{"mirror": {"limited", "broken"}},
|
||||
wantHits: map[string]int{"limited": 1, "broken": 1},
|
||||
wantErr: `(?s)failed to parse the remote POM.*429 Too Many Requests for:\n - http://\S+/example-api-1\.0\.0\.pom$`,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
@@ -726,7 +744,8 @@ func Test_fetchPOMFromRemoteRepositories_mirror(t *testing.T) {
|
||||
|
||||
// newServer registers an HTTP server for a role. status 200 serves the POM;
|
||||
// any other status (e.g. 404 or 429) makes the fetch fall back to the next candidate.
|
||||
newServer := func(role string, status int) *httptest.Server {
|
||||
// A non-empty body overrides the served POM.
|
||||
newServer := func(role string, status int, body string) *httptest.Server {
|
||||
s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
hits[role]++
|
||||
if u, _, ok := r.BasicAuth(); ok {
|
||||
@@ -736,7 +755,7 @@ func Test_fetchPOMFromRemoteRepositories_mirror(t *testing.T) {
|
||||
w.WriteHeader(status)
|
||||
return
|
||||
}
|
||||
_, _ = w.Write([]byte(minimalPOM))
|
||||
_, _ = w.Write([]byte(cmp.Or(body, minimalPOM)))
|
||||
}))
|
||||
t.Cleanup(s.Close)
|
||||
return s
|
||||
@@ -745,11 +764,13 @@ func Test_fetchPOMFromRemoteRepositories_mirror(t *testing.T) {
|
||||
// repo1: original repository; mirror: settings.xml target; chain/dead:
|
||||
// trivy.yaml targets (dead always 404s).
|
||||
servers := map[string]*httptest.Server{
|
||||
"repo1": newServer("repo1", http.StatusOK),
|
||||
"mirror": newServer("mirror", http.StatusOK),
|
||||
"chain": newServer("chain", http.StatusOK),
|
||||
"dead": newServer("dead", http.StatusNotFound),
|
||||
"limited": newServer("limited", http.StatusTooManyRequests),
|
||||
"repo1": newServer("repo1", http.StatusOK, ""),
|
||||
"mirror": newServer("mirror", http.StatusOK, ""),
|
||||
"chain": newServer("chain", http.StatusOK, ""),
|
||||
"dead": newServer("dead", http.StatusNotFound, ""),
|
||||
"limited": newServer("limited", http.StatusTooManyRequests, ""),
|
||||
"broken": newServer("broken", http.StatusOK, "not a pom"),
|
||||
"limit2": newServer("limit2", http.StatusTooManyRequests, ""),
|
||||
}
|
||||
|
||||
// trivy.yaml mirrors: resolve role names to server URLs.
|
||||
@@ -785,7 +806,7 @@ func Test_fetchPOMFromRemoteRepositories_mirror(t *testing.T) {
|
||||
paths := []string{"com", "example", "example-api", "1.0.0", "example-api-1.0.0.pom"}
|
||||
got, err := p.fetchPOMFromRemoteRepositories(t.Context(), paths, false, []repository{pomRepo})
|
||||
if tt.wantErr != "" {
|
||||
require.ErrorContains(t, err, tt.wantErr)
|
||||
require.Regexp(t, tt.wantErr, err)
|
||||
} else {
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, got)
|
||||
|
||||
@@ -845,10 +845,10 @@ func (p *Parser) fetchPOMFromRemoteRepositories(ctx context.Context, paths []str
|
||||
}
|
||||
|
||||
seen := set.New[string]()
|
||||
// A 429 only skips the rate-limited mirror; the last one is kept so it can be returned
|
||||
// if no other mirror serves the POM. A rate-limited mirror leaves the result unknown,
|
||||
// A 429 only skips the rate-limited mirror; all rate-limited targets are collected so they can
|
||||
// be returned if no other mirror serves the POM. A rate-limited mirror leaves the result unknown,
|
||||
// so the 429 wins over the "not found" that the remaining mirrors may have returned.
|
||||
var lastRateLimitErr error
|
||||
var rateLimitTargets []rateLimitTarget
|
||||
// Try all remoteRepositories by following order:
|
||||
// 1. remoteRepositories from settings.xml
|
||||
// 2. remoteRepositories from pom.xml (passed as parameter)
|
||||
@@ -876,11 +876,11 @@ func (p *Parser) fetchPOMFromRemoteRepositories(ctx context.Context, paths []str
|
||||
if snapshot {
|
||||
pomFileName, err := p.fetchPomFileNameFromMavenMetadata(ctx, candidate.url, repoPaths)
|
||||
if err != nil {
|
||||
if _, ok := errors.AsType[*rateLimitError](err); ok {
|
||||
lastRateLimitErr = err
|
||||
if target, ok := errors.AsType[*rateLimitTarget](err); ok {
|
||||
rateLimitTargets = append(rateLimitTargets, *target)
|
||||
continue
|
||||
}
|
||||
return nil, xerrors.Errorf("fetch maven-metadata.xml error: %w", err)
|
||||
return nil, wrapWithRateLimitTargets(xerrors.Errorf("fetch maven-metadata.xml error: %w", err), rateLimitTargets)
|
||||
}
|
||||
// Use file name from `maven-metadata.xml` if it exists
|
||||
if pomFileName != "" {
|
||||
@@ -889,19 +889,19 @@ func (p *Parser) fetchPOMFromRemoteRepositories(ctx context.Context, paths []str
|
||||
}
|
||||
fetched, err := p.fetchPOMFromRemoteRepository(ctx, candidate.url, repoPaths)
|
||||
if err != nil {
|
||||
if _, ok := errors.AsType[*rateLimitError](err); ok {
|
||||
lastRateLimitErr = err
|
||||
if target, ok := errors.AsType[*rateLimitTarget](err); ok {
|
||||
rateLimitTargets = append(rateLimitTargets, *target)
|
||||
continue
|
||||
}
|
||||
return nil, xerrors.Errorf("fetch repository error: %w", err)
|
||||
return nil, wrapWithRateLimitTargets(xerrors.Errorf("fetch repository error: %w", err), rateLimitTargets)
|
||||
} else if fetched == nil {
|
||||
continue
|
||||
}
|
||||
return fetched, nil
|
||||
}
|
||||
}
|
||||
if lastRateLimitErr != nil {
|
||||
return nil, lastRateLimitErr
|
||||
if len(rateLimitTargets) > 0 {
|
||||
return nil, newRateLimitError(rateLimitTargets)
|
||||
}
|
||||
return nil, xerrors.Errorf("the POM was not found in remote repositories")
|
||||
}
|
||||
@@ -945,7 +945,7 @@ func (p *Parser) fetchPomFileNameFromMavenMetadata(ctx context.Context, repoURL
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode == http.StatusTooManyRequests {
|
||||
return "", newRateLimitError(req, resp)
|
||||
return "", newRateLimitTarget(req, resp)
|
||||
}
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
p.logger.Debug("Failed to fetch", log.String("url", req.URL.Redacted()), log.Int("statusCode", resp.StatusCode))
|
||||
@@ -986,7 +986,7 @@ func (p *Parser) fetchPOMFromRemoteRepository(ctx context.Context, repoURL url.U
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode == http.StatusTooManyRequests {
|
||||
return nil, newRateLimitError(req, resp)
|
||||
return nil, newRateLimitTarget(req, resp)
|
||||
}
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
p.logger.Debug("Failed to fetch", log.String("url", req.URL.Redacted()), log.Int("statusCode", resp.StatusCode))
|
||||
@@ -1073,7 +1073,24 @@ func shouldReturnError(err error) bool {
|
||||
return errors.As(err, &ue)
|
||||
}
|
||||
|
||||
// rateLimitError wraps a 429 Too Many Requests response from a remote Maven repository.
|
||||
// rateLimitTarget records a 429 response from a single remote request.
|
||||
type rateLimitTarget struct {
|
||||
url string
|
||||
retryAfter string
|
||||
}
|
||||
|
||||
func (t *rateLimitTarget) Error() string {
|
||||
return fmt.Sprintf("429 Too Many Requests for %s", t.url)
|
||||
}
|
||||
|
||||
func newRateLimitTarget(req *http.Request, resp *http.Response) *rateLimitTarget {
|
||||
return &rateLimitTarget{
|
||||
url: displayURL(*req.URL),
|
||||
retryAfter: resp.Header.Get("Retry-After"),
|
||||
}
|
||||
}
|
||||
|
||||
// rateLimitError wraps 429 Too Many Requests responses from remote Maven repositories.
|
||||
// The wrapped *types.UserError is exposed via Unwrap so the top level still prints the
|
||||
// clean 429 message.
|
||||
type rateLimitError struct {
|
||||
@@ -1083,20 +1100,39 @@ type rateLimitError struct {
|
||||
func (e *rateLimitError) Error() string { return e.err.Error() }
|
||||
func (e *rateLimitError) Unwrap() error { return e.err }
|
||||
|
||||
// newRateLimitError builds a rateLimitError for a 429 response, including Retry-After.
|
||||
func newRateLimitError(req *http.Request, resp *http.Response) *rateLimitError {
|
||||
var ra string
|
||||
if v := resp.Header.Get("Retry-After"); v != "" {
|
||||
ra = fmt.Sprintf(" Retry-After: %s.", v)
|
||||
// formatRateLimitTargets lists the rate-limited URLs with their Retry-After values, one per line.
|
||||
func formatRateLimitTargets(targets []rateLimitTarget) string {
|
||||
var lines []string
|
||||
for _, t := range targets {
|
||||
line := fmt.Sprintf(" - %s", t.url)
|
||||
if t.retryAfter != "" {
|
||||
line += fmt.Sprintf(" (Retry-After: %s)", t.retryAfter)
|
||||
}
|
||||
lines = append(lines, line)
|
||||
}
|
||||
return strings.Join(lines, "\n")
|
||||
}
|
||||
|
||||
// wrapWithRateLimitTargets appends the 429 responses collected before a later failure to that failure.
|
||||
// Unlike newRateLimitError, it keeps the failure itself in the error chain, so that e.g. a timeout
|
||||
// is neither hidden behind the *types.UserError nor loses the diagnostics.
|
||||
func wrapWithRateLimitTargets(err error, targets []rateLimitTarget) error {
|
||||
if len(targets) == 0 {
|
||||
return err
|
||||
}
|
||||
return fmt.Errorf("%w\nBefore that, remote Maven repositories returned 429 Too Many Requests for:\n%s",
|
||||
err, formatRateLimitTargets(targets))
|
||||
}
|
||||
|
||||
func newRateLimitError(targets []rateLimitTarget) *rateLimitError {
|
||||
return &rateLimitError{
|
||||
err: &types.UserError{
|
||||
Message: fmt.Sprintf(
|
||||
"remote Maven repository returned 429 Too Many Requests for %s.%s\n"+
|
||||
"The repository blocks all subsequent requests from this IP until the block clears.\n"+
|
||||
"remote Maven repositories returned 429 Too Many Requests for:\n%s\n"+
|
||||
"The repositories block all subsequent requests from this IP until the block clears.\n"+
|
||||
"To avoid this, populate the local Maven cache before scanning "+
|
||||
"(e.g. run `mvn dependency:resolve`, or `mvn install` for a multi-module project, and cache ~/.m2 in CI).",
|
||||
req.URL.Redacted(), ra,
|
||||
formatRateLimitTargets(targets),
|
||||
),
|
||||
},
|
||||
}
|
||||
|
||||
@@ -241,7 +241,7 @@ func TestPom_Parse(t *testing.T) {
|
||||
w.Header().Set("Retry-After", "1800")
|
||||
w.WriteHeader(http.StatusTooManyRequests)
|
||||
}),
|
||||
wantErr: "429 Too Many Requests for http://",
|
||||
wantErr: "429 Too Many Requests for:\n - http://",
|
||||
},
|
||||
{
|
||||
name: "snapshot repository returns 429 Too Many Requests on maven-metadata.xml",
|
||||
@@ -250,7 +250,7 @@ func TestPom_Parse(t *testing.T) {
|
||||
w.Header().Set("Retry-After", "1800")
|
||||
w.WriteHeader(http.StatusTooManyRequests)
|
||||
}),
|
||||
wantErr: "429 Too Many Requests for http://",
|
||||
wantErr: "429 Too Many Requests for:\n - http://",
|
||||
},
|
||||
{
|
||||
name: "snapshot dependency",
|
||||
|
||||
@@ -73,3 +73,10 @@ func resolvePomRepos(servers []Server, pomRepos []pomRepository) []repository {
|
||||
}
|
||||
return repos
|
||||
}
|
||||
|
||||
// displayURL returns the URL without the userinfo, query and fragment, which may carry
|
||||
// credentials or a token.
|
||||
func displayURL(u url.URL) string {
|
||||
u.User, u.RawQuery, u.Fragment, u.ForceQuery = nil, "", "", false
|
||||
return u.String()
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package pom
|
||||
|
||||
import (
|
||||
"net/url"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func Test_displayURL(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
url string
|
||||
want string
|
||||
}{
|
||||
{
|
||||
name: "plain URL is kept",
|
||||
url: "https://repo.example.com/maven2/com/example/a/1.0/a-1.0.pom",
|
||||
want: "https://repo.example.com/maven2/com/example/a/1.0/a-1.0.pom",
|
||||
},
|
||||
{
|
||||
name: "username and password are removed",
|
||||
url: "https://user:pass@repo.example.com/maven2/a-1.0.pom",
|
||||
want: "https://repo.example.com/maven2/a-1.0.pom",
|
||||
},
|
||||
{
|
||||
name: "username without password is removed",
|
||||
url: "https://user@repo.example.com/maven2/a-1.0.pom",
|
||||
want: "https://repo.example.com/maven2/a-1.0.pom",
|
||||
},
|
||||
{
|
||||
name: "query and fragment are removed",
|
||||
url: "https://repo.example.com/maven2/a-1.0.pom?token=secret#frag",
|
||||
want: "https://repo.example.com/maven2/a-1.0.pom",
|
||||
},
|
||||
{
|
||||
name: "empty query is removed",
|
||||
url: "https://repo.example.com/maven2/a-1.0.pom?",
|
||||
want: "https://repo.example.com/maven2/a-1.0.pom",
|
||||
},
|
||||
{
|
||||
name: "port is kept",
|
||||
url: "http://user:pass@127.0.0.1:8081/maven2/?token=secret",
|
||||
want: "http://127.0.0.1:8081/maven2/",
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
u, err := url.Parse(tt.url)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, tt.want, displayURL(*u))
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user