Skip to content

fix: exclude sessionToken from sessions API response#1602

Open
Akshita-2307 wants to merge 2 commits into
nisshchayarathi:mainfrom
Akshita-2307:fix/session-api-expose-tokens-1543
Open

fix: exclude sessionToken from sessions API response#1602
Akshita-2307 wants to merge 2 commits into
nisshchayarathi:mainfrom
Akshita-2307:fix/session-api-expose-tokens-1543

Conversation

@Akshita-2307
Copy link
Copy Markdown

@Akshita-2307 Akshita-2307 commented Jun 1, 2026

The authenticated sessions endpoint returned full Prisma session records including sessionToken. Updated query to use select and return only id, expires, createdAt, and updatedAt.

Closes #1543

Summary by CodeRabbit

Release Notes

  • Bug Fixes

    • Sessions endpoint now returns only essential session fields for improved security and performance.
  • Tests

    • Added comprehensive test suite for patch validation service.

@vercel
Copy link
Copy Markdown

vercel Bot commented Jun 1, 2026

Someone is attempting to deploy a commit to the Nisshchaya's projects Team on Vercel.

A member of the Team first needs to authorize it.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Jun 1, 2026

Review Change Stack

📝 Walkthrough

Walkthrough

This PR addresses two independent concerns: restricting the sessions API to return only safe metadata fields (preventing session token exposure), and adding comprehensive test coverage for the PatchValidatorService validation logic.

Changes

Session API Field Restriction

Layer / File(s) Summary
Sessions endpoint Prisma select clause
app/api/auth/sessions/route.ts
The GET sessions endpoint adds a select clause to prisma.session.findMany that restricts returned fields to id, expires, createdAt, and updatedAt, preventing sensitive fields from being serialized in the API response.

PatchValidator Test Suite

Layer / File(s) Summary
PatchValidator test suite with factory and assertions
lib/services/__tests__/patch-validator.test.ts
A new Vitest test file introduces a makePatch factory helper and comprehensive test suite for PatchValidatorService.validatePatch, covering valid patches, confidence thresholds, syntax validation, file-type-aware checking, line ranges, and edge cases like empty suggestion bodies.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Possibly related issues

Suggested labels

gssoc:approved, level:intermediate, mentor:nisshchayarathi, GSSoC'26

Poem

🐰 A rabbit hops through session gates,
Picking only safe metadata states—
No tokens bare to hackers' gaze,
While patches dance through testing maze.
Security and tests align,
One PR keeps the burrow fine! 🐇

🚥 Pre-merge checks | ✅ 2 | ❌ 3

❌ Failed checks (3 warnings)

Check name Status Explanation Resolution
Linked Issues check ⚠️ Warning The PR implements only part of the requirements from issue #1543: it excludes sessionToken but selects only id, expires, createdAt, and updatedAt instead of the required id, expires, and userId fields. Additionally, no regression test was added as required. Add userId to the select projection and create a regression test to verify safe session selection, as specified in issue #1543.
Out of Scope Changes check ⚠️ Warning The PR includes a test file (patch-validator.test.ts) that is unrelated to the session API fix or issue #1543, appearing to be an out-of-scope addition to the changeset. Remove the patch-validator.test.ts file or move it to a separate PR, as it is not related to the session token exposure issue.
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'fix: exclude sessionToken from sessions API response' accurately summarizes the main security fix in the changeset—removing sensitive token exposure from the API response.

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

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

Comment @coderabbitai help to get the list of available commands and usage tips.

@github-actions github-actions Bot added the GSSoC'26 Part of GirlScript Summer of Code 2026 label Jun 1, 2026
@github-actions
Copy link
Copy Markdown

github-actions Bot commented Jun 1, 2026

🎉 Thanks for your contribution, @Akshita-2307!

Your PR has passed our automated GSSoC quality checks. Here's a quick summary:

Check Status
PR description ✅ Provided
PR title ✅ Meaningful
Linked issue ✅ Found
Change size ✅ Looks good (92 lines across 2 file(s))

A maintainer will review your PR soon. Please be patient and available for feedback. 💪

GSSoC'26 automation · Maintainer: @nisshchayarathi

1 similar comment
@github-actions
Copy link
Copy Markdown

github-actions Bot commented Jun 1, 2026

🎉 Thanks for your contribution, @Akshita-2307!

Your PR has passed our automated GSSoC quality checks. Here's a quick summary:

Check Status
PR description ✅ Provided
PR title ✅ Meaningful
Linked issue ✅ Found
Change size ✅ Looks good (92 lines across 2 file(s))

A maintainer will review your PR soon. Please be patient and available for feedback. 💪

GSSoC'26 automation · Maintainer: @nisshchayarathi

Copy link
Copy Markdown
Contributor

@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.

Actionable comments posted: 1

🧹 Nitpick comments (2)
lib/services/__tests__/patch-validator.test.ts (2)

6-16: ⚡ Quick win

Consider using a type-safe signature for the makePatch factory.

The factory currently uses Record<string, unknown> which accepts any property with any value, bypassing TypeScript's type checking. This can allow test data that doesn't match the actual patch interface to slip through at compile time.

♻️ Proposed refactor for type safety
-function makePatch(overrides: Record<string, unknown> = {}) {
+function makePatch(overrides: Partial<Parameters<typeof service.validatePatch>[0]> = {}) {
   return {
     file: "test.ts",
     suggestionBody: "const x = 1;",
     startLine: 1,
     endLine: 1,
     confidenceScore: 90,
     status: "pending" as const,
     ...overrides,
-  };
+  } as Parameters<typeof service.validatePatch>[0];
 }

