Skip to content

Add missing security headers to next config#883

Closed
saurabhhhcodes wants to merge 2 commits into
knoxiboy:mainfrom
saurabhhhcodes:fix/security-headers-874
Closed

Add missing security headers to next config#883
saurabhhhcodes wants to merge 2 commits into
knoxiboy:mainfrom
saurabhhhcodes:fix/security-headers-874

Conversation

@saurabhhhcodes

@saurabhhhcodes saurabhhhcodes commented Jul 11, 2026

Copy link
Copy Markdown
Contributor

User description

Closes #874\n\nAdds the security headers called out in the issue to the global Next.js headers config: CSP, nosniff, referrer policy, permissions policy, and HSTS in production.\n\nValidation:\n- git diff --check\n- node --check next.config.mjs


CodeAnt-AI Description

Add security headers and reject invalid video image uploads

What Changed

  • Adds site-wide security headers, including a stricter content policy and HSTS in production
  • Video generation now checks uploaded image URLs before starting work and stops invalid PNG, JPG, or WEBP payloads with a clear 422 error
  • Adds test coverage for image format detection and for blocking malformed image uploads early

Impact

✅ Safer page loading
✅ Fewer failed video jobs from bad image uploads
✅ Clearer upload errors

💡 Usage Guide

Checking Your Pull Request

Every time you make a pull request, our system automatically looks through it. We check for security issues, mistakes in how you're setting up your infrastructure, and common code problems. We do this to make sure your changes are solid and won't cause any trouble later.

Talking to CodeAnt AI

Got a question or need a hand with something in your pull request? You can easily get in touch with CodeAnt AI right here. Just type the following in a comment on your pull request, and replace "Your question here" with whatever you want to ask:

@codeant-ai ask: Your question here

This lets you have a chat with CodeAnt AI about your pull request, making it easier to understand and improve your code.

Example

@codeant-ai ask: Can you suggest a safer alternative to storing this secret?

Preserve Org Learnings with CodeAnt

You can record team preferences so CodeAnt AI applies them in future reviews. Reply directly to the specific CodeAnt AI suggestion (in the same thread) and replace "Your feedback here" with your input:

@codeant-ai: Your feedback here

This helps CodeAnt AI learn and adapt to your team's coding style and standards.

Example

@codeant-ai: Do not flag unused imports.

Retrigger review

Ask CodeAnt AI to review the PR again, by typing:

@codeant-ai: review

Check Your Repository Health

To analyze the health of your code repository, visit our dashboard at https://app.codeant.ai. This tool helps you identify potential issues and areas for improvement in your codebase, ensuring your repository maintains high standards of code health.

Summary by CodeRabbit

  • New Features

    • Added validation for video image uploads, accepting PNG, JPG, and WEBP formats.
    • Invalid or malformed image content now receives a clear error before video processing begins.
    • Enhanced production security headers, including content security and transport protection.
  • Bug Fixes

    • Prevented non-image payloads from being queued for video generation.

@vercel

vercel Bot commented Jul 11, 2026

Copy link
Copy Markdown

Someone is attempting to deploy a commit to the Karan Mani Tripathi 's projects Team on Vercel.

A member of the Team first needs to authorize it.

@codeant-ai

codeant-ai Bot commented Jul 11, 2026

Copy link
Copy Markdown

CodeAnt AI is reviewing your PR.

@codeant-ai

codeant-ai Bot commented Jul 11, 2026

Copy link
Copy Markdown

Thanks for using CodeAnt! 🎉

We're free for open-source projects. if you're enjoying it, help us grow by sharing.

Share on X ·
Reddit ·
LinkedIn

@github-actions github-actions Bot added gssoc'26 GSSoC program issue level:advanced Advanced level task type:security Security fix labels Jul 11, 2026
@github-actions

Copy link
Copy Markdown

❌ PR Rejected — Issue Assignment Check Failed

Hi @saurabhhhcodes! This PR has been closed because you are not assigned to the issue(s) it references:

What to do:

  1. Comment /assign on the issue to request assignment from a maintainer.
  2. Wait until you are officially assigned.
  3. Then re-open or re-submit your PR.

