Skip to content

Validate video OCR image bytes before Tesseract - #882

Closed
saurabhhhcodes wants to merge 1 commit into
knoxiboy:mainfrom
saurabhhhcodes:fix/video-ocr-image-validation-873
Closed

Validate video OCR image bytes before Tesseract#882
saurabhhhcodes wants to merge 1 commit into
knoxiboy:mainfrom
saurabhhhcodes:fix/video-ocr-image-validation-873

Conversation

@saurabhhhcodes

@saurabhhhcodes saurabhhhcodes commented Jul 11, 2026

Copy link
Copy Markdown
Contributor

User description

Closes #873\n\nAdds server-side byte sniffing for the video generation image URL before the OCR pipeline runs. Malformed or non-image payloads now fail fast with a 422 instead of reaching Tesseract.js.\n\nValidation:\n- git diff --check\n- npm test -- --runInBand src/tests/lib/video-image-validation.test.ts src/tests/api/video-generate-route.test.ts


CodeAnt-AI Description

Reject invalid video upload images before starting OCR

What Changed

  • Video generation now checks the uploaded image content before sending it into OCR
  • Files that are not real PNG, JPG, or WEBP images are stopped early with a 422 error and a clear upload message
  • The upload is also rejected when the image cannot be read or fetched correctly, instead of reaching the job pipeline

Impact

✅ Fewer failed video generation jobs
✅ Clearer image upload errors
✅ Less wasted OCR processing on invalid files

💡 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 image URLs used during video generation.
    • Supports PNG, JPEG, and WEBP images.
    • Provides clear error messages when an image is unavailable, invalid, or unsupported.
  • Bug Fixes

    • Prevents video generation from proceeding with invalid image payloads.
  • Tests

    • Added coverage for image type detection, URL validation, and invalid video-generation requests.

@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:testing Testing 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: 96de52e5-da78-482f-8c03-8a7fb11d582f

📥 Commits

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

📒 Files selected for processing (4)
  • 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

Adds server-side magic-byte validation for optional video image URLs, rejects invalid payloads with structured HTTP 422 responses, and tests both the validator and generation route behavior.

Changes

Video image validation

Layer / File(s) Summary
Image validation primitives
src/lib/video/image-validation.ts
Defines PNG, JPEG, and WEBP allowlists, detects file types from magic bytes, and validates fetched image URLs.
Generation route validation
src/app/api/video/generate/route.ts
Validates optional imageUrl values and returns the validator’s error, code, and status before enqueueing generation work.
Validation behavior tests
src/__tests__/lib/video-image-validation.test.ts, src/__tests__/api/video-generate-route.test.ts
Tests supported signatures, cache: "no-store" fetching, invalid payload responses, and route-level rejection.

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

Possibly related issues

Possibly related PRs

Suggested labels: type:security

✨ 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
Comment on lines +46 to +57
if (data.imageUrl) {
const imageValidation = await validateVideoImageUrl(data.imageUrl);
if (!imageValidation.ok) {
return NextResponse.json(
{
error: imageValidation.error,
code: imageValidation.code,
},
{ status: imageValidation.status },
);
}
}

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: The new validation runs whenever an image URL is present, even when text content is already provided. In this flow OCR would not use the image, so valid text submissions can now fail incorrectly due to an unrelated image URL; gate validation to only run when OCR is actually needed. [incorrect condition logic]

Severity Level: Major ⚠️
- ❌ Text plus image submissions rejected for incidental bad image URL.
- ⚠️ Video generation fails when OCR would be skipped anyway.
Steps of Reproduction ✅
1. Issue a POST request to `/api/video/generate` (handled by `POST` in
`src/app/api/video/generate/route.ts:23`) with a JSON body containing both a valid
`content` string and an `imageUrl` pointing to a malformed or non-image payload (for
example a URL returning plain text, as modeled in
`src/__tests__/api/video-generate-route.test.ts:50-55`).

