Skip to content
Open
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
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -863,7 +863,7 @@ The <code>remediate</code> command scans manifest files for known vulnerabilitie
<h4>Supported Manifest Formats</h4>
<ul>
<li><strong>Maven</strong> — <code>pom.xml</code> (single-module projects; updates dependency version elements and resolves property references)</li>
<li><strong>Gradle Version Catalog</strong> — <code>libs.versions.toml</code> or any <code>*.versions.toml</code> file (updates centralized version references and inline version declarations)</li>
<li><strong>Gradle Version Catalog</strong> — <code>libs.versions.toml</code> or any <code>*.versions.toml</code> file (updates centralized version references and inline version declarations). In a multi-project build, every project that belongs to the catalog's build is analyzed, so dependencies used only in subprojects are included.</li>
</ul>

<h4>CLI Flags</h4>
Expand Down Expand Up @@ -943,7 +943,7 @@ When multiple vulnerability providers suggest different remediation versions for

<h4>Known Limitations</h4>
<ul>
<li>Gradle DSL files (<code>build.gradle</code>, <code>build.gradle.kts</code>) are not supported — only version catalog files (<code>*.versions.toml</code>).</li>
<li>Gradle DSL files (<code>build.gradle</code>, <code>build.gradle.kts</code>) are not supported — only version catalog files (<code>*.versions.toml</code>). Dependencies declared directly in a build file (not in the catalog) are reported as skipped, since they cannot be edited.</li>
<li>Multi-module Maven projects with inherited dependency versions from parent POMs are not supported — only versions declared directly in the scanned <code>pom.xml</code> are updated.</li>
</ul>

Expand Down
92 changes: 44 additions & 48 deletions src/providers/java_gradle.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,8 @@ import Base_java, { ecosystem_gradle } from "./base_java.js";

/** @typedef {import('../provider.js').Provided} Provided */

const ROOT_PROJECT_KEY_NAME = "root-project";

const BUILD_FILE_NAMES = ['build.gradle.kts', 'build.gradle']
const MAX_BUILD_FILE_SEARCH_DEPTH = 5

