Skip to content

Vulnerable sample for Action test#2

Open
souro1212 wants to merge 1 commit intomainfrom
feat/vuln-demo-1757571343
Open

Vulnerable sample for Action test#2
souro1212 wants to merge 1 commit intomainfrom
feat/vuln-demo-1757571343

Conversation

@souro1212
Copy link
Member

@souro1212 souro1212 commented Sep 11, 2025

This PR intentionally adds risky patterns for testing ai-secure-code-review-action.

Summary by CodeRabbit

  • New Features
    • Introduced a new REST API endpoint: GET /items.
    • Supports a query parameter: sort.
    • Returns a simple confirmation response to indicate a successful request.

@coderabbitai
Copy link

coderabbitai bot commented Sep 11, 2025

Walkthrough

Introduces a Spring REST controller in DemoController with a new GET /items endpoint. The items method accepts a sort request parameter, calls Class.forName on it, returns "ok", and declares throws Exception. No additional usage of the loaded class is present.

Changes

Cohort / File(s) Summary of Changes
REST controller and endpoint
src/main/java/com/acme/DemoController.java
Converted to Spring REST controller; added GET /items endpoint. Method public String items(@RequestParam String sort) throws Exception calls Class.forName(sort) and returns "ok".

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor C as Client
  participant DC as DemoController
  participant J as JVM Reflection

  C->>DC: GET /items?sort=<className>
  DC->>J: Class.forName(sort)
  alt Class found
    J-->>DC: Class<?> loaded
    DC-->>C: "ok"
  else Class not found or error
    J-->>DC: throws Exception
    DC-->>C: Propagated error (exception)
  end
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Pre-merge checks (2 passed, 1 warning)

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The title "Vulnerable sample for Action test" is concise and directly reflects the PR objective of adding an intentionally vulnerable sample for testing, so it accurately summarizes the primary intent of the changeset.

Poem

A whisker twitch, a GET’s delight,
I hop to /items, ears upright.
You whisper “sort,” I fetch a class—
Reflection’s warren, swift to pass.
With thump of paws, I chirp “ok,”
Then bound along my Springtime way. 🐇✨

✨ Finishing touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feat/vuln-demo-1757571343

Comment @coderabbitai help to get the list of available commands and usage tips.

@github-actions
Copy link

🔐 Secure Code Review (AI)

