Skip to content

Bounty fix#79

Merged
Junman140 merged 3 commits intoPi-Defi-world:mainfrom
DavisVT:bounty-fix
Mar 26, 2026
Merged

Bounty fix#79
Junman140 merged 3 commits intoPi-Defi-world:mainfrom
DavisVT:bounty-fix

Conversation

@DavisVT
Copy link
Copy Markdown
Contributor

@DavisVT DavisVT commented Mar 25, 2026

closes #24

Summary by CodeRabbit

  • Bug Fixes

    • Improved API key permission validation to correctly handle stored permission values, reducing risk of permission-related errors and access inconsistencies.
  • Refactor

    • Internal permission handling rewritten to remove unsafe type assumptions and improve robustness and reliability of permission processing.

DavisVT added 2 commits March 25, 2026 07:45
Fixes issue Pi-Defi-world#24 - Replace unsafe 'as any' type cast with proper type inference.
The permissions parameter is already typed as string[], and Prisma will handle the
JSON serialization automatically without the need for type bypassing.
@drips-wave
Copy link
Copy Markdown

drips-wave bot commented Mar 25, 2026

@DavisVT Great news! 🎉 Based on an automated assessment of this PR, the linked Wave issue(s) no longer count against your application limits.

You can now already apply to more issues while waiting for a review of this PR. Keep up the great work! 🚀

Learn more about application limits

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Mar 25, 2026

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 71f2a195-cebf-4968-8e25-e0f4d1051a6c

📥 Commits

Reviewing files that changed from the base of the PR and between c4a7af5 and 32b0bf0.

📒 Files selected for processing (6)
  • src/config/env.ts
  • src/jobs/walletActivationJob.ts
  • src/services/pi/activationService.ts
  • src/services/pi/client.ts
  • src/services/wallet/index.ts
  • src/services/wallet/walletActivationService.ts
💤 Files with no reviewable changes (1)
  • src/services/wallet/index.ts
✅ Files skipped from review due to trivial changes (5)
  • src/config/env.ts
  • src/services/pi/activationService.ts
  • src/jobs/walletActivationJob.ts
  • src/services/wallet/walletActivationService.ts
  • src/services/pi/client.ts

📝 Walkthrough

Walkthrough

Replaces unsafe any casts for API key permissions by adding an exported PermissionScope union type and a validatePermissions() function; updates validateApiKey and generateApiKey to store/forward validated permissions. Other edits are formatting, minor refactors, and whitespace cleanup across PI and wallet services and config.

Changes

