Skip to content

Commit e47a887

Browse files
Merge pull request #206 from refactorfirst/Address-OpenVuln-findings
#205 Address OpenVuln findings
2 parents 65d3bef + 1642746 commit e47a887

24 files changed

Lines changed: 5608 additions & 133 deletions

File tree

‎change-proneness-ranker/src/main/java/org/hjug/git/GitLogReader.java‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,12 @@ public String getRepoUrl() throws IOException {
9696
return "";
9797
}
9898

99+
// Only web URLs may be embedded in generated reports as source links;
100+
// anything else (javascript:, data:, file:, ...) is rejected outright.
101+
if (!originUrl.startsWith("https://") && !originUrl.startsWith("http://")) {
102+
return "";
103+
}
104+
99105
repoUrl = originUrl.replace(".git", "");
100106

101107
if (repoUrl.contains("gitlab")) {
@@ -105,7 +111,11 @@ public String getRepoUrl() throws IOException {
105111
} else {
106112
repoUrl = repoUrl + "/blob/" + getCurrentCommitHash() + "/";
107113
}
108-
return repoUrl;
114+
115+
// Keep only RFC 3986 URL characters: drops every char that is markup- or
116+
// JS-significant outside a URL (space, ", ', <, >, `, {, }, \), so the value
117+
// cannot break out of an attribute or a <script> template literal downstream.
118+
return repoUrl.replaceAll("[^A-Za-z0-9._~:/?#\\[\\]@!$&'()*+,;=%-]", "");
109119
}
110120

111121
// log --follow implementation may be worth adopting in the future

‎change-proneness-ranker/src/test/java/org/hjug/git/GitLogReaderGetRepoUrlTest.java‎

Lines changed: 125 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package org.hjug.git;
22

33
import static org.junit.jupiter.api.Assertions.assertEquals;
4+
import static org.junit.jupiter.api.Assertions.assertFalse;
45
import static org.junit.jupiter.api.Assertions.assertTrue;
56