Risk Summary: High (1), Medium (1)

  1. Finding: Unsafe Class Loading

    • Why it matters: The use of Class.forName(sort) allows for arbitrary class loading based on user input. This can lead to Remote Code Execution (RCE) if an attacker can control the sort parameter to load malicious classes.
    • Evidence (diff lines):
      Class<?> clazz = Class.forName(sort);
    • Fix (concrete): Validate the sort parameter against a whitelist of allowed class names or avoid using Class.forName with user input entirely. For example:
      if (!isValidSortParameter(sort)) {
          throw new IllegalArgumentException("Invalid sort parameter");
      }
  2. Finding: Lack of Input Validation

    • Why it matters: The sort parameter is directly taken from user input without any validation or sanitization, which can lead to injection attacks or unexpected behavior.
    • Evidence (diff lines):
      public String items(@RequestParam String sort) throws Exception {
    • Fix (concrete): Implement input validation for the sort parameter to ensure it only contains expected values (e.g., specific strings or patterns). For example:
      if (!sort.matches("^[a-zA-Z0-9]+$")) {
          throw new IllegalArgumentException("Invalid sort parameter");
      }

Safeguards Checklist:

  • Input validation: Fail
  • Output encoding: N/A
  • Authentication/Authorization checks: N/A
  • Error handling: Fail
  • Secure coding practices: Fail

The diff is small and focused, but the issues identified pose significant security risks that need to be addressed immediately.


Models can make mistakes. Verify before merging.

@secure-code-warrior-for-github

Micro-Learning Topic: Injection attack (Detected by phrase)

Matched on "injection attack"

Injection flaws, such as SQL, NoSQL, OS, and LDAP injection, occur when untrusted data is sent to an interpreter as part of a command or query. The attacker’s hostile data can trick the interpreter into executing unintended commands or accessing data without proper authorization. Source: https://www.owasp.org/index.php/Category:OWASP_Top_Ten_Project

Try a challenge in Secure Code Warrior

Helpful references

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (1)
src/main/java/com/acme/DemoController.java (1)

4-4: Declare an explicit content type for the endpoint.

Helps clients and avoids ambiguous defaults for String responses.

-  @GetMapping("/items")
+  @GetMapping(value = "/items", produces = "text/plain")
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between eadf57b and be0c6ad.

📒 Files selected for processing (1)
  • src/main/java/com/acme/DemoController.java (1 hunks)
🔇 Additional comments (1)
src/main/java/com/acme/DemoController.java (1)

1-9: Unsafe reflection — validate/whitelist or remove Class.forName(sort)

DemoController.java calls Class.forName(sort) on an untrusted @RequestParam (src/main/java/com/acme/DemoController.java:1-9) — replace reflection with a whitelist or remove it.

Re-run a repo-wide scan (previous rg skipped files) to find other occurrences:

rg -nP -C2 --hidden --no-ignore 'Class\.forName\s*\(|ClassLoader\s*\.\s*getSystemClassLoader\s*\(' -g '!**/target/**' -g '!**/build/**'

@@ -1,2 +1,9 @@
// safe baseline
public class DemoController {}
import org.springframework.web.bind.annotation.*;
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Missing package declaration; class won’t compile under src/main/java/com/acme. Also replace wildcard import and add required imports.

Add the package and explicit imports (needed for the fix below).

+package com.acme;
-import org.springframework.web.bind.annotation.*;
+import org.springframework.http.ResponseEntity;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.RequestParam;
+import org.springframework.web.bind.annotation.RestController;
+import java.util.Set;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
import org.springframework.web.bind.annotation.*;
package com.acme;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.Set;
🤖 Prompt for AI Agents
In src/main/java/com/acme/DemoController.java at lines 1-1, add the package
declaration "package com.acme;" at the top and replace the wildcard import with
explicit Spring MVC imports; e.g., import
org.springframework.web.bind.annotation.RestController; import
org.springframework.web.bind.annotation.RequestMapping; import
org.springframework.web.bind.annotation.GetMapping; import
org.springframework.web.bind.annotation.PostMapping; import
org.springframework.web.bind.annotation.PathVariable; import
org.springframework.web.bind.annotation.RequestBody; and any other specific
annotations or types used in the file (plus import
org.springframework.http.ResponseEntity if you return ResponseEntity). Ensure
the package line is the first statement and only the needed imports are listed
instead of the wildcard.

Comment on lines +5 to +6
Class<?> clazz = Class.forName(sort);
return "ok";
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Uncontrolled reflection: Class.forName on user input is a critical vulnerability (classloader injection).

A user can cause arbitrary classes to load and run static initializers (DoS/side effects). Remove reflection and validate input via an allowlist, returning proper HTTP status.

-  public String items(@RequestParam String sort) throws Exception {
-    Class<?> clazz = Class.forName(sort);
-    return "ok";
-  }
+  public ResponseEntity<String> items(
+      @RequestParam(name = "sort", required = false, defaultValue = "name") String sort) {
+    // Allow-list acceptable sort keys only; do NOT reflectively load anything from user input.
+    Set<String> allowed = Set.of("name", "price", "createdAt");
+    if (!allowed.contains(sort)) {
+      return ResponseEntity.badRequest().body("invalid sort");
+    }
+    return ResponseEntity.ok("ok");
+  }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
public String items(@RequestParam String sort) throws Exception {
Class<?> clazz = Class.forName(sort);
public ResponseEntity<String> items(
@RequestParam(name = "sort", required = false, defaultValue = "name") String sort) {
// Allow-list acceptable sort keys only; do NOT reflectively load anything from user input.
Set<String> allowed = Set.of("name", "price", "createdAt");
if (!allowed.contains(sort)) {
return ResponseEntity.badRequest().body("invalid sort");
}
return ResponseEntity.ok("ok");
}
🤖 Prompt for AI Agents
In src/main/java/com/acme/DemoController.java around lines 5-6, the code calls
Class.forName(sort) directly on user-provided input which enables uncontrolled
reflection and classloader injection; replace this by validating the incoming
'sort' parameter against a strict allowlist of permitted sort keys (e.g., map of
allowed names to concrete comparator/strategy classes or enums), do not call
Class.forName on raw input, and if the value is not in the allowlist return an
appropriate HTTP error (400 or 403) rather than loading a class; implement the
mapping server-side so only known, safe implementations are used and remove any
dynamic class loading or execution triggered by user input.

@secure-code-warrior-for-github

Micro-Learning Topic: External entity injection (Detected by phrase)

Matched on "xxE"

What is this? (2min video)

An XML External Entity attack is a type of attack against an application that parses XML input. This attack occurs when XML input containing a reference to an external entity is processed by a weakly configured XML parser. This attack may lead to the disclosure of confidential data, denial of service, server-side request forgery, port scanning from the perspective of the machine where the parser is located, and other system impacts.

Try a challenge in Secure Code Warrior

Helpful references

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant