Skip to content
Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.List;
Expand Down Expand Up @@ -253,22 +254,44 @@
}

@GetMapping("/file")
public ResponseEntity<String> readFile(

Check failure on line 257 in src/main/java/io/github/randomcodespace/iq/api/GraphController.java

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Refactor this method to reduce its Cognitive Complexity from 18 to the 15 allowed.

See more on https://sonarcloud.io/project/issues?id=RandomCodeSpace_codeiq&issues=AZ3AgY0Cqpstt_9Mkeay&open=AZ3AgY0Cqpstt_9Mkeay&pullRequest=65
@RequestParam String path,
@RequestParam(required = false) Integer startLine,
@RequestParam(required = false) Integer endLine) {
Path codebasePath = Path.of(config.getRootPath()).toAbsolutePath().normalize();
Path resolved = codebasePath.resolve(path).normalize();
if (!resolved.startsWith(codebasePath)) {
Path codebaseReal;
try {
codebaseReal = Path.of(config.getRootPath()).toRealPath();
} catch (IOException e) {
return ResponseEntity.status(500)
.contentType(MediaType.TEXT_PLAIN)
.body("Failed to resolve codebase root: " + e.getMessage());

Check warning

Code scanning / CodeQL

Information exposure through an error message Medium

Error information
can be exposed to an external user.
Comment on lines +265 to +267
}
Path candidate = codebaseReal.resolve(path).normalize();
if (!candidate.startsWith(codebaseReal)) {
return ResponseEntity.status(403)
.contentType(MediaType.TEXT_PLAIN)
.body("Path traversal blocked");
}
Path resolvedReal;
try {
resolvedReal = candidate.toRealPath();
} catch (NoSuchFileException e) {

Check warning on line 278 in src/main/java/io/github/randomcodespace/iq/api/GraphController.java

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Replace "e" with an unnamed pattern.

See more on https://sonarcloud.io/project/issues?id=RandomCodeSpace_codeiq&issues=AZ3AgY0Cqpstt_9Mkeaz&open=AZ3AgY0Cqpstt_9Mkeaz&pullRequest=65
return ResponseEntity.notFound().build();
} catch (IOException e) {
return ResponseEntity.status(500)
.contentType(MediaType.TEXT_PLAIN)
.body("Failed to resolve file: " + e.getMessage());

Check warning

Code scanning / CodeQL

Information exposure through an error message Medium

Error information
can be exposed to an external user.
Comment thread
aksOps marked this conversation as resolved.
Dismissed
}
if (!resolvedReal.startsWith(codebaseReal)) {
return ResponseEntity.status(403)
.contentType(MediaType.TEXT_PLAIN)
.body("Path traversal blocked");
}
if (!Files.isRegularFile(resolved)) {
if (!Files.isRegularFile(resolvedReal)) {
return ResponseEntity.notFound().build();
}
try {
String content = Files.readString(resolved, StandardCharsets.UTF_8);
String content = Files.readString(resolvedReal, StandardCharsets.UTF_8);
if (startLine != null || endLine != null) {
String[] lines = content.split("\n", -1);
int start = (startLine != null ? startLine : 1);
Expand Down
12 changes: 9 additions & 3 deletions src/main/java/io/github/randomcodespace/iq/mcp/McpTools.java
Original file line number Diff line number Diff line change
Expand Up @@ -385,9 +385,15 @@ public String readFile(
@McpToolParam(description = "Start line number, 1-based (optional — omit to read entire file)", required = false) Integer startLine,
@McpToolParam(description = "End line number, 1-based inclusive (optional — omit to read to end)", required = false) Integer endLine) {
try {
Path root = Path.of(config.getRootPath()).toAbsolutePath().normalize();
Path resolved = root.resolve(filePath).normalize();
// Path traversal protection
Path root = Path.of(config.getRootPath()).toRealPath();
Path candidate = root.resolve(filePath).normalize();
// Lexical traversal guard (rejects ../ before any filesystem touch)
if (!candidate.startsWith(root)) {
return toJson(Map.of(PROP_ERROR, "Path traversal detected"));
}
// Follow symlinks and re-check so an in-repo symlink pointing outside the
// codebase (e.g. link -> /etc/passwd) cannot be used to exfiltrate files.
Path resolved = candidate.toRealPath();
if (!resolved.startsWith(root)) {
return toJson(Map.of(PROP_ERROR, "Path traversal detected"));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -557,6 +557,49 @@
.andExpect(content().string("aaa\nbbb\nccc"));
}

@Test
void readFileShouldRejectSymlinkEscapingRoot(@TempDir Path tempDir) throws Exception {
Path target = Files.createTempFile("codeiq-escape-", ".txt");
try {
Files.writeString(target, "TOP SECRET", StandardCharsets.UTF_8);
Path link = tempDir.resolve("leak.txt");
try {
Files.createSymbolicLink(link, target.toAbsolutePath());
} catch (UnsupportedOperationException | java.io.IOException unsupported) {

Check warning on line 568 in src/test/java/io/github/randomcodespace/iq/api/GraphControllerTest.java

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Replace "unsupported" with an unnamed pattern.

See more on https://sonarcloud.io/project/issues?id=RandomCodeSpace_codeiq&issues=AZ3AgY2pqpstt_9Mkea0&open=AZ3AgY2pqpstt_9Mkea0&pullRequest=65
// Filesystem does not support symlinks (e.g. Windows without privilege) — skip.
return;
}
CodeIqConfigTestSupport.override(config).rootPath(tempDir.toAbsolutePath().toString()).done();
var controller = new GraphController(queryService, config);
var fileMvc = MockMvcBuilders.standaloneSetup(controller).build();

fileMvc.perform(get("/api/file").param("path", "leak.txt"))
.andExpect(status().isForbidden())
.andExpect(content().string("Path traversal blocked"));
} finally {
Files.deleteIfExists(target);
}
}

@Test
void readFileShouldAllowInRepoSymlink(@TempDir Path tempDir) throws Exception {
Path real = tempDir.resolve("real.txt");
Files.writeString(real, "in-repo", StandardCharsets.UTF_8);
Path link = tempDir.resolve("alias.txt");
try {
Files.createSymbolicLink(link, real);
} catch (UnsupportedOperationException | java.io.IOException unsupported) {

Check warning on line 591 in src/test/java/io/github/randomcodespace/iq/api/GraphControllerTest.java

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Replace "unsupported" with an unnamed pattern.

See more on https://sonarcloud.io/project/issues?id=RandomCodeSpace_codeiq&issues=AZ3AgY2pqpstt_9Mkea1&open=AZ3AgY2pqpstt_9Mkea1&pullRequest=65
return;
}
CodeIqConfigTestSupport.override(config).rootPath(tempDir.toAbsolutePath().toString()).done();
var controller = new GraphController(queryService, config);
var fileMvc = MockMvcBuilders.standaloneSetup(controller).build();

fileMvc.perform(get("/api/file").param("path", "alias.txt"))
.andExpect(status().isOk())
.andExpect(content().string("in-repo"));
}

// POST /api/analyze removed — API is read-only

// --- /api/file-tree ---
Expand Down
43 changes: 43 additions & 0 deletions src/test/java/io/github/randomcodespace/iq/mcp/McpToolsTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -524,4 +524,47 @@

assertEquals("line2\nline3", result);
}

@Test
void readFileShouldRejectSymlinkEscapingRoot(@TempDir Path tempDir) throws IOException {
CodeIqConfigTestSupport.override(config).rootPath(tempDir.toString()).done();

Path target = Files.createTempFile("codeiq-escape-", ".txt");
try {
Files.writeString(target, "TOP SECRET");
Path link = tempDir.resolve("leak.txt");
try {
Files.createSymbolicLink(link, target.toAbsolutePath());
} catch (UnsupportedOperationException | IOException unsupported) {

Check warning on line 538 in src/test/java/io/github/randomcodespace/iq/mcp/McpToolsTest.java

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Replace "unsupported" with an unnamed pattern.

See more on https://sonarcloud.io/project/issues?id=RandomCodeSpace_codeiq&issues=AZ3AgY29qpstt_9Mkea2&open=AZ3AgY29qpstt_9Mkea2&pullRequest=65
// Filesystem does not support symlinks (e.g. Windows without privilege) — skip.
return;
}

String result = mcpTools.readFile("leak.txt", null, null);

assertFalse(result.contains("TOP SECRET"),
"Symlink target contents must not leak through read_file");
Map<String, Object> parsed = parseJson(result);
assertEquals("Path traversal detected", parsed.get("error"));
} finally {
Files.deleteIfExists(target);
}
}

@Test
void readFileShouldAllowInRepoSymlink(@TempDir Path tempDir) throws IOException {
CodeIqConfigTestSupport.override(config).rootPath(tempDir.toString()).done();
Path real = tempDir.resolve("real.txt");
Files.writeString(real, "in-repo");
Path link = tempDir.resolve("alias.txt");
try {
Files.createSymbolicLink(link, real);
} catch (UnsupportedOperationException | IOException unsupported) {

Check warning on line 562 in src/test/java/io/github/randomcodespace/iq/mcp/McpToolsTest.java

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Replace "unsupported" with an unnamed pattern.

See more on https://sonarcloud.io/project/issues?id=RandomCodeSpace_codeiq&issues=AZ3AgY29qpstt_9Mkea3&open=AZ3AgY29qpstt_9Mkea3&pullRequest=65
return;
}

String result = mcpTools.readFile("alias.txt", null, null);

assertEquals("in-repo", result);
}
}
Loading