2. The request is parsed and validated by `parseAndValidateRequest(req,
generateVideoSchema)` in `src/app/api/video/generate/route.ts:43`, using
`generateVideoSchema` from `src/lib/validations/video.ts:4-9`, which explicitly allows
both `content` and `imageUrl` and only requires that at least one of them be present.

3. Because `data.imageUrl` is non-null, the condition at
`src/app/api/video/generate/route.ts:46` executes `validateVideoImageUrl(data.imageUrl)`
from `src/lib/video/image-validation.ts:49-82`, which performs a fetch and magic-byte
validation and returns `{ ok: false, status: 422, code: "INVALID_IMAGE_PAYLOAD", error:
... }` for malformed image payloads.

4. The handler then returns a 422 response at `src/app/api/video/generate/route.ts:48-55`
and never enqueues the `video/generate.requested` event for Inngest, even though the text
`content` alone is sufficient for `runVideoPipeline({ content, imageUrl })` in
`src/inngest/functions.ts:15-24` and `src/lib/video/pipeline.ts:102-120` (where OCR is
only run when `imageUrl` is present and `content` is absent), causing otherwise valid
text-based submissions with an incidental bad image URL to be rejected.

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/app/api/video/generate/route.ts
**Line:** 46:57
**Comment:**
	*Incorrect Condition Logic: The new validation runs whenever an image URL is present, even when text content is already provided. In this flow OCR would not use the image, so valid text submissions can now fail incorrectly due to an unrelated image URL; gate validation to only run when OCR is actually needed.

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
👍 | 👎

Comment on lines +34 to +36
if (bytes.length >= JPEG_SIGNATURE.length && JPEG_SIGNATURE.every((byte, index) => bytes[index] === byte)) {
return 'image/jpeg';
}

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: The JPEG detector accepts any 3-byte prefix FF D8 FF, which can classify invalid/truncated payloads as JPEG and let malformed data pass this gate. Strengthen JPEG validation with a longer signature check (and/or minimal structural checks) so malformed payloads fail fast as intended. [logic error]

Severity Level: Major ⚠️
- ⚠️ Malformed JPEG-like payloads can pass validation gate.
- ⚠️ Downstream image consumers may still fail unexpectedly.
Steps of Reproduction ✅
1. An attacker hosts an endpoint that returns a payload whose first three bytes match the
JPEG magic prefix `[0xff, 0xd8, 0xff]` but whose remaining bytes are arbitrary non-JPEG
data (for example, `0xff 0xd8 0xff` followed by text or random bytes).

2. A client sends a POST request to `/api/video/generate` (handled by `POST` in
`src/app/api/video/generate/route.ts:23`) with `imageUrl` pointing to this endpoint, which
passes `safeUrl` validation in `src/lib/validations/common.ts:3-4` via
`generateVideoSchema` in `src/lib/validations/video.ts:4-9`.

3. The route calls `validateVideoImageUrl(data.imageUrl)` at
`src/app/api/video/generate/route.ts:46-47`, which fetches the URL, converts the body to a
`Uint8Array` at `src/lib/video/image-validation.ts:61`, and then invokes
`detectVideoImageMimeType(bytes)` at `src/lib/video/image-validation.ts:62`.

4. Inside `detectVideoImageMimeType`, the JPEG branch at
`src/lib/video/image-validation.ts:34-36` only checks that `bytes.length >= 3` and that
the first three bytes equal the JPEG signature, so it returns `'image/jpeg'` even though
the payload is not structurally valid; `validateVideoImageUrl` then treats this as `ok:
true` at `src/lib/video/image-validation.ts:73`, allowing malformed data to pass the
validation gate instead of failing fast as intended.

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:** 34:36
**Comment:**
	*Logic Error: The JPEG detector accepts any 3-byte prefix `FF D8 FF`, which can classify invalid/truncated payloads as JPEG and let malformed data pass this gate. Strengthen JPEG validation with a longer signature check (and/or minimal structural checks) so malformed payloads fail fast as intended.

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
👍 | 👎


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: The server fetches a user-controlled URL directly, which enables SSRF against internal network targets (for example cloud metadata or private services). Restrict allowed hosts/IP ranges (block localhost, link-local, RFC1918, etc.) before fetching, and reject non-public destinations. [ssrf]

