fix(moderation): validate action body fields with Zod (#797)#829
fix(moderation): validate action body fields with Zod (#797)#829Dasmat13 wants to merge 1 commit into
Conversation
|
@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 is reviewing your PR. |
Thanks for using CodeAnt! 🎉We're free for open-source projects. if you're enjoying it, help us grow by sharing. Share on X · |
|
Caution Review failedThe pull request is closed. ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (2)
WalkthroughThe 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. ChangesModeration action validation and tests
Estimated code review effort: 2 (Simple) | ~12 minutes Possibly related issues
Possibly related PRs
Suggested reviewers: ✨ Finishing Touches🧪 Generate unit tests (beta)
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. Comment |
❌ PR Rejected — Issue Assignment Check FailedHi @Dasmat13! This PR has been closed because you are not assigned to the issue(s) it references:
What to do:
|
| const moderationActionSchema = z.object({ | ||
| logId: z.number().int().positive(), | ||
| userEmail: z.string().email(), | ||
| action: z.enum(["dismiss", "warn", "block"]), | ||
| }); |
There was a problem hiding this comment.
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`.(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 finished reviewing your PR. |
User description
Fixes #797
Summary
Adds strict Zod schema validation to
POST /api/admin/moderation/actionto prevent malformed or malicious inputs from reaching the database.What Changed
moderationActionSchemausingz.object():logId→z.number().int().positive()— rejects strings, floats, negatives, and zerouserEmail→z.string().email()— rejects injection vectors and malformed emailsaction→z.enum(["dismiss", "warn", "block"])— rejects any value outside the allowed set!logId || !userEmail || !actionpresence check withparseAndValidateRequest()from the existing centralized validation helper (src/lib/validations/validate.ts)admin-moderation-action.test.ts) with 6 cases covering:dismiss,warn, andblockactions including email sending and audit log verificationSecurity Impact
Prevents injection vectors via
userEmailand invalid enum values viaactionfrom 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
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:
This lets you have a chat with CodeAnt AI about your pull request, making it easier to understand and improve your code.
Example
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:
This helps CodeAnt AI learn and adapt to your team's coding style and standards.
Example
Retrigger review
Ask CodeAnt AI to review the PR again, by typing:
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
Tests