Skip to content

Comments

🛡️ Sentinel: [HIGH] Fix CSRF vulnerability via Content-Type enforcement#100

Draft
Dexploarer wants to merge 1 commit intomainfrom
sentinel-fix-csrf-json-content-type-4413514494244013636
Draft

🛡️ Sentinel: [HIGH] Fix CSRF vulnerability via Content-Type enforcement#100
Dexploarer wants to merge 1 commit intomainfrom
sentinel-fix-csrf-json-content-type-4413514494244013636

Conversation

@Dexploarer
Copy link
Owner

🛡️ Sentinel: [HIGH] Fix CSRF vulnerability via Content-Type enforcement

Severity: HIGH

Vulnerability:
The readJsonBody helper blindly parsed request bodies as JSON without verifying the Content-Type header. This allowed "simple requests" (e.g., text/plain POSTs) sent from a malicious origin (CSRF) to be processed by the server, bypassing CORS preflight checks. If the server was running locally (default unauthenticated mode), this could lead to Remote Code Execution (RCE) via endpoints like /api/terminal/run.

Fix:

  • Enforce Content-Type: application/json (case-insensitive substring match) in readJsonBody.
  • Reject invalid requests with 415 Unsupported Media Type.
  • Updated test infrastructure to ensure tests send correct headers.

Verification:

  • Run npx vitest run src/api/server.csrf.test.ts to verifying that text/plain requests are rejected and application/json requests are accepted.
  • Run npx vitest run src/api/ to ensure no regressions in existing endpoints.

PR created automatically by Jules for task 4413514494244013636 started by @Dexploarer

… to prevent CSRF

- Updated `readJsonBody` in `src/api/http-helpers.ts` to reject requests without `Content-Type: application/json` by default.
- Added `ReadJsonBodyOptions.requireContentType` (defaults to "application/json") to allow opting out if needed.
- Updated test helpers `createMockIncomingMessage` to auto-inject Content-Type for JSON requests to fix regressions in existing tests.
- Manually updated tests in `src/api/cloud-routes.test.ts` that were using partial mocks without correct headers.
- Added `src/api/server.csrf.test.ts` to verify the security fix.
- This prevents CSRF attacks where a malicious site could send a "simple request" (e.g. text/plain) with a JSON body that would be parsed and executed by the server.
@google-labs-jules
Copy link

👋 Jules, reporting for duty! I'm here to lend a hand with this pull request.

When you start a review, I'll add a 👀 emoji to each comment to let you know I've read it. I'll focus on feedback directed at me and will do my best to stay out of conversations between you and other bots or reviewers to keep the noise down.

I'll push a commit with your requested changes shortly after. Please note there might be a delay between these steps, but rest assured I'm on the job!

For more direct control, you can switch me to Reactive Mode. When this mode is on, I will only act on comments where you specifically mention me with @jules. You can find this option in the Pull Request section of your global Jules UI settings. You can always switch back!

New to Jules? Learn more at jules.google/docs.


For security, I will only act on instructions from the user who triggered this task.

@github-actions github-actions bot added the tests label Feb 19, 2026
@coderabbitai
Copy link

coderabbitai bot commented Feb 19, 2026

Important

Review skipped

Draft detected.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch sentinel-fix-csrf-json-content-type-4413514494244013636

Tip

Issue Planner is now in beta. Read the docs and try it out! Share your feedback on Discord.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

@gemini-code-assist
Copy link

Summary of Changes

Hello @Dexploarer, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request implements a critical security fix to prevent Cross-Site Request Forgery (CSRF) attacks. Previously, the server's JSON body parsing logic did not validate the Content-Type header, allowing non-JSON requests to be processed as JSON. This vulnerability could lead to Remote Code Execution (RCE) in certain configurations. The changes introduce strict Content-Type validation for JSON endpoints, ensuring that only properly formatted application/json requests are processed, thereby mitigating the risk of CSRF attacks.

Highlights

  • Security Fix: Addressed a high-severity CSRF vulnerability by enforcing Content-Type: application/json for JSON body parsing, preventing malicious text/plain requests from bypassing CORS preflight checks.
  • Content-Type Enforcement: The readJsonBody helper now validates the Content-Type header, rejecting requests with an invalid type (e.g., text/plain) with a 415 Unsupported Media Type status.
  • Test Infrastructure Updates: Updated mock request creation in test helpers and existing tests to ensure Content-Type: application/json is correctly set, and added a dedicated test file for CSRF protection.

🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