Alternatively, if the Patch type is exported from types/self-healing.ts, you could import and use it directly:

import type { Patch } from "../../types/self-healing";

function makePatch(overrides: Partial<Patch> = {}): Patch {
  // ...
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@lib/services/__tests__/patch-validator.test.ts` around lines 6 - 16, Update
the makePatch factory to be type-safe by importing the Patch type (e.g. from
"../../types/self-healing") and changing the signature from makePatch(overrides:
Record<string, unknown> = {}) to makePatch(overrides: Partial<Patch> = {}):
Patch; inside the function keep the same defaults (file, suggestionBody,
startLine, endLine, confidenceScore, status) and spread overrides to produce and
return a value that conforms to Patch so TypeScript enforces correct test data.

25-31: Update confidence threshold expectation (it matches the implementation).

SELF_HEAL_CONFIDENCE_THRESHOLD is set to 85 in types/self-healing.ts, and validatePatch assigns low_confidence only when confidenceScore < SELF_HEAL_CONFIDENCE_THRESHOLD—so confidenceScore: 50 correctly hits low_confidence. Consider adding a boundary test for confidenceScore: 85 to ensure it does not become low_confidence.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@lib/services/__tests__/patch-validator.test.ts` around lines 25 - 31, Add a
boundary unit test to ensure validatePatch (the service.validatePatch function)
treats a confidenceScore equal to SELF_HEAL_CONFIDENCE_THRESHOLD as not
"low_confidence": create a new test similar to the existing one that calls
service.validatePatch(makePatch({ confidenceScore: 85 }), "const a = 0;") and
assert result.status is not "low_confidence" (or assert the expected status for
>= threshold); reference SELF_HEAL_CONFIDENCE_THRESHOLD (from
types/self-healing.ts), validatePatch, and makePatch to locate the code under
test.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@lib/services/__tests__/patch-validator.test.ts`:
- Around line 62-68: The test for empty suggestionBody uses a weak negative
assertion; update the assertion in the "should handle empty suggestionBody
gracefully" test to a specific positive expectation for
service.validatePatch(makePatch({ suggestionBody: "" }), "const a = 0;") — e.g.,
assert the exact expected status string ("valid", "invalid", or whatever the
intended outcome is) and/or specific result fields (like result.status ===
"valid" or result.error === null) instead of `.not.toBe("invalid_syntax")`;
locate the test block and replace the negative assertion with the precise
expected status/value for validatePatch to make the test deterministic.

---

Nitpick comments:
In `@lib/services/__tests__/patch-validator.test.ts`:
- Around line 6-16: Update the makePatch factory to be type-safe by importing
the Patch type (e.g. from "../../types/self-healing") and changing the signature
from makePatch(overrides: Record<string, unknown> = {}) to makePatch(overrides:
Partial<Patch> = {}): Patch; inside the function keep the same defaults (file,
suggestionBody, startLine, endLine, confidenceScore, status) and spread
overrides to produce and return a value that conforms to Patch so TypeScript
enforces correct test data.
- Around line 25-31: Add a boundary unit test to ensure validatePatch (the
service.validatePatch function) treats a confidenceScore equal to
SELF_HEAL_CONFIDENCE_THRESHOLD as not "low_confidence": create a new test
similar to the existing one that calls service.validatePatch(makePatch({
confidenceScore: 85 }), "const a = 0;") and assert result.status is not
"low_confidence" (or assert the expected status for >= threshold); reference
SELF_HEAL_CONFIDENCE_THRESHOLD (from types/self-healing.ts), validatePatch, and
makePatch to locate the code under test.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 4f9aae43-3800-4d2f-81b0-fecd0eb7a940

📥 Commits

Reviewing files that changed from the base of the PR and between 63ecb90 and 71285ba.

📒 Files selected for processing (2)
  • app/api/auth/sessions/route.ts
  • lib/services/__tests__/patch-validator.test.ts

Comment on lines +62 to +68
it("should handle empty suggestionBody gracefully", () => {
const result = service.validatePatch(
makePatch({ suggestionBody: "" }),
"const a = 0;"
);
expect(result.status).not.toBe("invalid_syntax");
});
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.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Strengthen the assertion for empty suggestionBody test.

The test uses .not.toBe("invalid_syntax") which is a weak negative assertion. If the service returns an unexpected status like "error" or "unknown", the test would still pass, potentially hiding bugs.

✅ Proposed fix to use a positive assertion
 it("should handle empty suggestionBody gracefully", () => {
   const result = service.validatePatch(
     makePatch({ suggestionBody: "" }),
     "const a = 0;"
   );
-  expect(result.status).not.toBe("invalid_syntax");
+  expect(result.status).toBe("valid");
 });

If the expected behavior for empty suggestionBody is different (e.g., it should return "invalid" or another specific status), update the assertion to match that expected behavior.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@lib/services/__tests__/patch-validator.test.ts` around lines 62 - 68, The
test for empty suggestionBody uses a weak negative assertion; update the
assertion in the "should handle empty suggestionBody gracefully" test to a
specific positive expectation for service.validatePatch(makePatch({
suggestionBody: "" }), "const a = 0;") — e.g., assert the exact expected status
string ("valid", "invalid", or whatever the intended outcome is) and/or specific
result fields (like result.status === "valid" or result.error === null) instead
of `.not.toBe("invalid_syntax")`; locate the test block and replace the negative
assertion with the precise expected status/value for validatePatch to make the
test deterministic.

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

Labels

GSSoC'26 Part of GirlScript Summer of Code 2026

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Session API exposes raw session tokens

1 participant