Skip to content

fix: standardize credential ID naming and improve error handling acro…#68

Merged
TejaBudumuru3 merged 1 commit intomainfrom
debugs-fixing
Feb 3, 2026
Merged

fix: standardize credential ID naming and improve error handling acro…#68
TejaBudumuru3 merged 1 commit intomainfrom
debugs-fixing

Conversation

@TejaBudumuru3
Copy link
Contributor

@TejaBudumuru3 TejaBudumuru3 commented Feb 3, 2026

…ss routes and services

Summary by CodeRabbit

  • Bug Fixes

    • Fixed retry logic to properly terminate at the correct attempt count.
    • Improved handling of missing credentials during workflow execution with explicit error messaging.
  • Improvements

    • Standardized HTTP status codes across API responses for consistent error handling.
    • Enhanced authorization error responses for better clarity.

@coderabbitai
Copy link

coderabbitai bot commented Feb 3, 2026

📝 Walkthrough

Walkthrough

This PR standardizes HTTP status codes using constants across route files, renames credential-related fields from credId to credentialId throughout the codebase, migrates the ExecutionRegistry and type definitions from the worker to a shared nodes package, changes user identification from req.user.id to req.user.sub in routes, and enhances TypeScript type annotations for route handlers.

Changes

Cohort / File(s) Summary
Status Code Standardization
apps/http-backend/src/routes/google_callback.ts, sheet.routes.ts, userMiddleware.ts, userRoutes.ts
Replaced hardcoded HTTP status codes (200, 400, 401, 403, 500) with named constants from statusCodes for consistency across error and success responses.
Credential Field Renaming (credId → credentialId)
apps/http-backend/src/routes/sheet.routes.ts, apps/worker/src/engine/executor.ts, packages/nodes/src/common/google-oauth-service.ts, packages/nodes/src/gmail/gmail.executor.ts, packages/nodes/src/google-sheets/google-sheets.executor.ts, packages/nodes/src/registry/Execution.config.types.ts
Systematically renamed credential parameter from credId to credentialId across backend routes, worker executor, and node executors for naming consistency.
User Identifier Source Migration (req.user.id → req.user.sub)
apps/http-backend/src/routes/userRoutes/userRoutes.ts, executionRoutes.ts
Changed user identifier extraction from req.user.id to req.user.sub across multiple route handlers.
Route Handler Type Annotations
apps/http-backend/src/routes/userRoutes/userRoutes.ts
Added explicit Response type annotations to route handler signatures for improved TypeScript type safety in /getCredentials/:type, /create/workflow, /executeWorkflow, and other handlers.
Worker Registry Migration to Shared Package
apps/worker/src/engine/registory.ts, apps/worker/src/types.ts, apps/worker/src/tests/test.ts, executor.ts
Removed local ExecutionRegistry class and type definitions (ExecutionContext, ExecutionResult, NodeExecutor); updated test imports to use ExecutionRegister as register from @repo/nodes package. Added guard clause in executor for missing credentialsID.
Import and Logic Refinements
apps/http-backend/src/routes/userRoutes/userRoutes.ts, apps/processor/src/lib/retry.ts
Changed axios import from named/auxiliary to default import; adjusted retry termination condition from maxRetries - 1 to maxRetries; minor formatting adjustment in executionRoutes context object.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~40 minutes

Possibly related PRs

Suggested reviewers

  • Vamsi-o

Poem

🐰 Credentials now have prettier names, status codes stand proud,
From credId to credentialId, no more ambiguous clouds,
User IDs leap from id to sub, a shift subtle yet grand,
The registry hops to the shared package land!
hop hop

🚥 Pre-merge checks | ✅ 2 | ❌ 1
❌ Failed checks (1 warning)
Check name Status Explanation Resolution
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 accurately summarizes the main changes: standardizing credential ID naming (credId → credentialId) and replacing hardcoded status codes with constants across multiple files.

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

✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch debugs-fixing

Important

Action Needed: IP Allowlist Update

If your organization protects your Git platform with IP whitelisting, please add the new CodeRabbit IP address to your allowlist:

  • 136.113.208.247/32 (new)
  • 34.170.211.100/32
  • 35.222.179.152/32

Failure to add the new IP will result in interrupted reviews.


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

@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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (4)
apps/http-backend/src/routes/google_callback.ts (2)

202-237: ⚠️ Potential issue | 🟠 Major

Debug endpoint exposes sensitive credential metadata.

The /debug/credentials endpoint returns credential details including token presence, refresh token length, expiry dates, and scopes. While useful for development, this endpoint should be:

  1. Disabled or protected in production environments
  2. Restricted to admin users only

Consider adding environment checks or authentication guards.


133-135: ⚠️ Potential issue | 🟡 Minor

Hardcoded localhost URLs will break in production.

The redirect URLs are hardcoded to http://localhost:3000. These should be configurable via environment variables.

🔧 Proposed fix
+      const frontendUrl = process.env.FRONTEND_URL || "http://localhost:3000";
       // Redirect to workflow page if workflowId is provided, otherwise to general workflow page
       const redirectUrl = workflowId 
-        ? `http://localhost:3000/workflows/${workflowId}`
-        : "http://localhost:3000/workflow";
+        ? `${frontendUrl}/workflows/${workflowId}`
+        : `${frontendUrl}/workflow`;
apps/http-backend/src/routes/userRoutes/userRoutes.ts (2)

362-366: ⚠️ Potential issue | 🟡 Minor

Inconsistent status code: use UNAUTHORIZED instead of BAD_GATEWAY.