Severity Level: Critical 🚨
- ❌ Video generation endpoint can query internal metadata services.
- ❌ Attackers can reach private network services via imageUrl.
- ⚠️ SSRF may bypass perimeter network protections entirely.
Steps of Reproduction ✅
1. An attacker sends a POST request to `/api/video/generate` (handled by `POST` in
`src/app/api/video/generate/route.ts:23`) with a JSON body where `imageUrl` is a URL to an
internal resource, such as `http://169.254.169.254/latest/meta-data/...`, and optionally
omits `content`.

2. The body is parsed by `parseAndValidateRequest` against `generateVideoSchema` in
`src/lib/validations/video.ts:4-9`, where `imageUrl` is validated only as a `safeUrl`
(`trimmedString.url().max(2048)` in `src/lib/validations/common.ts:3-4`) with no host or
IP-range restrictions, so internal network endpoints are accepted.

3. Because `data.imageUrl` is present, the route calls
`validateVideoImageUrl(data.imageUrl)` at `src/app/api/video/generate/route.ts:46-47`,
which in turn executes `fetch(imageUrl, { cache: 'no-store' })` at
`src/lib/video/image-validation.ts:51` directly against the attacker-controlled URL from
the server environment.

4. On infrastructure where the backend has network access to cloud metadata services or
other internal systems, this design allows the attacker to cause server-side requests to
those internal endpoints (SSRF) and observe success or failure via the validation response
from `validateVideoImageUrl`, potentially exfiltrating sensitive information or
interacting with private services.

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: The server fetches a user-controlled URL directly, which enables SSRF against internal network targets (for example cloud metadata or private services). Restrict allowed hosts/IP ranges (block localhost, link-local, RFC1918, etc.) before fetching, and reject non-public destinations.

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 very large payload can exhaust memory and crash or degrade the server. Enforce a strict maximum byte limit (via Content-Length check plus streamed read cap) and fail once the cap is exceeded. [performance]

Severity Level: Major ⚠️
- ❌ Large image responses can crash video generation backend.
- ⚠️ Memory pressure degrades performance for legitimate video jobs.
Steps of Reproduction ✅
1. An attacker hosts a server at a public URL and configures it to return a very large
HTTP response body (for example, hundreds of megabytes or several gigabytes) with status
200 when requested.

2. The attacker sends a POST request to `/api/video/generate` (handled by `POST` in
`src/app/api/video/generate/route.ts:23`) with `imageUrl` pointing to this large-response
endpoint and no `content`, which is accepted because `imageUrl` passes the `safeUrl`
validation in `src/lib/validations/common.ts:3-4` via `generateVideoSchema` in
`src/lib/validations/video.ts:4-9`.

3. The route calls `validateVideoImageUrl(data.imageUrl)` at
`src/app/api/video/generate/route.ts:46-47`, which fetches the URL and then executes
`const bytes = new Uint8Array(await response.arrayBuffer());` at
`src/lib/video/image-validation.ts:61`, causing the entire remote response body to be
buffered into memory with no explicit size cap.

4. Under sufficiently large responses or multiple concurrent malicious requests, this
unbounded allocation can exhaust the server process’s memory or trigger heavy garbage
collection, degrading performance or crashing the video generation API and its associated
background processing.

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 very large payload can exhaust memory and crash or degrade the server. Enforce a strict maximum byte limit (via Content-Length check plus streamed read cap) and fail once the cap is exceeded.

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:testing Testing 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]: Tesseract.js OCR Missing File Type Validation

2 participants