Cohort / File(s) Summary
Auth middleware
src/middleware/auth.ts
Added exported PermissionScope type and validatePermissions(permissions: unknown): string[]. validateApiKey now sets req.apiKey.permissions from the validator; generateApiKey passes permissions directly to Prisma create (removed any cast).
PI client & activation
src/services/pi/client.ts, src/services/pi/activationService.ts
Reformatted Axios header/key usage and request shapes, expanded error-message extraction, and collapsed conditional expressions — no behavioral changes.
Config
src/config/env.ts
Reformatted inline fallback parsing for minBalancePi (no logic change).
Jobs & Wallet services
src/jobs/walletActivationJob.ts, src/services/wallet/*
Whitespace/comment cleanup and removal of trailing blank lines only.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Possibly related PRs

Poem

I nibble at casts and tidy the lair, 🐇
Permissions now hop in rows so fair,
No more any to make things fray,
Clean code carrots line the way,
A little rabbit cheers today! 🎉

🚥 Pre-merge checks | ✅ 2 | ❌ 3

❌ Failed checks (1 warning, 2 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 60.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Title check ❓ Inconclusive The title 'Bounty fix' is vague and generic; it does not clearly convey the specific technical change or objective of the pull request. Consider using a more descriptive title such as 'Remove unsafe any cast from permissions validation' to clearly indicate the main technical change.
Out of Scope Changes check ❓ Inconclusive While most changes are focused on the permissions fix, additional formatting and whitespace changes in multiple files appear unrelated to the core objective. Clarify whether the whitespace and formatting changes in auth.ts, env.ts, client.ts, walletActivationJob.ts, activationService.ts, and walletActivationService.ts are intentional or should be separated into a distinct refactoring pull request.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Linked Issues check ✅ Passed The pull request successfully addresses the core objective from issue #24 by removing the unsafe 'as any' cast and implementing proper type validation for permissions.

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

✨ 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 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)
src/middleware/auth.ts (2)

159-176: Consider validating input permissions against PermissionScope.

While removing the as any cast is correct, there's no validation that incoming permissions strings are valid PermissionScope values. Invalid scope strings (e.g., typos like "p2p:raed") will be stored but will never match in requireSegmentScope, causing silent permission failures.

🛡️ Optional: Add input validation
+const VALID_SCOPES: readonly string[] = [
+  "p2p:read", "p2p:write", "p2p:admin",
+  "sme:read", "sme:write", "sme:admin",
+  "gateway:read", "gateway:write", "gateway:admin",
+  "enterprise:read", "enterprise:write", "enterprise:admin",
+] as const;
+
 export async function generateApiKey(
   userId?: string,
   permissions: string[] = [],
 ): Promise<string> {
+  const invalidScopes = permissions.filter((p) => !VALID_SCOPES.includes(p));
+  if (invalidScopes.length > 0) {
+    throw new AppError(`Invalid permission scopes: ${invalidScopes.join(", ")}`, 400);
+  }
+
   const crypto = await import("crypto");
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/middleware/auth.ts` around lines 159 - 176, The generateApiKey function
currently accepts a permissions: string[] and persists them directly (via
prisma.apiKey.create) without ensuring they are valid PermissionScope values;
update generateApiKey to validate each entry in permissions against the
PermissionScope enum/union (e.g., by checking membership in
Object.values(PermissionScope) or a permissionSet) and either filter out invalid
entries or throw a descriptive error, then persist only validated scopes so
downstream checks like requireSegmentScope will behave correctly; reference
generateApiKey, the permissions parameter, PermissionScope, and
prisma.apiKey.create when making the change.

49-61: Consider logging when permissions data is malformed.

If the database contains malformed permissions (non-array or mixed types), this function silently returns [], which will cause requireSegmentScope to deny access with a "Missing segment scope" error. Without logging, debugging such failures would be difficult.

🔧 Proposed fix to add debug logging
 function validatePermissions(permissions: unknown): string[] {
   if (!permissions) {
     return [];
   }

   if (Array.isArray(permissions)) {
-    return permissions.every((p) => typeof p === "string")
-      ? (permissions as string[])
-      : [];
+    if (permissions.every((p) => typeof p === "string")) {
+      return permissions as string[];
+    }
+    logger.warn("API key permissions array contains non-string elements", {
+      types: permissions.map((p) => typeof p),
+    });
+    return [];
   }

+  logger.warn("API key permissions field is not an array", {
+    type: typeof permissions,
+  });
   return [];
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/middleware/auth.ts` around lines 49 - 61, The validatePermissions
function currently swallows malformed permission values and returns an empty
array; update validatePermissions to log a warning/debug message whenever the
input is not an all-string array (e.g., non-array or array with non-string
members) including the raw permissions value and its type so it's visible when
requireSegmentScope denies access; locate validatePermissions in
src/middleware/auth.ts and add a concise logger call (use the module's existing
logger or console.warn/debug if none) that reports the malformed permissions
before returning [].
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@src/middleware/auth.ts`:
- Around line 159-176: The generateApiKey function currently accepts a
permissions: string[] and persists them directly (via prisma.apiKey.create)
without ensuring they are valid PermissionScope values; update generateApiKey to
validate each entry in permissions against the PermissionScope enum/union (e.g.,
by checking membership in Object.values(PermissionScope) or a permissionSet) and
either filter out invalid entries or throw a descriptive error, then persist
only validated scopes so downstream checks like requireSegmentScope will behave
correctly; reference generateApiKey, the permissions parameter, PermissionScope,
and prisma.apiKey.create when making the change.
- Around line 49-61: The validatePermissions function currently swallows
malformed permission values and returns an empty array; update
validatePermissions to log a warning/debug message whenever the input is not an
all-string array (e.g., non-array or array with non-string members) including
the raw permissions value and its type so it's visible when requireSegmentScope
denies access; locate validatePermissions in src/middleware/auth.ts and add a
concise logger call (use the module's existing logger or console.warn/debug if
none) that reports the malformed permissions before returning [].

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: a650f560-c7f3-4a4a-b86f-46be6e124b26

📥 Commits

Reviewing files that changed from the base of the PR and between b03a35e and c4a7af5.

📒 Files selected for processing (1)
  • src/middleware/auth.ts

@Junman140
Copy link
Copy Markdown
Member

@DavisVT cl failed

1 similar comment
@Junman140
Copy link
Copy Markdown
Member

@DavisVT cl failed

@DavisVT
Copy link
Copy Markdown
Contributor Author

DavisVT commented Mar 26, 2026

done

@Junman140

@Junman140 Junman140 merged commit 39d5485 into Pi-Defi-world:main Mar 26, 2026
1 of 2 checks passed
@Junman140
Copy link
Copy Markdown
Member

@DavisVT fix please

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.

any` cast for permissions

2 participants