Skip to content

fix(moderation): validate action body fields with Zod (#797)#829

Closed
Dasmat13 wants to merge 1 commit into
knoxiboy:mainfrom
Dasmat13:fix/admin-moderation-validation
Closed

fix(moderation): validate action body fields with Zod (#797)#829
Dasmat13 wants to merge 1 commit into
knoxiboy:mainfrom
Dasmat13:fix/admin-moderation-validation

Conversation

@Dasmat13

@Dasmat13 Dasmat13 commented Jul 8, 2026

Copy link
Copy Markdown
Contributor

User description

Fixes #797

Summary

Adds strict Zod schema validation to POST /api/admin/moderation/action to prevent malformed or malicious inputs from reaching the database.

What Changed

  • Added moderationActionSchema using z.object():
    • logIdz.number().int().positive() — rejects strings, floats, negatives, and zero
    • userEmailz.string().email() — rejects injection vectors and malformed emails
    • actionz.enum(["dismiss", "warn", "block"]) — rejects any value outside the allowed set
  • Replaced the loose !logId || !userEmail || !action presence check with parseAndValidateRequest() from the existing centralized validation helper (src/lib/validations/validate.ts)
  • Added a dedicated test suite (admin-moderation-action.test.ts) with 6 cases covering:
    • Unauthorized access (NEXT_REDIRECT propagation)
    • Schema validation failures for all invalid input combinations
    • User not found (404)
    • Successful dismiss, warn, and block actions including email sending and audit log verification

Security Impact

Prevents injection vectors via userEmail and invalid enum values via action from ever reaching the database layer.

Testing

All 41 test suites (206 tests) pass with npm run test.


CodeAnt-AI Description

Reject invalid moderation actions before they reach the database

What Changed

  • Admin moderation requests now reject malformed input with a 400 response instead of trying to process it
  • The action must now include a positive whole-number log ID, a valid email address, and one of the allowed actions
  • Added coverage for invalid requests, unauthorized access, missing users, and successful dismiss, warn, and block flows

Impact

✅ Fewer bad moderation requests
✅ Clearer validation errors
✅ Safer admin moderation actions

💡 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

  • Bug Fixes

    • Improved moderation action request handling with clearer validation responses for invalid or incomplete submissions.
    • Added safer handling for missing users, returning a not-found response instead of failing unexpectedly.
    • Ensured moderation actions now consistently trigger the right follow-up messaging, emails, and audit records.
  • Tests

    • Added coverage for admin moderation actions, including dismiss, warn, and block flows, plus validation and authorization failures.

@vercel

vercel Bot commented Jul 8, 2026

Copy link
Copy Markdown

@Dasmat13 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 8, 2026

Copy link
Copy Markdown

CodeAnt AI is reviewing your PR.

@codeant-ai

codeant-ai Bot commented Jul 8, 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:bug Bug fix type:security Security fix labels Jul 8, 2026
@coderabbitai

coderabbitai Bot commented Jul 8, 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: 34b98e3e-5a1a-482f-ab02-17de4bbcdb41

📥 Commits

Reviewing files that changed from the base of the PR and between de5a7d1 and 40a3dc2.

📒 Files selected for processing (2)
  • src/__tests__/api/admin-moderation-action.test.ts
  • src/app/api/admin/moderation/action/route.ts

Walkthrough

The admin moderation action POST route now validates request bodies against a Zod schema (logId, userEmail, action) via parseAndValidateRequest, replacing manual JSON parsing and field checks. A new Jest test suite covers authorization failures, validation errors, not-found, and dismiss/warn/block success flows.

Changes

Moderation action validation and tests

Layer / File(s) Summary
Zod schema and route validation
src/app/api/admin/moderation/action/route.ts
Introduces moderationActionSchema and replaces manual body parsing/missing-field checks with parseAndValidateRequest.
Test harness and mocks
src/__tests__/api/admin-moderation-action.test.ts
Mocks admin auth, current user, email helpers, audit logging, and DB select/update with a queued result mechanism; resets mocks in beforeEach.
Authorization/validation/not-found tests
src/__tests__/api/admin-moderation-action.test.ts
Verifies requireAdmin failure propagation, 400 on invalid bodies, and 404 for missing users.
Dismiss/warn/block success tests
src/__tests__/api/admin-moderation-action.test.ts
Verifies success responses, DB updates, email dispatch, and audit log metadata for each moderation action.

Estimated code review effort: 2 (Simple) | ~12 minutes

Possibly related issues

Possibly related PRs

  • knoxiboy/DoubtDesk#603: Both PRs modify src/app/api/admin/moderation/action/route.ts, with this PR's tests asserting the audit log entries added in #603.

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.

@github-actions

github-actions Bot commented Jul 8, 2026

Copy link
Copy Markdown

❌ PR Rejected — Issue Assignment Check Failed

Hi @Dasmat13! 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 8, 2026
@github-actions github-actions Bot closed this Jul 8, 2026
@github-actions github-actions Bot added the size/l label Jul 8, 2026
@codeant-ai codeant-ai Bot added the size:L This PR changes 100-499 lines, ignoring generated files label Jul 8, 2026
@github-actions github-actions Bot removed the size:L This PR changes 100-499 lines, ignoring generated files label Jul 8, 2026
Comment on lines +12 to +16
const moderationActionSchema = z.object({
logId: z.number().int().positive(),
userEmail: z.string().email(),
action: z.enum(["dismiss", "warn", "block"]),
});

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 schema is not actually strict: z.object() without .strict() will accept unknown fields and silently strip them instead of rejecting the request. That means payloads with unexpected keys still pass validation, which breaks the stated “strict validation” behavior and can let malformed inputs appear valid. Make the object schema strict so extra keys return a 400. [incomplete implementation]

Severity Level: Major ⚠️
- ⚠️ Admin moderation API accepts unexpected fields without rejection.
- ⚠️ Strict validation expectation broken for unknown request keys.
Steps of Reproduction ✅
1. Start the Next.js application so that the API route handler in
`src/app/api/admin/moderation/action/route.ts:18-136` is mounted as `POST
/api/admin/moderation/action`.

2. From any HTTP client, send a POST request to `/api/admin/moderation/action` with a JSON
body that includes all valid fields plus an extra one, for example:

   `{ "logId": 1, "userEmail": "user@example.com", "action": "dismiss", "unexpectedField":
   "foo" }`.

3. In `route.ts:12-16`, the handler calls `parseAndValidateRequest(request,
moderationActionSchema)` where `moderationActionSchema` is defined as `z.object({ logId,
userEmail, action })` without `.strict()`, and `parseAndValidateRequest` in
`src/lib/validations/validate.ts:5-27` uses `schema.safeParse(body)`.

4. Because Zod’s default `z.object()` strips unknown keys instead of rejecting them,
`safeParse` in `validate.ts:19-27` treats the payload as valid, returns `{ errorResponse:
null, data: parsed.data }`, and the handler at `route.ts:24-30` proceeds with DB updates
and responses, never returning a 400 for the extra `unexpectedField`.

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/admin/moderation/action/route.ts
**Line:** 12:16
**Comment:**
	*Incomplete Implementation: The schema is not actually strict: `z.object()` without `.strict()` will accept unknown fields and silently strip them instead of rejecting the request. That means payloads with unexpected keys still pass validation, which breaks the stated “strict validation” behavior and can let malformed inputs appear valid. Make the object schema strict so extra keys return a 400.

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 8, 2026

Copy link
Copy Markdown

CodeAnt AI finished reviewing your PR.

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

Labels

gssoc'26 GSSoC program issue invalid This doesn't seem right level:advanced Advanced level task size/l type:bug Bug fix type:security Security fix

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Admin Moderation Actions Don't Validate 'action' Against Enum

1 participant