This route still uses BAD_GATEWAY for missing user authentication, while all other routes in this PR have been updated to use UNAUTHORIZED. This should be consistent.

Proposed fix
       if (!req.user)
         return res
-          .status(statusCodes.BAD_GATEWAY)
+          .status(statusCodes.UNAUTHORIZED)
           .json({ message: "User isnot logged in /not authorized" });

708-714: ⚠️ Potential issue | 🟡 Minor

Inconsistent user identifier: use req.user?.sub instead of req.user?.id.

All other routes in this PR have been updated to use req.user.sub, but this endpoint still uses req.user?.id. This may return undefined if the JWT payload doesn't have an id field.

Proposed fix
 router.get("/protected", userMiddleware, (req: AuthRequest, res) => {
   return res.json({
     ok: true,
-    userId: req.user?.id,
+    userId: req.user?.sub,
     email: req.user?.email,
   });
 });
🤖 Fix all issues with AI agents
In `@packages/nodes/src/common/google-oauth-service.ts`:
- Around line 92-97: The findFirst query using this.prisma.credential.findFirst
currently omits the user filter (credentialId is checked but userId is commented
out), allowing credential access by ID alone; restore and use the passed userId
in the where clause (e.g., include userId: userId alongside id: credentialId and
type: "google_oauth") so the query only returns credentials owned by the
requesting user, and ensure any callers still pass a validated userId parameter
when invoking the method that performs this lookup.
🧹 Nitpick comments (6)
apps/worker/src/tests/test.ts (2)

2-3: Remove commented-out import.

Since the local registory.ts file has been removed in this PR, the commented-out import is dead code and should be deleted.

🧹 Proposed fix
 import { executeWorkflow } from "../engine/executor.js";
-// import { register } from "../engine/registory.js";
 import { ExecutionRegister as register } from "@repo/nodes";

42-42: Add error handling to debug() call for consistency.

testDirect() has .catch(console.error) but debug() does not. An unhandled promise rejection from debug() will cause inconsistent behavior.

🧹 Proposed fix
-debug();
+debug().catch(console.error);
apps/http-backend/src/routes/userRoutes/executionRoutes.ts (1)

34-38: Minor formatting inconsistency: extra space before comma.

Line 36 has a trailing space before the comma (config: config ,) which is inconsistent with the rest of the codebase.

Also note that credentialsId is commented out. If credential support is needed for node execution, this should be addressed in a follow-up.

🧹 Proposed fix
             const context = {
                 userId: req.user.sub,
-                config: config ,
+                config: config,
                 // credentialsId: nodeData.CredentialsID  || ""
             }
packages/nodes/src/google-sheets/google-sheets.executor.ts (1)

5-10: Local interface duplicates shared type with different nullability.

NodeExecutionContext is defined locally with credentialId as required, but ExecutionContext in packages/nodes/src/registry/Execution.config.types.ts has credentialId?: string (optional). This inconsistency could cause issues if the executor is called without a credentialId.

Consider either:

  1. Importing and extending the shared ExecutionContext type, or
  2. Ensuring the local type matches the shared definition with proper guards
packages/nodes/src/gmail/gmail.executor.ts (1)

4-9: Local interface duplicates shared type.

Similar to google-sheets.executor.ts, this file defines a local NodeExecutionContext with credentialId as required. Consider importing from the shared types in packages/nodes/src/registry/Execution.config.types.ts to maintain consistency.

apps/http-backend/src/routes/sheet.routes.ts (1)

10-10: Consider aligning route parameter names with variable names.

The route paths use :cred while the code now uses credentialId. For consistency with the PR's naming standardization goal, consider renaming the route parameters:

-  "/getDocuments/:cred",
+  "/getDocuments/:credentialId",
-  "/getSheets/:cred/:sheetId",
+  "/getSheets/:credentialId/:sheetId",

Note: This is a breaking change if clients depend on the current URL structure.

Also applies to: 56-57

Comment on lines 92 to 97
const credentials = await this.prisma.credential.findFirst({
where: {
id: credId,
id: credentialId,
// userId: userId,
type: "google_oauth",
},
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Security concern: userId filter is commented out.

The userId is passed as a parameter but not used in the query filter (Line 95 is commented out). This means any user who knows a credentialId could potentially access credentials belonging to other users.

This is an authorization bypass risk. The query should verify that the credential belongs to the requesting user.

🔒 Proposed fix
       const credentials = await this.prisma.credential.findFirst({
         where: {
           id: credentialId,
-          // userId: userId,
+          userId: userId,
           type: "google_oauth",
         },
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const credentials = await this.prisma.credential.findFirst({
where: {
id: credId,
id: credentialId,
// userId: userId,
type: "google_oauth",
},
const credentials = await this.prisma.credential.findFirst({
where: {
id: credentialId,
userId: userId,
type: "google_oauth",
},
🤖 Prompt for AI Agents
In `@packages/nodes/src/common/google-oauth-service.ts` around lines 92 - 97, The
findFirst query using this.prisma.credential.findFirst currently omits the user
filter (credentialId is checked but userId is commented out), allowing
credential access by ID alone; restore and use the passed userId in the where
clause (e.g., include userId: userId alongside id: credentialId and type:
"google_oauth") so the query only returns credentials owned by the requesting
user, and ensure any callers still pass a validated userId parameter when
invoking the method that performs this lookup.

@TejaBudumuru3 TejaBudumuru3 merged commit 62d111d into main Feb 3, 2026
2 checks passed
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