PRs that fix issues not assigned to the author cannot be accepted — this ensures fair contribution tracking.

@github-actions github-actions Bot added the invalid This doesn't seem right label Jul 11, 2026
@github-actions github-actions Bot closed this Jul 11, 2026
@coderabbitai

coderabbitai Bot commented Jul 11, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: a895cbca-a394-47c6-be00-0d7f6940acbe

📥 Commits

Reviewing files that changed from the base of the PR and between 8e7bd25 and f2a4d6c.

📒 Files selected for processing (5)
  • next.config.mjs
  • src/__tests__/api/video-generate-route.test.ts
  • src/__tests__/lib/video-image-validation.test.ts
  • src/app/api/video/generate/route.ts
  • src/lib/video/image-validation.ts

Walkthrough

The PR adds multiple security headers to Next.js responses and validates video generation image URLs by inspecting fetched file signatures before the request proceeds to job creation.

Changes

Security header configuration

Layer / File(s) Summary
Security header policy
next.config.mjs
Builds a shared security header list, adds HSTS in production, and applies the headers to matched routes.

Video image payload validation

Layer / File(s) Summary
Image validation contracts and signature detection
src/lib/video/image-validation.ts
Defines supported image MIME types and detects PNG, JPEG, and WebP signatures from raw bytes.
Image URL validation
src/lib/video/image-validation.ts, src/__tests__/lib/video-image-validation.test.ts
Fetches image URLs without caching and returns structured validation results for supported or invalid payloads.
Video generation route integration
src/app/api/video/generate/route.ts, src/__tests__/api/video-generate-route.test.ts
Validates supplied image URLs before processing and tests the 422 malformed-payload response.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant VideoGenerateRoute
  participant validateVideoImageUrl
  participant ImageURL
  Client->>VideoGenerateRoute: POST imageUrl
  VideoGenerateRoute->>validateVideoImageUrl: validate image URL
  validateVideoImageUrl->>ImageURL: fetch image bytes
  ImageURL-->>validateVideoImageUrl: response payload
  validateVideoImageUrl-->>VideoGenerateRoute: validation result
  VideoGenerateRoute-->>Client: 422 error or continue processing
Loading

Possibly related issues

Possibly related PRs

  • knoxiboy/DoubtDesk#731 — Modifies the same video generation route and overlaps with its request-validation flow.

Suggested reviewers: knoxiboy

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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.

@codeant-ai codeant-ai Bot added the size:L label Jul 11, 2026
@github-actions github-actions Bot removed the size:L label Jul 11, 2026

export async function validateVideoImageUrl(imageUrl: string): Promise<VideoImageValidationResult> {
try {
const response = await fetch(imageUrl, { cache: 'no-store' });

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Suggestion: This fetches a user-controlled URL directly from the server without any SSRF guardrails (no scheme restriction to HTTPS only, no private-network/localhost/IP blocking, no allowlist). An attacker can submit internal URLs and make the backend probe internal services/metadata endpoints. Add strict outbound URL validation (protocol + hostname/IP checks) before issuing the request. [ssrf]

Severity Level: Critical 🚨
❌ /api/video/generate can fetch attacker-chosen internal URLs.
❌ Backend may reach cloud metadata or admin services.
⚠️ Potential pivot to internal network reconnaissance.
Steps of Reproduction ✅
1. Start the DoubtDesk Next.js app so that the API route handler in
`src/app/api/video/generate/route.ts:23-110` is active, exposing `POST
/api/video/generate`.

2. From a client, send `POST /api/video/generate` with JSON body `{ "content": null,
"imageUrl": "http://127.0.0.1:8080/internal-status" }`. The body is parsed and validated
by `parseAndValidateRequest` in `src/lib/validations/validate.ts:5-27` using
`generateVideoSchema` in `src/lib/validations/video.ts:4-7`, which applies `safeUrl` from
`src/lib/validations/common.ts:3-5` (only syntax + length checks, no SSRF filtering).

3. In `src/app/api/video/generate/route.ts:46-48`, the handler sees a non-null
`data.imageUrl` and calls `validateVideoImageUrl(data.imageUrl)`, passing the
attacker-controlled URL to `validateVideoImageUrl` implemented in
`src/lib/video/image-validation.ts:49-82`.

4. Inside `validateVideoImageUrl`, line `51 const response = await fetch(imageUrl, {
cache: 'no-store' });` issues a server-side `fetch` to
`http://127.0.0.1:8080/internal-status` (or any attacker-chosen internal/metadata
endpoint). There are no scheme, hostname, or private-network restrictions, so the backend
will attempt to reach internal services, demonstrating an SSRF capability even though only
a validation result (not the full response body) is returned to the client.

Fix in Cursor Fix in VSCode Claude

(Use Cmd/Ctrl + Click for best experience)

Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** src/lib/video/image-validation.ts
**Line:** 51:51
**Comment:**
	*Ssrf: This fetches a user-controlled URL directly from the server without any SSRF guardrails (no scheme restriction to HTTPS only, no private-network/localhost/IP blocking, no allowlist). An attacker can submit internal URLs and make the backend probe internal services/metadata endpoints. Add strict outbound URL validation (protocol + hostname/IP checks) before issuing the request.

Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix
👍 | 👎

};
}

