Skip to content

Vulnerable sample for Action test#2

Open
souro1212 wants to merge 1 commit into
mainfrom
feat/vuln-demo-1757571326
Open

Vulnerable sample for Action test#2
souro1212 wants to merge 1 commit into
mainfrom
feat/vuln-demo-1757571326

Conversation

@souro1212
Copy link
Copy Markdown
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

    • Introduces internal support for running user-supplied logic, enabling more dynamic interactions.
    • Adds capability to retrieve user information from the database to support data-driven experiences.
  • Chores

    • Adds a new module to host these capabilities and streamline future enhancements.

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Sep 11, 2025

Walkthrough

Adds new file app.js defining two functions: runUserCode(code) executes eval on input; getUser(db, id) builds a SQL string using the id and calls db.query. Includes a comment noting eval and SQL concatenation. No additional logic, validation, or error handling.

Changes

Cohort / File(s) Summary
New functions
app.js
Added runUserCode(code) calling eval; added getUser(db, id) concatenating id into a SQL SELECT and calling db.query; included comment noting insecure patterns.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor Caller
  participant App as app.js
  participant JS as eval(...)
  participant DB as db.query(...)

  rect rgb(240,248,255)
    note over Caller,App: runUserCode flow
    Caller->>App: runUserCode(code)
    App->>JS: eval(code)
    JS-->>App: result
    App-->>Caller: result
  end

  rect rgb(245,255,250)
    note over Caller,DB: getUser flow
    Caller->>App: getUser(db, id)
    App->>App: q = "SELECT * FROM users WHERE id = '<id>'"
    App->>DB: db.query(q)
    DB-->>App: rows
    App-->>Caller: rows
  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 50.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" accurately reflects the PR's intent to add an intentionally vulnerable example for testing and aligns with the changeset that introduces eval and SQL injection patterns in app.js. It is concise, focused on the primary purpose, and free of noisy details or emojis. Reviewers scanning history should be able to understand the PR's main goal from this title.

Poem

I nibble through code with whiskers keen,
Two new paths in the garden seen—
One runs user spells, swift and bright,
One fetches rows in the moonlit night.
Thump-thump, I review with careful cheer,
Tiny file, big ears, changes clear.

Tip

👮 Agentic pre-merge checks are now available in preview!

Pro plan users can now enable pre-merge checks in their settings to enforce checklists before merging PRs.

  • Built-in checks – Quickly apply ready-made checks to enforce title conventions, require pull request descriptions that follow templates, validate linked issues for compliance, and more.
  • Custom agentic checks – Define your own rules using CodeRabbit’s advanced agentic capabilities to enforce organization-specific policies and workflows. For example, you can instruct CodeRabbit’s agent to verify that API documentation is updated whenever API schema files are modified in a PR. Note: Upto 5 custom checks are currently allowed during the preview period. Pricing for this feature will be announced in a few weeks.

Please see the documentation for more information.

Example:

reviews:
  pre_merge_checks:
    custom_checks:
      - name: "Undocumented Breaking Changes"
        mode: "warning"
        instructions: |
          Pass/fail criteria: All breaking changes to public APIs, CLI flags, environment variables, configuration keys, database schemas, or HTTP/GraphQL endpoints must be documented in the "Breaking Change" section of the PR description and in CHANGELOG.md. Exclude purely internal or private changes (e.g., code not exported from package entry points or explicitly marked as internal).

Please share your feedback with us on this Discord post.

✨ 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-1757571326

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

@github-actions
Copy link
Copy Markdown

🔐 Secure Code Review (AI)

Risk Summary: High (2)

  1. Finding: Use of eval()

    • Why it matters: The use of eval() allows execution of arbitrary code, which can lead to Remote Code Execution (RCE) vulnerabilities if user input is not properly sanitized.
    • Evidence (diff lines): +function runUserCode(code) { return eval(code); }
    • Fix (concrete): Avoid using eval(). Instead, implement a safer alternative for executing user code, such as using a sandboxed environment or a library designed for safe code execution.
  2. Finding: SQL Injection vulnerability

    • Why it matters: The construction of SQL queries using string concatenation with user input makes the application vulnerable to SQL Injection attacks, allowing attackers to manipulate queries and access unauthorized data.
    • Evidence (diff lines): +const q = "SELECT * FROM users WHERE id = '" + id + "'";
    • Fix (concrete): Use parameterized queries or prepared statements to safely handle user input. For example, modify the query to use placeholders: const q = "SELECT * FROM users WHERE id = ?"; and pass id as a parameter.

Safeguards Checklist:

  • Input validation: Fail
  • Output encoding: N/A
  • Use of parameterized queries: Fail
  • Avoidance of dangerous functions (e.g., eval): Fail

The diff is small and focused, but it contains critical security issues that need immediate attention.


Models can make mistakes. Verify before merging.

@secure-code-warrior-for-github
Copy link
Copy Markdown

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

Micro-Learning Topic: SQL injection (Detected by phrase)

Matched on "SQL Injection"

What is this? (2min video)

This is probably one of the two most exploited vulnerabilities in web applications and has led to a number of high profile company breaches. It occurs when an application fails to sanitize or validate input before using it to dynamically construct a statement. An attacker that exploits this vulnerability will be able to gain access to the underlying database and view or modify data without permission.

Try a challenge in Secure Code Warrior

Helpful references

Copy link
Copy Markdown

@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)
app.js (1)