67
import java.io.File;
@@ -100,4 +101,128 @@ void testGetRepoUrlWithNoOrigin() throws Exception {
100101
assertEquals("", repoUrl);
101102
}
102103
}
104+
105+
@Test
106+
void testGetRepoUrl_returnsEmpty_whenOriginUrlIsJavascriptScheme() throws Exception {
107+
git.remoteAdd()
108+
.setName("origin")
109+
.setUri(new URIish("javascript:alert(1)"))
110+
.call();
111+
112+
try (GitLogReader gitLogReader = new GitLogReader(projectBaseDir)) {
113+
String repoUrl = gitLogReader.getRepoUrl();
114+
assertEquals("", repoUrl, "javascript: scheme should be rejected");
115+
}
116+
}
117+
118+
@Test
119+
void testGetRepoUrl_returnsEmpty_whenOriginUrlIsDataScheme() throws Exception {
120+
git.remoteAdd()
121+
.setName("origin")
122+
.setUri(new URIish("data:text/html,<script>alert(1)</script>"))
123+
.call();
124+
125+
try (GitLogReader gitLogReader = new GitLogReader(projectBaseDir)) {
126+
String repoUrl = gitLogReader.getRepoUrl();
127+
assertEquals("", repoUrl, "data: scheme should be rejected");
128+
}
129+
}
130+
131+
@Test
132+
void testGetRepoUrl_returnsEmpty_whenOriginUrlIsFileScheme() throws Exception {
133+
git.remoteAdd()
134+
.setName("origin")
135+
.setUri(new URIish("file:///etc/passwd"))
136+
.call();
137+
138+
try (GitLogReader gitLogReader = new GitLogReader(projectBaseDir)) {
139+
String repoUrl = gitLogReader.getRepoUrl();
140+
assertEquals("", repoUrl, "file: scheme should be rejected");
141+
}
142+
}
143+
144+
@Test
145+
void testGetRepoUrl_returnsEmpty_whenOriginUrlIsNotHttpOrHttps() throws Exception {
146+
git.remoteAdd()
147+
.setName("origin")
148+
.setUri(new URIish("ssh://git@example.com/repo.git"))
149+
.call();
150+
151+
try (GitLogReader gitLogReader = new GitLogReader(projectBaseDir)) {
152+
String repoUrl = gitLogReader.getRepoUrl();
153+
assertEquals("", repoUrl, "ssh: scheme should be rejected");
154+
}
155+
}
156+
157+
@Test
158+
void testGetRepoUrl_sanitizesUrl_removingMarkupCharacters() throws Exception {
159+
git.getRepository().getConfig().setString("remote", "origin", "url", "https://example.com/repo\"<unsafe>.git");
160+
git.getRepository().getConfig().save();
161+
162+
try (GitLogReader gitLogReader = new GitLogReader(projectBaseDir)) {
163+
String repoUrl = gitLogReader.getRepoUrl();
164+
assertTrue(repoUrl.startsWith("https://example.com/repounsafe"));
165+
assertFalse(repoUrl.contains("\""), "URL must not retain quotes: " + repoUrl);
166+
assertFalse(repoUrl.contains("<"), "URL must not retain angle brackets: " + repoUrl);
167+
}
168+
}
169+
170+
@Test
171+
void testGetRepoUrl_allowsValidHttpsUrl() throws Exception {
172+
git.remoteAdd()
173+
.setName("origin")
174+
.setUri(new URIish("https://github.com/user/repo.git"))
175+
.call();
176+
177+
try (GitLogReader gitLogReader = new GitLogReader(projectBaseDir)) {
178+
String repoUrl = gitLogReader.getRepoUrl();
179+
assertTrue(
180+
repoUrl.startsWith("https://github.com/user/repo/blob/"),
181+
"Valid HTTPS URL should be allowed: " + repoUrl);
182+
}
183+
}
184+
185+
@Test
186+
void testGetRepoUrl_allowsValidHttpUrl() throws Exception {
187+
git.remoteAdd()
188+
.setName("origin")
189+
.setUri(new URIish("http://example.com/repo.git"))
190+
.call();
191+
192+
try (GitLogReader gitLogReader = new GitLogReader(projectBaseDir)) {
193+
String repoUrl = gitLogReader.getRepoUrl();
194+
assertTrue(
195+
repoUrl.startsWith("http://example.com/repo/blob/"),
196+
"Valid HTTP URL should be allowed: " + repoUrl);
197+
}
198+
}
199+
200+
@Test
201+
void testGetRepoUrl_stripsGitSuffix() throws Exception {
202+
git.remoteAdd()
203+
.setName("origin")
204+
.setUri(new URIish("https://github.com/user/repo.git"))
205+
.call();
206+
207+
try (GitLogReader gitLogReader = new GitLogReader(projectBaseDir)) {
208+
String repoUrl = gitLogReader.getRepoUrl();
209+
assertTrue(!repoUrl.contains(".git"), "URL should not contain .git suffix");
210+
}
211+
}
212+
213+
@Test
214+
void testGetRepoUrl_appendsBlobPath_forNonGithubHosts() throws Exception {
215+
git.remoteAdd()
216+
.setName("origin")
217+
.setUri(new URIish("https://example.com/user/repo.git"))
218+
.call();
219+
220+
try (GitLogReader gitLogReader = new GitLogReader(projectBaseDir)) {
221+
String repoUrl = gitLogReader.getRepoUrl();
222+
String commitHash = git.log().call().iterator().next().getName();
223+
assertTrue(
224+
repoUrl.endsWith("/blob/" + commitHash + "/"),
225+
"Non-GitHub hosts should get /blob/ path: " + repoUrl);
226+
}
227+
}
103228
}

‎cli/src/main/java/org/hjug/refactorfirst/ReportCommand.java‎