const bytes = new Uint8Array(await response.arrayBuffer());

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Suggestion: This reads the entire remote response into memory with no size cap, so a large payload can cause excessive memory usage or process instability before validation completes. Enforce a strict maximum download size (via Content-Length checks plus streamed byte limits) and reject oversized payloads early. [performance]

Severity Level: Major ⚠️
❌ Large remote images can OOM Next.js video API.
⚠️ Video generation requests can stall under resource exhaustion.
⚠️ Resource spikes may degrade other API endpoints.
Steps of Reproduction ✅
1. Run the DoubtDesk Next.js backend so that the video generation API handler in
`src/app/api/video/generate/route.ts:23-110` is exposed as `POST /api/video/generate`.

2. Host a very large file (e.g., >500MB) at an attacker-controlled URL such as
`https://attacker.example/huge.bin`, and send `POST /api/video/generate` with body `{
"content": null, "imageUrl": "https://attacker.example/huge.bin" }`. The request body is
accepted by `parseAndValidateRequest` (`src/lib/validations/validate.ts:5-27`) and
`generateVideoSchema` (`src/lib/validations/video.ts:4-7`) as long as the URL is
syntactically valid.

3. In `src/app/api/video/generate/route.ts:46-48`, the handler calls
`validateVideoImageUrl(data.imageUrl)`. Inside `validateVideoImageUrl`
(`src/lib/video/image-validation.ts:49-82`), line `51 const response = await
fetch(imageUrl, { cache: 'no-store' });` starts downloading the large file from the remote
server.

4. At `src/lib/video/image-validation.ts:61`, `const bytes = new Uint8Array(await
response.arrayBuffer());` reads the entire response body into an `ArrayBuffer` with no
`Content-Length` check and no byte-size cap, unlike the explicit `AI_IMAGE_MAX_BYTES`
limit enforced in `src/lib/ai/ai-image-validation.ts:1-3,102-110`. For very large
payloads, this can cause excessive memory usage or process instability (OOM or severe GC
thrashing) in the Next.js server handling `/api/video/generate`.

Fix in Cursor Fix in VSCode Claude

(Use Cmd/Ctrl + Click for best experience)

Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** src/lib/video/image-validation.ts
**Line:** 61:61
**Comment:**
	*Performance: This reads the entire remote response into memory with no size cap, so a large payload can cause excessive memory usage or process instability before validation completes. Enforce a strict maximum download size (via `Content-Length` checks plus streamed byte limits) and reject oversized payloads early.

Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix
👍 | 👎

@codeant-ai

codeant-ai Bot commented Jul 11, 2026

Copy link
Copy Markdown

CodeAnt AI finished reviewing your PR.

@knoxiboy knoxiboy removed gssoc'26 GSSoC program issue level:advanced Advanced level task type:security Security fix size/l labels Jul 15, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

invalid This doesn't seem right

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Missing Security Headers in next.config.mjs

2 participants