Changelog
  • src/api/tests/sandbox-test-helpers.ts
    • Updated createMockReq to automatically include Content-Type: application/json header when a request body is provided, aligning mock requests with the new content type enforcement.
  • src/api/cloud-routes.test.ts
    • Modified existing createMockIncomingMessage calls to explicitly set the Content-Type: application/json header for POST requests, ensuring compatibility with the new readJsonBody validation.
  • src/api/http-helpers.ts
    • Extended ReadJsonBodyOptions with new properties (requireContentType, contentTypeErrorStatus, contentTypeErrorMessage) to configure content type validation.
    • Implemented Content-Type header validation within the readJsonBody function, rejecting requests that do not match the required content type with a 415 Unsupported Media Type error.
  • src/api/server.csrf.test.ts
    • Added a new test file dedicated to CSRF protection, including tests to verify that readJsonBody correctly rejects text/plain requests and accepts application/json requests.
  • src/test-support/test-helpers.ts
    • Introduced logic into createMockIncomingMessage to automatically inject Content-Type: application/json for mock requests that include a JSON body, if the header is not already present.
Activity
  • PR created automatically by Jules for task 4413514494244013636, initiated by @Dexploarer.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Comment on lines 11 to 21
export function createMockReq(method: string, body?: string): IncomingMessage {
const headers: Record<string, string> = {};
if (body) {
headers["content-type"] = "application/json";
}
return createMockIncomingMessage({
method,
headers: {},
headers,
body,
}) as IncomingMessage;
}

Choose a reason for hiding this comment

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

Lack of Input Validation:
The createMockReq function does not validate the method or body parameters. Passing an invalid HTTP method or malformed body could result in misleading test outcomes or errors that are difficult to diagnose. Consider adding validation for the method (e.g., ensuring it is a recognized HTTP verb) and for the body (e.g., checking if it is valid JSON when the content-type is set to 'application/json').

Recommended Solution:
Add input validation logic before constructing the mock request:

const validMethods = ["GET", "POST", "PUT", "DELETE", ...];
if (!validMethods.includes(method)) {
  throw new Error(`Invalid HTTP method: ${method}`);
}
if (body && headers["content-type"] === "application/json") {
  try {
    JSON.parse(body);
  } catch {
    throw new Error("Body is not valid JSON");
  }
}

