Skip to content

API: require auth and identity-bound ownership for POST /api/tasks (match docs contract)#414

Open
pradipthaadhi wants to merge 1 commit intotestfrom
yuliusupwork/myc-4585-api-require-auth-and-identity-bound-ownership-for-post
Open

API: require auth and identity-bound ownership for POST /api/tasks (match docs contract)#414
pradipthaadhi wants to merge 1 commit intotestfrom
yuliusupwork/myc-4585-api-require-auth-and-identity-bound-ownership-for-post

Conversation

@pradipthaadhi
Copy link
Copy Markdown
Collaborator

@pradipthaadhi pradipthaadhi commented Apr 8, 2026

  • Updated the import of the task validation function to validateCreateTaskRequest for clarity.
  • Modified the createTaskHandler to utilize the new validation function, which now includes JSON body validation and authentication context checks.
  • Added new tests for createTaskHandler and validateCreateTaskRequest to ensure proper functionality and error handling.

Summary by CodeRabbit

  • Refactor
    • Enhanced task creation validation to include authentication context verification, ensuring secure and consistent account association with each request.

- Updated the import of the task validation function to `validateCreateTaskRequest` for clarity.
- Modified the `createTaskHandler` to utilize the new validation function, which now includes JSON body validation and authentication context checks.
- Added new tests for `createTaskHandler` and `validateCreateTaskRequest` to ensure proper functionality and error handling.
@vercel
Copy link
Copy Markdown
Contributor

vercel bot commented Apr 8, 2026

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
recoup-api Ready Ready Preview Apr 8, 2026 6:28am

Request Review

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Apr 8, 2026

📝 Walkthrough

Walkthrough

The validation logic for task creation is consolidated into a request-level validator that handles JSON parsing, body validation via Zod, and auth context resolution. The handler now delegates validation to validateCreateTaskRequest() instead of managing JSON parsing and separate body validation directly.

Changes

Cohort / File(s) Summary
Request-level validation refactoring
lib/tasks/createTaskHandler.ts, lib/tasks/validateCreateTaskBody.ts
Introduced validateCreateTaskRequest() to centralize JSON parsing, Zod body validation, and auth context resolution in a single async validator. Handler updated to call this new validator instead of manually parsing and validating. Auth context now resolves and overrides the effective account_id before returning the validated body.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • add auth validation to get tasks API #345: Both PRs implement request-level validation that awaits an async validator which invokes validateAuthContext to resolve/override account_id.
  • Merge to test to main #350: Both PRs convert per-endpoint validators into async, request-level validators that return either a NextResponse or validated object with integrated auth/account_id resolution logic.

Suggested reviewers

  • sweetmantech

Poem

📋 The request walked in with JSON so raw,
A validator emerged, a fresh unified law—
Parse, validate, resolve auth with care,
One handler to rule them, one place everywhere! ✨

🚥 Pre-merge checks | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Solid & Clean Code ⚠️ Warning The file validateCreateTaskBody.ts exports two functions with different responsibilities, violating SRP and breaking the established one-function-per-file naming convention used throughout the codebase. Move validateCreateTaskRequest() to a new file lib/tasks/validateCreateTaskRequest.ts to separate request-level validation from body-level validation and maintain codebase consistency.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch yuliusupwork/myc-4585-api-require-auth-and-identity-bound-ownership-for-post

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.

Copy link
Copy Markdown

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

🧹 Nitpick comments (2)
lib/tasks/validateCreateTaskBody.ts (1)

73-102: Split request-level validation into its own file to preserve SRP and naming consistency.

validateCreateTaskRequest introduces a second exported validator in a ...Body.ts module and is >20 lines while handling multiple responsibilities (JSON parse, body validate, auth validate, account override). Please move it to a dedicated file (for example, validateCreateTaskRequest.ts) and keep validateCreateTaskBody.ts focused on schema/body validation.

As per coding guidelines: lib/**/*.ts: "Apply Single Responsibility Principle (SRP): one exported function per file; each file should do one thing well", **/*.{js,ts,tsx,jsx}: "each file must export ONE primary function, and the file name must match that function", and **/*.{js,ts,tsx,jsx,py,java,cs,go,rb,php}: "Flag functions longer than 20 lines".

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@lib/tasks/validateCreateTaskBody.ts` around lines 73 - 102, The
validateCreateTaskRequest function in validateCreateTaskBody.ts mixes JSON
parsing, body validation, auth check and account override and must be moved to
its own file; create a new file named e.g. validateCreateTaskRequest.ts
exporting the single function validateCreateTaskRequest, have it call
validateCreateTaskBody(body) for schema validation and
validateAuthContext(request, { accountId: validatedBody.account_id }) for auth,
reuse getCorsHeaders for the JSON parse error response, and return the merged
object with account_id: auth.accountId; remove the validateCreateTaskRequest
export from validateCreateTaskBody.ts so that file only exports
validateCreateTaskBody.
lib/tasks/createTaskHandler.ts (1)

21-53: Consider trimming createTaskHandler to keep it under the 20-line guideline and more focused.

The handler currently mixes validation orchestration, persistence call, and response shaping. Extracting response builders (success/error) would keep this function tighter and easier to maintain.

As per coding guidelines: **/*.{js,ts,tsx,jsx,py,java,cs,go,rb,php}: "Flag functions longer than 20 lines" and lib/**/*.ts: "Single responsibility per function".

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@lib/tasks/createTaskHandler.ts` around lines 21 - 53, createTaskHandler is
doing validation, persistence and response shaping in one function; extract the
success and error response builders into small helpers (e.g.,
buildCreateTaskSuccessResponse and buildCreateTaskErrorResponse) and move the
NextResponse.json + getCorsHeaders logic into those helpers so createTaskHandler
only orchestrates validateCreateTaskRequest and createTask and returns the
helper results; keep existing behavior (return validated NextResponse early,
call createTask with validatedBody, log error in the catch and pass
error.message into the error builder) and reference createTaskHandler,
validateCreateTaskRequest, createTask, getCorsHeaders when locating where to
extract helpers.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@lib/tasks/createTaskHandler.ts`:
- Around line 21-53: createTaskHandler is doing validation, persistence and
response shaping in one function; extract the success and error response
builders into small helpers (e.g., buildCreateTaskSuccessResponse and
buildCreateTaskErrorResponse) and move the NextResponse.json + getCorsHeaders
logic into those helpers so createTaskHandler only orchestrates
validateCreateTaskRequest and createTask and returns the helper results; keep
existing behavior (return validated NextResponse early, call createTask with
validatedBody, log error in the catch and pass error.message into the error
builder) and reference createTaskHandler, validateCreateTaskRequest, createTask,
getCorsHeaders when locating where to extract helpers.

In `@lib/tasks/validateCreateTaskBody.ts`:
- Around line 73-102: The validateCreateTaskRequest function in
validateCreateTaskBody.ts mixes JSON parsing, body validation, auth check and
account override and must be moved to its own file; create a new file named e.g.
validateCreateTaskRequest.ts exporting the single function
validateCreateTaskRequest, have it call validateCreateTaskBody(body) for schema
validation and validateAuthContext(request, { accountId:
validatedBody.account_id }) for auth, reuse getCorsHeaders for the JSON parse
error response, and return the merged object with account_id: auth.accountId;
remove the validateCreateTaskRequest export from validateCreateTaskBody.ts so
that file only exports validateCreateTaskBody.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 6dc5a055-e9da-4b62-b26a-fdc18441ea59

📥 Commits

Reviewing files that changed from the base of the PR and between a3eec5d and c29d314.

⛔ Files ignored due to path filters (2)
  • lib/tasks/__tests__/createTaskHandler.test.ts is excluded by !**/*.test.*, !**/__tests__/** and included by lib/**
  • lib/tasks/__tests__/validateCreateTaskRequest.test.ts is excluded by !**/*.test.*, !**/__tests__/** and included by lib/**
📒 Files selected for processing (2)
  • lib/tasks/createTaskHandler.ts
  • lib/tasks/validateCreateTaskBody.ts

Copy link
Copy Markdown

@cubic-dev-ai cubic-dev-ai bot left a comment

Choose a reason for hiding this comment

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

4 issues found across 4 files

Confidence score: 4/5

  • This PR appears safe to merge with low functional risk; the reported issues are maintainability/style concerns rather than clear runtime bugs or regressions.
  • The highest-severity findings are in lib/tasks/validateCreateTaskBody.ts and indicate file-size/SRP convention drift, which can make future changes harder to reason about and review.
  • Test files lib/tasks/__tests__/validateCreateTaskRequest.test.ts and lib/tasks/__tests__/createTaskHandler.test.ts exceed the 100-line project guideline, which may reduce readability but is not likely to break behavior today.
  • Pay close attention to lib/tasks/validateCreateTaskBody.ts, lib/tasks/__tests__/validateCreateTaskRequest.test.ts, and lib/tasks/__tests__/createTaskHandler.test.ts - refactor for size/SRP alignment to keep maintenance risk from growing.
Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="lib/tasks/__tests__/createTaskHandler.test.ts">

<violation number="1" location="lib/tasks/__tests__/createTaskHandler.test.ts:1">
P2: Custom agent: **Enforce Clear Code Style and Maintainability Practices**

Newly added test file exceeds the rule’s 100-line maximum (120 lines), violating the maintainability size limit.</violation>
</file>

<file name="lib/tasks/__tests__/validateCreateTaskRequest.test.ts">

<violation number="1" location="lib/tasks/__tests__/validateCreateTaskRequest.test.ts:1">
P2: Custom agent: **Enforce Clear Code Style and Maintainability Practices**

New test module exceeds the Rule 3 file-length limit (<100 lines), reducing readability and maintainability.</violation>
</file>

<file name="lib/tasks/validateCreateTaskBody.ts">

<violation number="1" location="lib/tasks/validateCreateTaskBody.ts:73">
P2: Custom agent: **Enforce Clear Code Style and Maintainability Practices**

File exceeds the custom 100-line maintainability limit after PR additions.</violation>

<violation number="2" location="lib/tasks/validateCreateTaskBody.ts:73">
P2: Per the project's SRP convention, `validateCreateTaskRequest` should live in its own file `lib/tasks/validateCreateTaskRequest.ts`. The file-naming rule requires each file to export one primary function whose name matches the filename.</violation>
</file>
Architecture diagram
sequenceDiagram
    participant Client
    participant Handler as createTaskHandler
    participant Validator as validateCreateTaskRequest
    participant Auth as validateAuthContext
    participant DB as createTask (DB Service)

    Note over Client,DB: POST /api/tasks Flow

    Client->>Handler: POST request (JSON + Auth Headers)
    
    Handler->>Validator: NEW: validateCreateTaskRequest(request)
    
    Validator->>Validator: Parse JSON body
    alt Invalid JSON
        Validator-->>Handler: 400 Bad Request
        Handler-->>Client: Error response
    end

    Validator->>Validator: Zod schema validation
    alt Schema validation fails
        Validator-->>Handler: 400 Bad Request
        Handler-->>Client: Error response
    end

    Validator->>Auth: NEW: validateAuthContext(request, { accountId })
    Note right of Auth: Verifies API Key/JWT and<br/>identity-bound ownership
    
    alt Auth or Ownership failure
        Auth-->>Validator: 401 Unauthorized / 403 Forbidden
        Validator-->>Handler: Error Response
        Handler-->>Client: Error response
    else Auth Success
        Auth-->>Validator: Resolved Auth Context (accountId, etc.)
        Validator-->>Handler: Validated CreateTaskBody
    end

    Handler->>DB: createTask(validatedBody)
    
    alt DB Success
        DB-->>Handler: Created Task Record
        Handler-->>Client: 200 OK (Success + Task Data)
    else DB Failure (Exception)
        DB-->>Handler: Error
        Handler-->>Client: 500 Internal Server Error
    end
Loading

Reply with feedback, questions, or to request a fix. Tag @cubic-dev-ai to re-run a review, or fix all with cubic.

@@ -0,0 +1,120 @@
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
Copy link
Copy Markdown

@cubic-dev-ai cubic-dev-ai bot Apr 8, 2026

Choose a reason for hiding this comment

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

P2: Custom agent: Enforce Clear Code Style and Maintainability Practices

Newly added test file exceeds the rule’s 100-line maximum (120 lines), violating the maintainability size limit.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At lib/tasks/__tests__/createTaskHandler.test.ts, line 1:

<comment>Newly added test file exceeds the rule’s 100-line maximum (120 lines), violating the maintainability size limit.</comment>

<file context>
@@ -0,0 +1,120 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
+import { NextRequest, NextResponse } from "next/server";
+import { createTaskHandler } from "@/lib/tasks/createTaskHandler";
</file context>
Fix with Cubic

@@ -0,0 +1,257 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
Copy link
Copy Markdown

@cubic-dev-ai cubic-dev-ai bot Apr 8, 2026

Choose a reason for hiding this comment

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

P2: Custom agent: Enforce Clear Code Style and Maintainability Practices

New test module exceeds the Rule 3 file-length limit (<100 lines), reducing readability and maintainability.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At lib/tasks/__tests__/validateCreateTaskRequest.test.ts, line 1:

<comment>New test module exceeds the Rule 3 file-length limit (<100 lines), reducing readability and maintainability.</comment>

<file context>
@@ -0,0 +1,257 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import { NextRequest, NextResponse } from "next/server";
+import { validateCreateTaskRequest } from "@/lib/tasks/validateCreateTaskBody";
</file context>
Fix with Cubic

@@ -1,5 +1,6 @@
import { NextResponse } from "next/server";
import { NextRequest, NextResponse } from "next/server";
Copy link
Copy Markdown

@cubic-dev-ai cubic-dev-ai bot Apr 8, 2026

Choose a reason for hiding this comment

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

P2: Custom agent: Enforce Clear Code Style and Maintainability Practices

File exceeds the custom 100-line maintainability limit after PR additions.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At lib/tasks/validateCreateTaskBody.ts, line 73:

<comment>File exceeds the custom 100-line maintainability limit after PR additions.</comment>

<file context>
@@ -62,3 +63,40 @@ export function validateCreateTaskBody(body: unknown): NextResponse | CreateTask
+ * @param request - The incoming Next.js request
+ * @returns Error response or {@link CreateTaskBody} with account_id set from resolved auth context
+ */
+export async function validateCreateTaskRequest(
+  request: NextRequest,
+): Promise<NextResponse | CreateTaskBody> {
</file context>
Fix with Cubic

* @param request - The incoming Next.js request
* @returns Error response or {@link CreateTaskBody} with account_id set from resolved auth context
*/
export async function validateCreateTaskRequest(
Copy link
Copy Markdown

@cubic-dev-ai cubic-dev-ai bot Apr 8, 2026

Choose a reason for hiding this comment

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

P2: Per the project's SRP convention, validateCreateTaskRequest should live in its own file lib/tasks/validateCreateTaskRequest.ts. The file-naming rule requires each file to export one primary function whose name matches the filename.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At lib/tasks/validateCreateTaskBody.ts, line 73:

<comment>Per the project's SRP convention, `validateCreateTaskRequest` should live in its own file `lib/tasks/validateCreateTaskRequest.ts`. The file-naming rule requires each file to export one primary function whose name matches the filename.</comment>

<file context>
@@ -62,3 +63,40 @@ export function validateCreateTaskBody(body: unknown): NextResponse | CreateTask
+ * @param request - The incoming Next.js request
+ * @returns Error response or {@link CreateTaskBody} with account_id set from resolved auth context
+ */
+export async function validateCreateTaskRequest(
+  request: NextRequest,
+): Promise<NextResponse | CreateTaskBody> {
</file context>
Fix with Cubic

* @param body - The request body to validate.
* @returns A NextResponse with an error if validation fails, or the validated body if validation passes.
*/
export function validateCreateTaskBody(body: unknown): NextResponse | CreateTaskBody {
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

YAGNI principle

  • is this validateCreateTaskBody function still being used?

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants