Skip to content

Commit cdfa8ba

Browse files
Fix CodeRabbit issues in PR #206
1 parent dc27bb6 commit cdfa8ba

20 files changed

Lines changed: 756 additions & 208 deletions

File tree

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

Lines changed: 6 additions & 12 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;
@@ -155,21 +156,14 @@ void testGetRepoUrl_returnsEmpty_whenOriginUrlIsNotHttpOrHttps() throws Exceptio
155156

156157
@Test
157158
void testGetRepoUrl_sanitizesUrl_removingMarkupCharacters() throws Exception {
158-
// URL with various markup characters that could be used for XSS
159-
git.remoteAdd()
160-
.setName("origin")
161-
.setUri(new URIish("https://example.com/repo.git"))
162-
.call();
159+
git.getRepository().getConfig().setString("remote", "origin", "url", "https://example.com/repo\"<unsafe>.git");
160+
git.getRepository().getConfig().save();
163161

164-
// Manually set a config with markup characters (simulating attacker-controlled config)
165-
// We can't easily test this through the public API since getOriginUrl() reads from config
166-
// But we can test the sanitization logic directly by checking the behavior
167162
try (GitLogReader gitLogReader = new GitLogReader(projectBaseDir)) {
168163
String repoUrl = gitLogReader.getRepoUrl();
169-
// The URL should only contain RFC 3986 allowed characters
170-
assertTrue(
171-
repoUrl.matches("[A-Za-z0-9._~:/?#\\[\\]@!$&'()*+,;=%-]*"),
172-
"URL should only contain RFC 3986 characters: " + repoUrl);
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);
173167
}
174168
}
175169

‎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: 21 additions & 14 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.*;
@@ -467,21 +469,26 @@ private String getFileName(RuleViolation violation) {
467469
}
468470

469471
String canonicaliseURIStringForRepoLookup(String uriString) {
470-
String normalizedRepoPath = repositoryPath.replace("\\", "/");
471-
// Handle both absolute (file:///C:/...) and relative (file:...) URIs
472-
if (uriString.startsWith("file:///")) {
473-
// Absolute path URI
474-
return uriString.replace("file:///" + normalizedRepoPath + "/", "");
475-
} else if (uriString.startsWith("file://")) {
476-
// Absolute path URI (alternative format)
477-
return uriString.replace("file://" + normalizedRepoPath + "/", "");
478-
} else if (uriString.startsWith("file:")) {
479-
// Relative path URI - make it relative to repo root
480-
String relativePath = uriString.substring("file:".length());
481-
if (relativePath.startsWith("/")) {
482-
relativePath = relativePath.substring(1);
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("\\", "/");
483489
}
484-
return relativePath;
490+
} catch (IllegalArgumentException | URISyntaxException e) {
491+
log.debug("Unable to canonicalize file URI {}", uriString, e);
485492
}
486493
return uriString;
487494
}

‎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

‎graph-data-generator/src/main/java/org/hjug/gdg/GraphDataGenerator.java‎

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ public String generateBubbleChartData(
4242
RankedDisharmony rankedDisharmony = rankedDisharmonies.get(i);
4343
chartData.append("[");
4444
chartData.append("'");
45-
chartData.append(rankedDisharmony.getFileName());
45+
chartData.append(escapeJavaScriptString(rankedDisharmony.getFileName()));
4646
chartData.append("',");
4747
chartData.append(rankedDisharmony.getEffortRank());
4848
chartData.append(",");
@@ -58,4 +58,16 @@ public String generateBubbleChartData(
5858
}
5959
return chartData.toString();
6060
}
61+
62+
static String escapeJavaScriptString(String value) {
63+
if (value == null) {
64+
return "";
65+
}
66+
return value.replace("\\", "\\\\")
67+
.replace("'", "\\'")
68+
.replace("\n", "\\n")
69+
.replace("\r", "\\r")
70+
.replace("<", "\\u003C")
71+
.replace(">", "\\u003E");
72+
}
6173
}

‎graph-data-generator/src/test/java/org/hjug/gdg/GraphDataGeneratorTest.java‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,23 @@ void generateBubbleChartDataForTwoPoints() {
7979
assertTrue(data.startsWith("[ 'ID', 'Effort', 'Change Proneness', 'Priority', 'Priority (Visual)']"));
8080
}
8181

82+
@Test
83+
void generateBubbleChartData_escapesScriptClosingSequence() {
84+
RankedDisharmony disharmony = makeRankedDisharmony(1);
85+
disharmony.setFileName("</script><script>alert(1)</script>");
86+
87+
String data = gen.generateBubbleChartData(List.of(disharmony), 1, "Effort");
88+
89+
assertFalse(data.contains("</script>"));
90+
assertTrue(data.contains("\\u003C/script\\u003E"));
91+
}
92+
93+
@Test
94+
void escapeJavaScriptString_escapesQuotesBackslashesAndLineBreaks() {
95+
assertEquals("a\\\\b\\'c\\nd\\re", GraphDataGenerator.escapeJavaScriptString("a\\b'c\nd\re"));
96+
assertEquals("", GraphDataGenerator.escapeJavaScriptString(null));
97+
}
98+
8299
// ── helper ─────────────────────────────────────────────────────────────────
83100

84101
private RankedDisharmony makeRankedDisharmony(int priority) {

0 commit comments

Comments
 (0)