const TRUSTIFY_DA_IGNORE_REGEX_LINE = /.*\s?(exhortignore|trustify-da-ignore)\s*$/g
const TRUSTIFY_DA_IGNORE_REGEX = /\/\/\s?(exhortignore|trustify-da-ignore)/
Expand All @@ -40,6 +40,28 @@ function stripString(depPart) {
return depPart.replaceAll(/["']/g,"")
}

/**
* Walk from `startDir` upward looking for a Gradle build file. Bounded so a scan
* starting outside a Gradle project cannot escape to the filesystem root.
* @param {string} startDir
* @returns {string|undefined} absolute path to the nearest build file, if any
*/
export function findNearestBuildFile(startDir) {
let dir = startDir
for (let depth = 0; depth < MAX_BUILD_FILE_SEARCH_DEPTH; depth++) {
for (const name of BUILD_FILE_NAMES) {
const candidate = path.join(dir, name)
if (fs.existsSync(candidate)) {
return candidate
}
}
const parent = path.dirname(dir)
if (parent === dir) { break }
dir = parent
}
return undefined
}

/**
* This class provides common functionality for Groovy and Kotlin DSL files.
*/
Expand Down Expand Up @@ -75,30 +97,7 @@ export default class Java_gradle extends Base_java {
* @returns {boolean}
*/
validateLockFile(manifestDir) {
return this.#findBuildFile(manifestDir) !== undefined
}

/**
* Walk from `startDir` upward looking for a Gradle build file.
* Stops after 5 levels to avoid scanning to the filesystem root.
* @param {string} startDir
* @returns {string|undefined} absolute path to the build file, or undefined
*/
#findBuildFile(startDir) {
const maxDepth = 5
let dir = startDir
for (let i = 0; i < maxDepth; i++) {
for (const name of ['build.gradle.kts', 'build.gradle']) {
const candidate = path.join(dir, name)
if (fs.existsSync(candidate)) {
return candidate
}
}
const parent = path.dirname(dir)
if (parent === dir) { break }
dir = parent
}
return undefined
return findNearestBuildFile(manifestDir) !== undefined
}

/**
Expand Down Expand Up @@ -127,7 +126,7 @@ export default class Java_gradle extends Base_java {
if (!path.basename(manifest).endsWith('.versions.toml')) {
return manifest
}
const found = this.#findBuildFile(path.dirname(manifest))
const found = findNearestBuildFile(path.dirname(manifest))
if (!found) {
throw new Error(`No parent build.gradle found for ${path.basename(manifest)}`)
}
Expand Down Expand Up @@ -200,7 +199,9 @@ export default class Java_gradle extends Base_java {
line: `${processedLine}:compile`,
depth: depth
};
});
})
// Depth -1 marks lines that are not part of a dependency tree (e.g. "No dependencies").
.filter(entry => entry.depth > 0);
}

/**
Expand Down Expand Up @@ -242,11 +243,8 @@ export default class Java_gradle extends Base_java {
}
}

#buildRootCoordinate(properties) {
const group = properties.group || 'unknown'
const version = properties.version || '0.0.0'
const rootName = properties[ROOT_PROJECT_KEY_NAME]?.match(/Root project '(.+)'/)?.[1] || 'unknown'
return `${group}:${rootName}:jar:${version}`
#buildRootCoordinate({ group, name, version }) {
return `${group || 'unknown'}:${name || 'unknown'}:jar:${version || '0.0.0'}`
}

/**
Expand Down Expand Up @@ -294,24 +292,22 @@ export default class Java_gradle extends Base_java {
}

/**
*
* @param {string} manifestPath - path to build.gradle.
* @param {Object} opts - contains various options settings from client.
* @return {{Object}} an object that contains all gradle properties
* Reads the identity of the project that `gradle properties` was run in.
* `name` is the current project, so a subproject build file yields the
* subproject's identity rather than the root project's.
* @param {string} manifestPath - path to build.gradle[.kts]
* @param {Object} opts - client options
* @returns {{group: string|undefined, name: string|undefined, version: string|undefined}}
*/
#extractProperties(manifestPath, opts) {
let properties = {}
let propertiesContent = this.#getProperties(manifestPath, opts)
let regExpMatchArray = propertiesContent.match(/([^\n:]+):[\t ]*(.*)/g);
for (let i = 0; i < regExpMatchArray.length - 1; i++) {
let parts = regExpMatchArray[i].split(":");
properties[parts[0].trim()] = parts[1].trim()
}
let regExpMatchArray1 = propertiesContent.match(/Root project '(.+)'/);
if (regExpMatchArray1[0]) {
properties[ROOT_PROJECT_KEY_NAME] = regExpMatchArray1[0]
const output = this.#getProperties(manifestPath, opts)
const readProperty = key => output.match(new RegExp(`^${key}:[ \\t]*(.*)$`, 'm'))?.[1].trim()

return {
group: readProperty('group'),
name: readProperty('name'),
version: readProperty('version'),
}
return properties;
}

/**
Expand Down
64 changes: 53 additions & 11 deletions src/remediate.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { PackageURL } from 'packageurl-js'

import analysis from './analysis.js'
import { availableProviders, match } from './provider.js'
import { discoverGradleSubprojects, findNearestBuildFile } from './providers/java_gradle.js'
import { extractRemediations, compareVersions } from './remediation.js'
import { mavenChangeKey, mavenDepsForEditSite, updateMavenVersions } from './updaters/maven_updater.js'
import { tomlChangeKey, tomlDepsForEditSite, updateTomlVersions } from './updaters/toml_updater.js'
Expand Down Expand Up @@ -203,6 +204,33 @@ export function findManifests(targetPath) {
return manifests
}

/**
* Resolves which manifests must be analyzed to produce remediations for `manifestPath`.
*
* Maven manifests are analyzed as-is. A Gradle version catalog is shared by every project
* in its build, while `gradle dependencies` only reports the project it runs in, so the
* catalog's owning build is expanded to all of its projects. Falls back to analyzing the
* catalog itself when the build cannot be discovered (no settings file) or has no projects.
*
* @param {string} manifestPath - the manifest being remediated
* @param {ManifestType} manifestType
* @param {Object} opts - client options
* @returns {Promise<string[]>} manifests to analyze
*/
async function analysisPathsFor(manifestPath, manifestType, opts) {
if (manifestType.label !== 'toml') {
return [manifestPath]
}

const buildFile = findNearestBuildFile(path.dirname(manifestPath))

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Medium · Sibling dependencies go unreported

When a version catalog is stored beneath a subproject that has its own build file while the build settings file is in an ancestor directory, findNearestBuildFile() selects the subproject build file, so analysisPathsFor() starts discovery in that subproject and cannot find the ancestor settings file. Discovery falls back to the catalog or analyzes only that subproject, leaving sibling-project dependencies out of the report.

Find the build and settings context that owns the catalog before discovering projects, rather than starting from the nearest subproject build file.

Also at src/remediate.js:230.

Prompt for AI agents
In `src/remediate.js` at line 225:

**Sibling dependencies go unreported**

When a version catalog is stored beneath a subproject that has its own build file while the build settings file is in an ancestor directory, `findNearestBuildFile()` selects the subproject build file, so `analysisPathsFor()` starts discovery in that subproject and cannot find the ancestor settings file. Discovery falls back to the catalog or analyzes only that subproject, leaving sibling-project dependencies out of the report.

Find the build and settings context that owns the catalog before discovering projects, rather than starting from the nearest subproject build file.

Also at `src/remediate.js:230`.

if (!buildFile) {
return [manifestPath]
}
Comment on lines +225 to +228

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Medium · Catalog fallback is silently skipped

When a target catalog has no nearby Gradle build file, analysisPathsFor returns the catalog path when no build file is found, but match rejects that path because the Gradle provider requires a nearby build file. The catch then skips it, so remediation returns no results instead of performing the advertised fallback or reporting that analysis is impossible.

Do not route the catalog through provider matching in this state; either report the missing build as an error or implement a fallback that can actually analyze it.

Also at src/remediate.js:329-333.

Prompt for AI agents
In `src/remediate.js` at lines 225-228:

**Catalog fallback is silently skipped**

When a target catalog has no nearby Gradle build file, `analysisPathsFor` returns the catalog path when no build file is found, but `match` rejects that path because the Gradle provider requires a nearby build file. The catch then skips it, so remediation returns no results instead of performing the advertised fallback or reporting that analysis is impossible.

Do not route the catalog through provider matching in this state; either report the missing build as an error or implement a fallback that can actually analyze it.

Also at `src/remediate.js:329-333`.


const projects = await discoverGradleSubprojects(path.dirname(buildFile), opts)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟠 High · Subproject dependencies go unreported

When a settings-included subproject has no local build file, or Gradle project listing fails while a root build file exists, discoverGradleSubprojects() returns only projects with their own build files, and analysisPathsFor() treats a nonempty result as complete; when listing fails, it likewise falls back to the root manifest. Dependencies configured for omitted subprojects never reach analysis, so the remediation report misses them.

Discover and analyze every settings-included project, including projects without local build files, and ensure a failed project listing does not silently reduce analysis to the root.

Also at README.md:866, src/remediate.js:231.

Prompt for AI agents
In `src/remediate.js` at line 230:

**Subproject dependencies go unreported**

When a settings-included subproject has no local build file, or Gradle project listing fails while a root build file exists, `discoverGradleSubprojects()` returns only projects with their own build files, and `analysisPathsFor()` treats a nonempty result as complete; when listing fails, it likewise falls back to the root manifest. Dependencies configured for omitted subprojects never reach analysis, so the remediation report misses them.

Discover and analyze every settings-included project, including projects without local build files, and ensure a failed project listing does not silently reduce analysis to the root.

Also at `README.md:866`, `src/remediate.js:231`.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Medium · Gradle discovery can block remediation

When gradle configuration or plugin resolution stalls while listing projects, discoverGradleSubprojects runs Gradle synchronously before analysis, and invokeCommand has no timeout. A Gradle configuration or plugin-resolution process that stalls therefore blocks runRemediation indefinitely before it can return a report.

Run project discovery with a bounded timeout and surface a clear failure rather than waiting indefinitely.

Prompt for AI agents
In `src/remediate.js` at line 230:

**Gradle discovery can block remediation**

When gradle configuration or plugin resolution stalls while listing projects, `discoverGradleSubprojects` runs Gradle synchronously before analysis, and `invokeCommand` has no timeout. A Gradle configuration or plugin-resolution process that stalls therefore blocks `runRemediation` indefinitely before it can return a report.

Run project discovery with a bounded timeout and surface a clear failure rather than waiting indefinitely.

return projects.length > 0 ? projects : [manifestPath]
}

/**
* Resolves a version conflict among candidates. Default: highest version wins.
* @param {string[]} versions
Expand Down Expand Up @@ -289,17 +317,29 @@ export async function runRemediation(targetPath, options = {}) {
continue
}

let provider
try {
provider = match(manifestPath, availableProviders, opts)
} catch {
continue
}
const providerPriority = providers ? providers.split(',').map(p => p.trim()).filter(Boolean) : undefined
const analysisPaths = await analysisPathsFor(manifestPath, manifestType, opts)

// A dependency visible from several projects yields one remediation per analysis.
// Keep a single entry per purl so it is reported and edited once.
/** @type {Map<string, import('./remediation.js').Remediation>} */
const remediationsByPurl = new Map()
for (const analysisPath of analysisPaths) {
let provider
try {
provider = match(analysisPath, availableProviders, opts)
} catch {
continue
}

const analysisReport = await analysis.requestStack(provider, manifestPath, url, false, opts)
const extracted = extractRemediations(analysisReport, {
providerPriority: providers ? providers.split(',').map(p => p.trim()).filter(Boolean) : undefined,
})
const analysisReport = await analysis.requestStack(provider, analysisPath, url, false, opts)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Medium · Catalog audit metadata is replaced

When a version catalog is analyzed through the new project fan-out, analysis.requestStack() receives each project build file, so it encodes that file as the source manifest and labels it build.gradle or build.gradle.kts; the backend receives no version-catalog content for the catalog remediation request.

Preserve the catalog path and content as the audit manifest while separately selecting the project build file used to generate each project's SBOM.

Prompt for AI agents
In `src/remediate.js` at line 335:

**Catalog audit metadata is replaced**

When a version catalog is analyzed through the new project fan-out, `analysis.requestStack()` receives each project build file, so it encodes that file as the source manifest and labels it `build.gradle` or `build.gradle.kts`; the backend receives no version-catalog content for the catalog remediation request.

Preserve the catalog path and content as the audit manifest while separately selecting the project build file used to generate each project's SBOM.

for (const remediation of extractRemediations(analysisReport, { providerPriority })) {
if (!remediationsByPurl.has(remediation.purl)) {
remediationsByPurl.set(remediation.purl, remediation)
}
}
}
const extracted = [...remediationsByPurl.values()].sort((a, b) => a.purl.localeCompare(b.purl))
Comment on lines +325 to +342

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Medium · Conflicting remediation details disappear

When analyses report different fixed versions, vulnerability details, or recommendations for the same dependency PURL, remediationsByPurl keeps the first remediation and discards later reports, so project discovery order determines the fix and the merged remediation omits details from other projects; the catalog can remain vulnerable and callers receive incomplete results.

Merge or resolve all remediations for each PURL across project reports instead of retaining only the first.

Prompt for AI agents
In `src/remediate.js` at lines 325-342:

**Conflicting remediation details disappear**

When analyses report different fixed versions, vulnerability details, or recommendations for the same dependency PURL, `remediationsByPurl` keeps the first remediation and discards later reports, so project discovery order determines the fix and the merged remediation omits details from other projects; the catalog can remain vulnerable and callers receive incomplete results.

Merge or resolve all remediations for each PURL across project reports instead of retaining only the first.


let remediations = excludeMatchers.length === 0
? extracted
Expand Down Expand Up @@ -333,7 +373,9 @@ export async function runRemediation(targetPath, options = {}) {
groupId: remediation.groupId,
artifactId: remediation.artifactId,
newVersion: remediation.fixedInVersion,
reason: 'Dependency not directly declared in the manifest',
reason: manifestType.label === 'toml'
? 'Dependency not declared in the version catalog'
: 'Dependency not directly declared in the manifest',
})
continue
}
Expand Down
20 changes: 20 additions & 0 deletions test/providers/java_gradle_groovy.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,26 @@ suite('testing the java-gradle-groovy data provider', () => {
}).timeout(process.env.GITHUB_ACTIONS ? 40000 : 10000)
})

suite('subproject and empty dependency trees', () => {
[
{ name: 'subproject build file', scenario: 'gradle_multi_project/app' },
{ name: 'empty dependency blocks', scenario: 'empty_dependencies' },
].forEach(({ name, scenario }) => {
test(`verify gradle data provided for stack analysis with scenario ${name}`, async () => {
const dir = `test/providers/tst_manifests/gradle/${scenario}`
const expectedSbom = fs.readFileSync(`${dir}/expected_stack_sbom.json`).toString().trim()
const depTree = fs.readFileSync(`${dir}/depTree.txt`).toString()
const props = fs.readFileSync(`${dir}/gradle.properties`).toString()
const provider = new Java_gradle_groovy()
mockInvokeCommand(provider, depTree, props, '')

const provided = await provider.provideStack(`${dir}/build.gradle`)

expect(JSON.parse(provided.content)).to.deep.equal(JSON.parse(expectedSbom))
}).timeout(10000)
})
})

suite('artifact hash computation', () => {
const testCase = 'deps_with_no_ignore_common_paths'
const dir = `test/providers/tst_manifests/gradle/${testCase}`
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
plugins { id 'java' }

group = 'com.example'
version = '1.0.0'

repositories { mavenCentral() }

// Intentionally no dependencies: exercises empty configuration blocks.
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
> Task :dependencies

compileClasspath - Compile classpath for source set 'main'.
No dependencies

runtimeClasspath - Runtime classpath of source set 'main'.
No dependencies

Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
{
"bomFormat": "CycloneDX",
"specVersion": "1.6",
"version": 1,
"metadata": {
"timestamp": "2023-08-07T00:00:00.000Z",
"component": {
"group": "com.example",
"name": "empty_dependencies",
"version": "1.0.0",
"purl": "pkg:maven/com.example/empty_dependencies@1.0.0",
"type": "application",
"bom-ref": "pkg:maven/com.example/empty_dependencies@1.0.0"
},
"tools": {
"components": [
{
"type": "application",
"name": "trustify-da-javascript-client",
"version": "0.4.0"
}
]
}
},
"components": [],
"dependencies": []
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@

> Task :properties

------------------------------------------------------------
Root project 'empty_dependencies'
------------------------------------------------------------

allprojects: [root project 'empty_dependencies']
group: com.example
name: empty_dependencies
version: 1.0.0
Original file line number Diff line number Diff line change
@@ -1 +1,11 @@
// app build
plugins { id 'java' }

group = 'com.example'
version = '1.0.0'

repositories { mavenCentral() }

dependencies {
implementation 'org.apache.commons:commons-lang3:3.16.0'
implementation 'commons-io:commons-io:2.16.1'
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
> Task :app:dependencies

compileClasspath - Compile classpath for source set 'main'.
+--- org.apache.commons:commons-lang3:3.16.0
\--- commons-io:commons-io:2.16.1

runtimeClasspath - Runtime classpath of source set 'main'.
+--- org.apache.commons:commons-lang3:3.16.0
\--- commons-io:commons-io:2.16.1

Loading
Loading