Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(java): add support of test scope for pom.xml files #7486

Draft
wants to merge 8 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 12 additions & 6 deletions docs/docs/coverage/language/java.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,12 @@ Each artifact supports the following scanners:

The following table provides an outline of the features Trivy offers.

| Artifact | Internet access | Dev dependencies | [Dependency graph][dependency-graph] | Position | [Detection Priority][detection-priority] |
|------------------|:---------------------:|:----------------:|:------------------------------------:|:--------:|:----------------------------------------:|
| JAR/WAR/PAR/EAR | Trivy Java DB | Include | - | - | Not needed |
| pom.xml | Maven repository [^1] | Exclude | ✓ | ✓[^7] | - |
| *gradle.lockfile | - | Exclude | ✓ | ✓ | Not needed |
| *.sbt.lock | - | Exclude | - | ✓ | Not needed |
| Artifact | Internet access | Dev dependencies | [Dependency graph][dependency-graph] | Position | [Detection Priority][detection-priority] |
|------------------|:---------------------:|:------------------:|:------------------------------------:|:--------:|:----------------------------------------:|
| JAR/WAR/PAR/EAR | Trivy Java DB | Include | - | - | Not needed |
| pom.xml | Maven repository [^1] | [Exclude](#scopes) | ✓ | ✓[^7] | - |
| *gradle.lockfile | - | Exclude | ✓ | ✓ | Not needed |
| *.sbt.lock | - | Exclude | - | ✓ | Not needed |

These may be enabled or disabled depending on the target.
See [here](./index.md) for the detail.
Expand Down Expand Up @@ -69,6 +69,11 @@ The vulnerability database will be downloaded anyway.
!!! Warning
Trivy may skip some dependencies (that were not found on your local machine) when the `--offline-scan` flag is passed.

### scopes
Trivy supports `runtime`, `compile`, `test` and `import` (for `dependencyManagement`) [dependency scopes][dependency-scopes].
Dependencies without scope are also detected.

By default, Trivy doesn't report dependencies with `test` scope. Use the `--include-dev-deps` flag to include them.

### maven-invoker-plugin
Typically, the integration tests directory (`**/[src|target]/it/*/pom.xml`) of [maven-invoker-plugin][maven-invoker-plugin] doesn't contain actual `pom.xml` files and should be skipped to avoid noise.
Expand Down Expand Up @@ -120,3 +125,4 @@ Make sure that you have cache[^8] directory to find licenses from `*.pom` depend
[maven-pom-repos]: https://maven.apache.org/settings.html#repositories
[sbt-dependency-lock]: https://stringbean.github.io/sbt-dependency-lock
[detection-priority]: ../../scanner/vulnerability.md#detection-priority
[dependency-scopes]: https://maven.apache.org/guides/introduction/introduction-to-dependency-mechanism.html#Dependency_Scope
1 change: 1 addition & 0 deletions pkg/dependency/parser/java/pom/artifact.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ type artifact struct {

Module bool
Relationship ftypes.Relationship
Test bool

Locations ftypes.Locations
}
Expand Down
16 changes: 15 additions & 1 deletion pkg/dependency/parser/java/pom/parse.go
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,7 @@ func (p *Parser) Parse(r xio.ReadSeekerAt) ([]ftypes.Package, []ftypes.Dependenc
return p.parseRoot(root.artifact(), make(map[string]struct{}))
}

// nolint: gocyclo
func (p *Parser) parseRoot(root artifact, uniqModules map[string]struct{}) ([]ftypes.Package, []ftypes.Dependency, error) {
// Prepare a queue for dependencies
queue := newArtifactQueue()
Expand Down Expand Up @@ -161,7 +162,16 @@ func (p *Parser) parseRoot(root artifact, uniqModules map[string]struct{}) ([]ft

// For soft requirements, skip dependency resolution that has already been resolved.
if uniqueArt, ok := uniqArtifacts[art.Name()]; ok {
// Check that both artifact and saved artifact has `test` scope.
// Otherwise, it is non-test dependency
art.Test = uniqueArt.Test && art.Test
if !uniqueArt.Version.shouldOverride(art.Version) {
// If saved artifact is `test`, but new artifact is `non-test`,
// then mark saved artifact as `non-test`.
if !art.Test && uniqueArt.Test {
uniqueArt.Test = art.Test
uniqArtifacts[art.Name()] = uniqueArt
}
continue
}
// mark artifact as Direct, if saved artifact is Direct
Expand Down Expand Up @@ -214,6 +224,7 @@ func (p *Parser) parseRoot(root artifact, uniqModules map[string]struct{}) ([]ft
Licenses: result.artifact.Licenses,
Relationship: art.Relationship,
Locations: art.Locations,
Test: art.Test,
}

// save only dependency names
Expand All @@ -234,6 +245,7 @@ func (p *Parser) parseRoot(root artifact, uniqModules map[string]struct{}) ([]ft
Licenses: art.Licenses,
Relationship: art.Relationship,
Locations: art.Locations,
Dev: art.Test,
}
pkgs = append(pkgs, pkg)

Expand Down Expand Up @@ -301,6 +313,7 @@ func (p *Parser) resolve(art artifact, rootDepManagement []pomDependency) (analy
result, err := p.analyze(pomContent, analysisOptions{
exclusions: art.Exclusions,
depManagement: rootDepManagement,
testScope: art.Test,
})
if err != nil {
return analysisResult{}, xerrors.Errorf("analyze error: %w", err)
Expand All @@ -323,6 +336,7 @@ type analysisOptions struct {
exclusions map[string]struct{}
depManagement []pomDependency // from the root POM
lineNumber bool // Save line numbers
testScope bool
}

func (p *Parser) analyze(pom *pom, opts analysisOptions) (analysisResult, error) {
Expand Down Expand Up @@ -400,7 +414,7 @@ func (p *Parser) parseDependencies(deps []pomDependency, props map[string]string
// Resolve dependencies
d = d.Resolve(props, depManagement, rootDepManagement)

if (d.Scope != "" && d.Scope != "compile" && d.Scope != "runtime") || d.Optional {
if (d.Scope != "" && d.Scope != "compile" && d.Scope != "runtime" && d.Scope != "test") || d.Optional {
continue
}

Expand Down
84 changes: 84 additions & 0 deletions pkg/dependency/parser/java/pom/parse_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1499,6 +1499,90 @@ func TestPom_Parse(t *testing.T) {
},
},
},
// [INFO] --- dependency:3.7.0:tree (default-cli) @ test-example ---
// [INFO] com.example:test-example:jar:1.0.0
// [INFO] +- org.example:example-nested:jar:3.3.3:compile
// [INFO] | \- org.example:example-dependency:jar:1.2.3:compile
// [INFO] \- org.example:example-dependency2:jar:2.3.4:test
// [INFO] \- org.example:example-api:jar:1.7.30:compile
{
name: "include dependencies with test scope",
inputFile: filepath.Join("testdata", "test-scope", "pom.xml"),
local: true,
want: []ftypes.Package{
{
ID: "com.example:test-example:1.0.0",
Name: "com.example:test-example",
Version: "1.0.0",
Relationship: ftypes.RelationshipRoot,
},
{
ID: "org.example:example-dependency2:2.3.4",
Name: "org.example:example-dependency2",
Version: "2.3.4",
Relationship: ftypes.RelationshipDirect,
Dev: true,
Locations: ftypes.Locations{
{
StartLine: 18,
EndLine: 23,
},
},
},
{
ID: "org.example:example-nested:3.3.3",
Name: "org.example:example-nested",
Version: "3.3.3",
Relationship: ftypes.RelationshipDirect,
Locations: ftypes.Locations{
{
StartLine: 13,
EndLine: 17,
},
},
},
{
ID: "org.example:example-api:1.7.30",
Name: "org.example:example-api",
Version: "1.7.30",
Licenses: []string{"The Apache Software License, Version 2.0"},
Relationship: ftypes.RelationshipIndirect,
},
{
ID: "org.example:example-dependency:1.2.3",
Name: "org.example:example-dependency",
Version: "1.2.3",
Relationship: ftypes.RelationshipIndirect,
},
},
wantDeps: []ftypes.Dependency{
{
ID: "com.example:test-example:1.0.0",
DependsOn: []string{
"org.example:example-dependency2:2.3.4",
"org.example:example-nested:3.3.3",
},
},
{
ID: "org.example:example-dependency2:2.3.4",
DependsOn: []string{
"org.example:example-api:1.7.30",
},
},
{
ID: "org.example:example-dependency:1.2.3",
DependsOn: []string{
"org.example:example-api:1.7.30",
},
},
{
ID: "org.example:example-nested:3.3.3",
DependsOn: []string{
"org.example:example-dependency:1.2.3",
},
},
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
Expand Down
1 change: 1 addition & 0 deletions pkg/dependency/parser/java/pom/pom.go
Original file line number Diff line number Diff line change
Expand Up @@ -303,6 +303,7 @@ func (d pomDependency) ToArtifact(opts analysisOptions) artifact {
Exclusions: exclusions,
Locations: locations,
Relationship: ftypes.RelationshipIndirect, // default
Test: d.Scope == "test" || opts.testScope,
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm wondering if it works as expected. For example, if two direct dependencies have the same transitive dependency, and one scope is "test" and the other is not, I guess it would not be considered devDependency. How does Maven work?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

hm... Nice catch.

I updated logic and added test for this case (comment before test shows how mvn works).
Can you take a look and check that this is what you meant?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Doesn't it mean it'll include the test even if testScope is false? Unlike the other PR, this PR still includes test dependencies for me

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

hmm... that's weird.
Do you see any vulnerabilities for test dependencies (or test packages in json format)?

debug logs for test dependencies are normal for this PR, because Trivy currently analyzes all dependencies and excludes Dev dependencies later.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It takes ages to scan and then fails with:

semaphore acquire: context deadline exceeded

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is timeout error.
Trivy's runtime has increased because Trivy first checks all dependencies (including test ones), and only then excludes them from the report

}
}

Expand Down
25 changes: 25 additions & 0 deletions pkg/dependency/parser/java/pom/testdata/test-scope/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.example</groupId>
<artifactId>test-example</artifactId>
<version>1.0.0</version>

<name>test-example</name>
<description>Example</description>

<dependencies>
<dependency>
<groupId>org.example</groupId>
<artifactId>example-nested</artifactId>
<version>3.3.3</version>
</dependency>
<dependency>
<groupId>org.example</groupId>
<artifactId>example-dependency2</artifactId>
<version>2.3.4</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>