Lines changed: 45 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
import org.apache.maven.project.MavenProject;
1212
import org.hjug.refactorfirst.report.CsvReport;
1313
import org.hjug.refactorfirst.report.HtmlReport;
14+
import org.hjug.refactorfirst.report.ReportWriter;
1415
import org.hjug.refactorfirst.report.SimpleHtmlReport;
1516
import org.hjug.refactorfirst.report.json.JsonReportExecutor;
1617
import picocli.CommandLine.Command;
@@ -92,46 +93,52 @@ public Integer call() {
9293
// TODO: add support for inferring arguments from gradle properties
9394
inferArgumentsFromMavenProject();
9495
populateDefaultArguments();
95-
switch (reportType) {
96-
case SIMPLE_HTML:
97-
SimpleHtmlReport simpleHtmlReport = new SimpleHtmlReport();
98-
simpleHtmlReport.execute(
99-
backEdgeAnalysisCount,
100-
analyzeCycles,
101-
showDetails,
102-
minifiyHtml,
103-
excludeTests,
104-
testSourceDirectory,
105-
projectName,
106-
projectVersion,
107-
baseDir,
108-
outputDirectory);
109-
return 0;
110-
case HTML:
111-
HtmlReport htmlReport = new HtmlReport();
112-
htmlReport.execute(
113-
backEdgeAnalysisCount,
114-
analyzeCycles,
115-
showDetails,
116-
minifiyHtml,
117-
excludeTests,
118-
testSourceDirectory,
119-
projectName,
120-
projectVersion,
121-
baseDir,
122-
outputDirectory);
123-
return 0;
124-
case JSON:
125-
JsonReportExecutor jsonReportExecutor = new JsonReportExecutor();
126-
jsonReportExecutor.execute(baseDir, outputDirectory);
127-
return 0;
128-
case CSV:
129-
CsvReport csvReport = new CsvReport();
130-
csvReport.execute(showDetails, projectName, projectVersion, outputDirectory, baseDir);
131-
return 0;
96+
try {
97+
outputDirectory = ReportWriter.containReportDirectory(baseDir, outputDirectory);
98+
switch (reportType) {
99+
case SIMPLE_HTML:
100+
SimpleHtmlReport simpleHtmlReport = new SimpleHtmlReport();
101+
simpleHtmlReport.execute(
102+
backEdgeAnalysisCount,
103+
analyzeCycles,
104+
showDetails,
105+
minifiyHtml,
106+
excludeTests,
107+
testSourceDirectory,
108+
projectName,
109+
projectVersion,
110+
baseDir,
111+
outputDirectory);
112+
return 0;
113+
case HTML:
114+
HtmlReport htmlReport = new HtmlReport();
115+
htmlReport.execute(
116+
backEdgeAnalysisCount,
117+
analyzeCycles,
118+
showDetails,
119+
minifiyHtml,
120+
excludeTests,
121+
testSourceDirectory,
122+
projectName,
123+
projectVersion,
124+
baseDir,
125+
outputDirectory);
126+
return 0;
127+
case JSON:
128+
JsonReportExecutor jsonReportExecutor = new JsonReportExecutor();
129+
jsonReportExecutor.execute(baseDir, outputDirectory);
130+
return 0;
131+
case CSV:
132+
CsvReport csvReport = new CsvReport();
133+
csvReport.execute(showDetails, projectName, projectVersion, outputDirectory, baseDir);
134+
return 0;
135+
}
136+
} catch (IllegalArgumentException | ReportWriter.ReportWriteException e) {
137+
log.error("Report generation failed: {}", e.getMessage());
138+
return 1;
132139
}
133140

134-
return 0;
141+
return 1;
135142
}
136143

137144
private void populateDefaultArguments() {
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
package org.hjug.refactorfirst;
2+
3+
import static org.junit.jupiter.api.Assertions.assertEquals;
4+
import static org.junit.jupiter.api.Assertions.assertFalse;
5+
import static org.junit.jupiter.api.Assumptions.assumeTrue;
6+
7+
import java.lang.reflect.Field;
8+
import java.nio.file.Files;
9+
import java.nio.file.Path;
10+
import org.junit.jupiter.api.Test;
11+
import org.junit.jupiter.api.io.TempDir;
12+
13+
class ReportCommandTest {
14+
15+
@Test
16+
void call_returnsFailureWhenOutputPathContainsSymlink(@TempDir Path tempDir) throws Exception {
17+
Path target = Files.createDirectory(tempDir.resolve("target"));
18+
Path link = tempDir.resolve("link");
19+
try {
20+
Files.createSymbolicLink(link, target);
21+
} catch (UnsupportedOperationException e) {
22+
assumeTrue(false, "Symbolic links not supported on this platform");
23+
}
24+
25+
ReportCommand command = new ReportCommand();
26+
setField(command, "baseDir", tempDir.toFile());
27+
setField(command, "outputDirectory", "link/reports");
28+
setField(command, "reportType", ReportType.CSV);
29+
30+
assertEquals(1, command.call());
31+
}
32+
33+
@Test
34+
void call_returnsFailureWhenOutputPathTraversesOutsideBase(@TempDir Path tempDir) throws Exception {
35+
Path baseDirectory = Files.createDirectory(tempDir.resolve("project"));
36+
ReportCommand command = new ReportCommand();
37+
setField(command, "baseDir", baseDirectory.toFile());
38+
setField(command, "outputDirectory", "../escape");
39+
setField(command, "reportType", ReportType.CSV);
40+
41+
assertEquals(1, command.call());
42+
assertFalse(Files.exists(tempDir.resolve("escape")));
43+
}
44+
45+
private static void setField(ReportCommand command, String name, Object value) throws ReflectiveOperationException {
46+
Field field = ReportCommand.class.getDeclaredField(name);
47+
field.setAccessible(true);
48+
field.set(command, value);
49+
}
50+
}

‎cost-benefit-calculator/src/main/java/org/hjug/cbc/CostBenefitCalculator.java‎

Lines changed: 32 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@
55

66
import java.io.File;
77
import java.io.IOException;
8+
import java.net.URI;
9+
import java.net.URISyntaxException;
810
import java.nio.file.Files;
911
import java.nio.file.Path;
1012
import java.util.*;
@@ -139,11 +141,18 @@ public List<DisharmonyInstance> getClassDisharmonies(CodebaseGraphDTO codebaseGr
139141

140142
List<DisharmonyInstance> instances = raw.stream()
141143
.map(d -> {
144+
String filePath = classToSourceFilePathMapping.get(d.getClassName());
145+
if (filePath == null && d.getClassName().contains("$")) {
146+
filePath = classToSourceFilePathMapping.get(
147+
d.getClassName().substring(0, d.getClassName().indexOf("$")));
148+
}
149+
if (filePath == null) {
150+
log.warn("No source file mapping found for class disharmony in class: {}", d.getClassName());
151+
}
142152
DisharmonyInstance instance = new DisharmonyInstance(
143153
disharmonyType,
144154
d.getClassName(),
145-
canonicaliseURIStringForRepoLookup(
146-
d.getMetrics().getSourceFilePath().replace("\\", "/")),
155+
filePath,
147156
d.getMetrics().getPackageName(),
148157
null,
149158
new ArrayList<>(d.getMetricValues()));
@@ -460,9 +469,27 @@ private String getFileName(RuleViolation violation) {
460469
}
461470

462471
String canonicaliseURIStringForRepoLookup(String uriString) {
463-
if (repositoryPath.startsWith("/") || repositoryPath.startsWith("\\")) {
464-
return uriString.replace("file://" + repositoryPath.replace("\\", "/") + "/", "");
472+
return canonicaliseURIStringForRepoLookup(repositoryPath, uriString);
473+
}
474+
475+
static String canonicaliseURIStringForRepoLookup(String repositoryPath, String uriString) {
476+
try {
477+
URI fileUri = new URI(uriString);
478+
if (!"file".equalsIgnoreCase(fileUri.getScheme())) {
479+
return uriString;
480+
}
481+
if (fileUri.isOpaque()) {
482+
return fileUri.getSchemeSpecificPart().replace("\\", "/");
483+
}
484+
485+
Path repository = Path.of(repositoryPath).toAbsolutePath().normalize();
486+
Path file = Path.of(fileUri).toAbsolutePath().normalize();
487+
if (file.startsWith(repository)) {
488+
return repository.relativize(file).toString().replace("\\", "/");
489+
}
490+
} catch (IllegalArgumentException | URISyntaxException e) {
491+
log.debug("Unable to canonicalize file URI {}", uriString, e);
465492
}
466-
return uriString.replace("file:///" + repositoryPath.replace("\\", "/") + "/", "");
493+
return uriString;
467494
}
468495
}

‎cost-benefit-calculator/src/test/java/org/hjug/cbc/CostBenefitCalculatorTest.java‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,13 @@ public void tearDown() {
4343
repository.close();
4444
}
4545

46+
@Test
47+
void canonicaliseURIStringForRepoLookup_relativizesAbsoluteUnixPath() {
48+
Assertions.assertEquals(
49+
"src/Foo.java",
50+
CostBenefitCalculator.canonicaliseURIStringForRepoLookup("/tmp/repo", "file:///tmp/repo/src/Foo.java"));
51+
}
52+
4653
@Test
4754
void testCBOViolation() throws IOException, GitAPIException, InterruptedException {
4855
// Has CBO violation

0 commit comments

Comments
 (0)