1-6: Add guardrails to prevent regressions.

  • Enforce no-eval in lints (Biome/ESLint) and block SQL string concatenation in queries.
  • Add a simple unit test asserting the query is parameterized.
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e535117 and 3e2f0a6.

📒 Files selected for processing (1)
  • app.js (1 hunks)
🧰 Additional context used
🪛 Biome (2.1.2)
app.js

[error] 2-2: eval() exposes to security risks and performance issues.

See the MDN web docs for more details.
Refactor the code so that it doesn't need to call eval().

(lint/security/noGlobalEval)

Comment thread app.js
@@ -0,0 +1,6 @@
// BAD: eval + SQLi
function runUserCode(code) { return eval(code); }
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

⚠️ Potential issue

Block eval and remove arbitrary code execution.

eval enables RCE and bypasses CSP; there’s no safe way to expose it here.

Apply this minimal hardening:

-function runUserCode(code) { return eval(code); }
+function runUserCode(/* code */) {
+  throw new Error("Disabled: eval is prohibited");
+}

If you truly need expression support, I can replace this with a safe, whitelisted evaluator. Want me to draft that?

📝 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
function runUserCode(code) { return eval(code); }
function runUserCode(/* code */) {
throw new Error("Disabled: eval is prohibited");
}
🧰 Tools
🪛 Biome (2.1.2)

[error] 2-2: eval() exposes to security risks and performance issues.

See the MDN web docs for more details.
Refactor the code so that it doesn't need to call eval().

(lint/security/noGlobalEval)

🤖 Prompt for AI Agents
In app.js around line 2, the runUserCode function currently uses eval(code)
which allows remote code execution; remove the eval usage and stop executing
arbitrary strings. Replace it with one of these safe options: 1) if you only
need to evaluate simple expressions, use a whitelisted expression evaluator
(e.g., expression-eval or a small custom parser) and validate input against an
allowlist; 2) if you must run JS snippets, execute them in a strict sandboxed
environment (e.g., Node VM with time/memory limits or vm2) and explicitly
disallow globals and I/O; or 3) if execution isn’t required, throw an error and
reject the request. Ensure inputs are validated, limit execution time/memory,
and log/audit attempts. Implement the chosen change and remove the eval line.

Comment thread app.js
Comment on lines +3 to +6
function getUser(db, id) {
const q = "SELECT * FROM users WHERE id = '" + id + "'";
return db.query(q);
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Fix SQL injection: use parameterized queries (and avoid quoting the parameter).

String concatenation of id is exploitable. Bind parameters and optionally constrain id.

MySQL/sqlite-style placeholders:

-function getUser(db, id) {
-  const q = "SELECT * FROM users WHERE id = '" + id + "'";
-  return db.query(q);
-}
+function getUser(db, id) {
+  const q = "SELECT * FROM users WHERE id = ? LIMIT 1";
+  return db.query(q, [id]);
+}

Postgres-style placeholders:

-function getUser(db, id) {
-  const q = "SELECT * FROM users WHERE id = '" + id + "'";
-  return db.query(q);
-}
+function getUser(db, id) {
+  const q = "SELECT * FROM users WHERE id = $1 LIMIT 1";
+  return db.query(q, [id]);
+}

To confirm which variant to use, run:


🏁 Script executed:

#!/bin/bash
# Detect DB driver and find db.query usages
rg -n -C2 '"(pg|mysql2|mssql|sqlite3|better-sqlite3|knex|sequelize|typeorm|prisma)"' package.json || true
rg -n -C3 --type=js --type=ts '\bdb\.query\s*\('

Length of output: 204


Fix SQL injection: use parameterized queries

String concatenation of id is exploitable; bind parameters and constrain id. Location: app.js lines 3-6.

MySQL/sqlite-style placeholders:

-function getUser(db, id) {
-  const q = "SELECT * FROM users WHERE id = '" + id + "'";
-  return db.query(q);
-}
+function getUser(db, id) {
+  const q = "SELECT * FROM users WHERE id = ? LIMIT 1";
+  return db.query(q, [id]);
+}

Postgres-style placeholders:

-function getUser(db, id) {
-  const q = "SELECT * FROM users WHERE id = '" + id + "'";
-  return db.query(q);
-}
+function getUser(db, id) {
+  const q = "SELECT * FROM users WHERE id = $1 LIMIT 1";
+  return db.query(q, [id]);
+}
📝 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
function getUser(db, id) {
const q = "SELECT * FROM users WHERE id = '" + id + "'";
return db.query(q);
}
function getUser(db, id) {
const q = "SELECT * FROM users WHERE id = ? LIMIT 1";
return db.query(q, [id]);
}
Suggested change
function getUser(db, id) {
const q = "SELECT * FROM users WHERE id = '" + id + "'";
return db.query(q);
}
function getUser(db, id) {
const q = "SELECT * FROM users WHERE id = $1 LIMIT 1";
return db.query(q, [id]);
}
🤖 Prompt for AI Agents
In app.js around lines 3-6, the current function builds the SQL via string
concatenation causing SQL injection; fix by using a parameterized query and
validating/constraining id before calling the DB. Ensure you switch the query to
use the appropriate placeholder for your driver (use ? for MySQL/SQLite or $1
for Postgres), pass id as a bound parameter array/params object to db.query, and
validate id (e.g., parseInt and verify numeric range or validate UUID format)
before executing so only valid ids are allowed.

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