Comment on lines +233 to +234
const contentType = req.headers["content-type"] || "";
if (!contentType.toLowerCase().includes(requireContentType.toLowerCase())) {

Choose a reason for hiding this comment

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

Content-Type Validation Permissiveness

The content-type check uses a substring match (includes) which may allow unintended content types, such as application/json+xml, to pass validation. This could result in the server attempting to parse non-JSON payloads as JSON, potentially causing errors or unexpected behavior.

Recommendation:
Consider using a stricter comparison, such as checking for an exact match or using a regular expression to match only valid JSON content types:

if (!/^application\/json($|;)/i.test(contentType)) {
  // ...
}

Comment on lines +25 to +28
setTimeout(() => {
req.emit("data", Buffer.from(JSON.stringify({ command: "whoami" })));
req.emit("end");
}, 10);

Choose a reason for hiding this comment

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

The use of setTimeout to emit 'data' and 'end' events introduces a race condition: if readJsonBody does not properly await these events, the test may pass or fail inconsistently depending on timing. To ensure deterministic behavior, consider emitting the events synchronously before awaiting readJsonBody, or refactor the test to guarantee that the function under test is listening for events before they are emitted. Example:

process.nextTick(() => {
  req.emit("data", Buffer.from(JSON.stringify({ command: "whoami" })));
  req.emit("end");
});

This approach ensures the events are emitted after the function has started listening, reducing the risk of race conditions.


// Auto-inject Content-Type for JSON requests if missing, to satisfy CSRF protection in readJsonBody.
if (json && !headers["content-type"] && !headers["Content-Type"]) {
headers["content-type"] = "application/json";

Choose a reason for hiding this comment

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

⚠️ Potential Side Effect: Mutating Input Headers Object

The code directly mutates the headers object by assigning to headers["content-type"] if the JSON flag is set and the header is missing. If the headers object is shared or reused elsewhere, this can lead to unintended side effects and test pollution.

Recommendation:
Clone the headers object before mutation to ensure test isolation:

const headersCopy = { ...headers };
if (json && !headersCopy["content-type"] && !headersCopy["Content-Type"]) {
  headersCopy["content-type"] = "application/json";
}
req.headers = headersCopy;

Copy link

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request effectively addresses a critical CSRF vulnerability by enforcing the Content-Type header in readJsonBody. The implementation is robust, using a case-insensitive substring match to accommodate headers with character sets, and includes sensible defaults for error responses. The addition of dedicated tests for this new behavior in server.csrf.test.ts is excellent, and the updates to existing tests and test helpers ensure the test suite remains consistent with the new security requirement. My review includes a couple of suggestions to improve the maintainability and cleanliness of the test code.

Comment on lines +2 to +80
import { describe, it, expect, vi } from "vitest";
import { EventEmitter } from "node:events";
import { readJsonBody } from "./http-helpers";

describe("CSRF Protection (Content-Type enforcement)", () => {
it("should REJECT JSON with text/plain (CSRF Protection)", async () => {
// Mock IncomingMessage
const req: any = new EventEmitter();
req.headers = { "content-type": "text/plain" };
req.off = vi.fn();
req.destroy = vi.fn();

// Mock ServerResponse
const res: any = {
statusCode: 200,
setHeader: vi.fn(),
end: vi.fn(),
writableEnded: false,
};

// Simulate body stream (though it shouldn't be read if header check fails first,
// but our implementation checks header first)
// We don't strictly need to emit data if it fails early, but good for robustness.
setTimeout(() => {
req.emit("data", Buffer.from(JSON.stringify({ command: "whoami" })));
req.emit("end");
}, 10);

const body = await readJsonBody(req, res);

expect(body).toBeNull();
expect(res.statusCode).toBe(415);
expect(res.end).toHaveBeenCalledWith(expect.stringContaining("Unsupported Media Type"));
});

it("should ACCEPT JSON with application/json", async () => {
const req: any = new EventEmitter();
req.headers = { "content-type": "application/json" };
req.off = vi.fn();
req.destroy = vi.fn();

const res: any = {
statusCode: 200,
setHeader: vi.fn(),
end: vi.fn(),
writableEnded: false,
};

setTimeout(() => {
req.emit("data", Buffer.from(JSON.stringify({ ok: true })));
req.emit("end");
}, 10);

const body = await readJsonBody(req, res);
expect(body).toEqual({ ok: true });
});

it("should ACCEPT JSON with application/json; charset=utf-8", async () => {
const req: any = new EventEmitter();
req.headers = { "content-type": "application/json; charset=utf-8" };
req.off = vi.fn();
req.destroy = vi.fn();

const res: any = {
statusCode: 200,
setHeader: vi.fn(),
end: vi.fn(),
writableEnded: false,
};

setTimeout(() => {
req.emit("data", Buffer.from(JSON.stringify({ ok: true })));
req.emit("end");
}, 10);

const body = await readJsonBody(req, res);
expect(body).toEqual({ ok: true });
});
});

Choose a reason for hiding this comment

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

medium

For consistency with other tests in the codebase and to improve readability, consider refactoring these tests to use the existing createMockIncomingMessage and createMockHttpResponse test helpers from src/test-support/test-helpers.ts. This will make the tests more concise and easier to maintain by removing the manual setup of mock request and response objects.

import { describe, it, expect } from "vitest";
import { createMockHttpResponse, createMockIncomingMessage } from "../test-support/test-helpers";
import { readJsonBody } from "./http-helpers";

describe("CSRF Protection (Content-Type enforcement)", () => {
  it("should REJECT JSON with text/plain (CSRF Protection)", async () => {
    const req = createMockIncomingMessage({
      headers: { "content-type": "text/plain" },
      body: JSON.stringify({ command: "whoami" }),
    });
    const { res, getStatus, getJson } = createMockHttpResponse();

    const body = await readJsonBody(req, res);

    expect(body).toBeNull();
    expect(getStatus()).toBe(415);
    expect(getJson<{ error: string }>().error).toContain("Unsupported Media Type");
  });

  it("should ACCEPT JSON with application/json", async () => {
    const req = createMockIncomingMessage({
      headers: { "content-type": "application/json" },
      body: JSON.stringify({ ok: true }),
    });
    const { res } = createMockHttpResponse();

    const body = await readJsonBody(req, res);

    expect(body).toEqual({ ok: true });
  });

  it("should ACCEPT JSON with application/json; charset=utf-8", async () => {
    const req = createMockIncomingMessage({
      headers: { "content-type": "application/json; charset=utf-8" },
      body: JSON.stringify({ ok: true }),
    });
    const { res } = createMockHttpResponse();

    const body = await readJsonBody(req, res);

    expect(body).toEqual({ ok: true });
  });
});

headers["content-type"] = "application/json";
}

// console.log('[test-helper] Request headers:', headers);

Choose a reason for hiding this comment

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

medium

This commented-out console.log appears to be a leftover from debugging. It should be removed to keep the code clean.

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

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant