Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: keys setting vulns #2718

Merged
merged 3 commits into from
Dec 6, 2024
Merged

fix: keys setting vulns #2718

merged 3 commits into from
Dec 6, 2024

Conversation

ogzhanolguncu
Copy link
Contributor

@ogzhanolguncu ogzhanolguncu commented Dec 6, 2024

What does this PR do?

Fixes vulnerabilities in key settings, prevents the exposure of workspaceId to RPC.

Type of change

  • Bug fix (non-breaking change which fixes an issue)
  • Chore (refactoring code, technical debt, workflow improvements)
  • Enhancement (small improvements)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • This change requires a documentation update

How should this be tested?

  • Test A
  • Test B

Checklist

Required

  • Filled out the "How to test" section in this PR
  • Read Contributing Guide
  • Self-reviewed my own code
  • Commented on my code in hard-to-understand areas
  • Ran pnpm build
  • Ran pnpm fmt
  • Checked for warnings, there are none
  • Removed all console.logs
  • Merged the latest changes from main onto my branch with git pull origin main
  • My changes don't cause any responsiveness issues

Appreciated

  • If a UI change was made: Added a screen recording or screenshots to this PR
  • Updated the Unkey Docs if changes were necessary

Summary by CodeRabbit

  • New Features

    • The DefaultBytes and DefaultPrefix components have been updated to remove the workspaceId field, simplifying the form structure.
  • Bug Fixes

    • Enhanced error handling for the setDefaultBytes and setDefaultPrefix procedures by streamlining the input validation process.
  • Refactor

    • Adjusted the input schemas and props in both components to eliminate dependencies on workspaceId, improving overall functionality.

Copy link

changeset-bot bot commented Dec 6, 2024

⚠️ No Changeset found

Latest commit: b1ed43c

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

Copy link

vercel bot commented Dec 6, 2024

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
dashboard ✅ Ready (Inspect) Visit Preview 💬 Add feedback Dec 6, 2024 7:55pm
engineering ✅ Ready (Inspect) Visit Preview 💬 Add feedback Dec 6, 2024 7:55pm
play ✅ Ready (Inspect) Visit Preview 💬 Add feedback Dec 6, 2024 7:55pm
www ✅ Ready (Inspect) Visit Preview 💬 Add feedback Dec 6, 2024 7:55pm

Copy link
Contributor

coderabbitai bot commented Dec 6, 2024

📝 Walkthrough
📝 Walkthrough

Walkthrough

The changes in this pull request involve the removal of the workspaceId field from the DefaultBytes and DefaultPrefix components, including their respective form schemas and props. Additionally, the input schemas for the setDefaultApiBytes and setDefaultApiPrefix procedures have been updated to eliminate the workspaceId requirement. The overall control flow, error handling, and mutation logic remain unchanged, ensuring that the components continue to function correctly without the workspaceId dependency.

Changes

File Path Change Summary
apps/dashboard/app/(app)/apis/[apiId]/settings/default-bytes.tsx Removed workspaceId from Props, formSchema, and the form's JSX; defaultValues updated accordingly.
apps/dashboard/app/(app)/apis/[apiId]/settings/default-prefix.tsx Removed workspaceId from Props, formSchema, and the form's JSX; defaultValues updated accordingly.
apps/dashboard/lib/trpc/routers/api/setDefaultBytes.ts Removed workspaceId from input schema; adjusted mutation logic to not validate workspaceId.
apps/dashboard/lib/trpc/routers/api/setDefaultPrefix.ts Removed workspaceId from input schema; adjusted mutation logic to not validate workspaceId.

Possibly related PRs

Suggested labels

Bug, Needs Approval

Suggested reviewers

  • mcstepp
  • perkinsjr

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

github-actions bot commented Dec 6, 2024

Thank you for following the naming conventions for pull request titles! 🙏

Copy link
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: 0

🧹 Outside diff range and nitpick comments (2)
apps/dashboard/lib/trpc/routers/api/setDefaultPrefix.ts (1)

Line range hint 52-56: Improve audit log description accuracy

Based on previous feedback, the audit log description should focus on the actual change being made rather than including the workspaceId in the description.

-          description: `Changed ${keyAuth.workspaceId} default prefix from ${keyAuth.defaultPrefix} to ${input.defaultPrefix}`,
+          description: `Updated API default prefix from ${keyAuth.defaultPrefix} to ${input.defaultPrefix}`,
apps/dashboard/lib/trpc/routers/api/setDefaultBytes.ts (1)

Line range hint 57-61: Maintain consistency in audit log descriptions

For consistency with setDefaultPrefix changes, the audit log description should be simplified.

-          description: `Changed ${keyAuth.workspaceId} default byte size for keys from ${keyAuth.defaultBytes} to ${input.defaultBytes}`,
+          description: `Updated API default byte size from ${keyAuth.defaultBytes} to ${input.defaultBytes}`,
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between bca5871 and 78f9c47.

📒 Files selected for processing (4)
  • apps/dashboard/app/(app)/apis/[apiId]/settings/default-bytes.tsx (0 hunks)
  • apps/dashboard/app/(app)/apis/[apiId]/settings/default-prefix.tsx (1 hunks)
  • apps/dashboard/lib/trpc/routers/api/setDefaultBytes.ts (1 hunks)
  • apps/dashboard/lib/trpc/routers/api/setDefaultPrefix.ts (1 hunks)
💤 Files with no reviewable changes (1)
  • apps/dashboard/app/(app)/apis/[apiId]/settings/default-bytes.tsx
🧰 Additional context used
📓 Learnings (2)
apps/dashboard/lib/trpc/routers/api/setDefaultPrefix.ts (1)
Learnt from: chronark
PR: unkeyed/unkey#2146
File: apps/dashboard/lib/trpc/routers/api/setDefaultPrefix.ts:80-80
Timestamp: 2024-11-10T16:45:16.994Z
Learning: Ensure that audit log descriptions accurately reflect the action being performed, such as updating the `defaultPrefix`, and avoid incorrect references like 'name' when not applicable.
apps/dashboard/app/(app)/apis/[apiId]/settings/default-prefix.tsx (1)
Learnt from: chronark
PR: unkeyed/unkey#2146
File: apps/dashboard/app/(app)/apis/[apiId]/settings/default-prefix.tsx:74-75
Timestamp: 2024-11-10T16:45:16.994Z
Learning: In `apps/dashboard/app/(app)/apis/[apiId]/settings/default-prefix.tsx`, the hidden `<input>` elements for `workspaceId` and `keyAuthId` work correctly without being registered with React Hook Form.
🔇 Additional comments (4)
apps/dashboard/lib/trpc/routers/api/setDefaultPrefix.ts (1)

Line range hint 8-26: LGTM! Security improvement by removing workspaceId validation

The removal of workspaceId from input validation is a good security enhancement that prevents potential workspace-hopping attacks while maintaining proper authorization through keyAuth lookup.

apps/dashboard/lib/trpc/routers/api/setDefaultBytes.ts (1)

Line range hint 8-31: LGTM! Consistent security improvement

The changes align with setDefaultPrefix.ts, removing workspaceId from input validation while maintaining proper authorization and input validation for byte size.

apps/dashboard/app/(app)/apis/[apiId]/settings/default-prefix.tsx (2)

21-24: LGTM! Frontend changes align with security improvements

The removal of workspaceId from the form schema and Props type properly complements the backend security enhancements while maintaining all necessary functionality.

Also applies to: 26-31


Line range hint 1-1: Verify complete removal of workspaceId references

Let's ensure all workspaceId references have been properly removed from the codebase.

Copy link
Collaborator

@chronark chronark left a comment

Choose a reason for hiding this comment

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

this is not secure

Copy link
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

🧹 Outside diff range and nitpick comments (1)
apps/dashboard/lib/trpc/routers/api/setDefaultPrefix.ts (1)

Line range hint 64-83: Improve audit log description clarity.

While the audit logging is generally well-implemented, the description could be more explicit about what was changed.

Consider this minor improvement:

-          description: `Changed ${keyAuth.id} default prefix from ${keyAuth.defaultPrefix} to ${input.defaultPrefix}`,
+          description: `Updated API key default prefix for ${keyAuth.name || keyAuth.id} from "${keyAuth.defaultPrefix}" to "${input.defaultPrefix}"`,

This makes it clearer what was changed and uses quotes to make the prefix values more distinguishable, especially if they contain spaces.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 78f9c47 and 0c51ab1.

📒 Files selected for processing (2)
  • apps/dashboard/lib/trpc/routers/api/setDefaultBytes.ts (4 hunks)
  • apps/dashboard/lib/trpc/routers/api/setDefaultPrefix.ts (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/dashboard/lib/trpc/routers/api/setDefaultBytes.ts
🧰 Additional context used
📓 Learnings (1)
apps/dashboard/lib/trpc/routers/api/setDefaultPrefix.ts (1)
Learnt from: chronark
PR: unkeyed/unkey#2146
File: apps/dashboard/lib/trpc/routers/api/setDefaultPrefix.ts:80-80
Timestamp: 2024-11-10T16:45:16.994Z
Learning: Ensure that audit log descriptions accurately reflect the action being performed, such as updating the `defaultPrefix`, and avoid incorrect references like 'name' when not applicable.
🔇 Additional comments (2)
apps/dashboard/lib/trpc/routers/api/setDefaultPrefix.ts (2)

33-47: LGTM! Comprehensive error handling.

The error handling is thorough with appropriate error codes and user-friendly messages. The separation between workspace and keyAuth not found cases provides clear feedback.


Line range hint 48-64: LGTM! Well-structured transaction with proper error handling.

The transaction properly ensures atomicity between the update and audit logging. The use of the verified keyAuth.id from the workspace query maintains security.

Comment on lines 17 to 24
const workspace = await db.query.workspaces
.findFirst({
where: (table, { eq }) => eq(table.id, input.keyAuthId),
where: (table, { eq }) => eq(table.tenantId, ctx.tenant.id),
with: {
keySpaces: {
where: (table, { eq }) => eq(table.id, input.keyAuthId),
},
},
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Codebase verification

⚠️ Security concern: Multiple endpoints still expose workspaceId in input schemas

Several endpoints still accept workspaceId directly in their input schemas, which is inconsistent with the security improvement implemented in setDefaultPrefix.ts. These endpoints should be updated to use tenantId from context instead:

  • apps/dashboard/lib/trpc/routers/workspace/changePlan.ts
  • apps/dashboard/lib/trpc/routers/workspace/changeName.ts
  • apps/dashboard/lib/trpc/routers/key/updateRatelimit.ts
  • apps/dashboard/lib/trpc/routers/ratelimit/updateNamespaceName.ts
  • apps/dashboard/lib/trpc/routers/api/updateName.ts
  • apps/dashboard/lib/trpc/routers/api/updateIpWhitelist.ts
🔗 Analysis chain

LGTM! Secure workspace retrieval implementation.

The change from using workspaceId from input to tenantId from context is a good security improvement. The query is well-structured with proper type safety.

Let's verify that no direct workspaceId usage remains in similar endpoints:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any remaining direct workspaceId usage in API router input schemas
ast-grep --pattern 'input(
  z.object({
    $$$
    workspaceId: z.string(),
    $$$
  })
)'

Length of output: 94


Script:

#!/bin/bash
# Let's try a broader search for workspaceId in router input schemas
rg -l "workspaceId.*z\.string" apps/dashboard/lib/trpc/routers/

# Also search for direct workspaceId usage in query conditions
rg -l "workspaceId.*input\." apps/dashboard/lib/trpc/routers/

# Search for any remaining direct workspaceId references in API routers
ast-grep --pattern 'workspaceId: z.string()'

Length of output: 515


Script:

#!/bin/bash
# Let's examine the content of these files to see how workspaceId is used
for file in apps/dashboard/lib/trpc/routers/workspace/changePlan.ts \
           apps/dashboard/lib/trpc/routers/workspace/changeName.ts \
           apps/dashboard/lib/trpc/routers/key/updateRatelimit.ts \
           apps/dashboard/lib/trpc/routers/ratelimit/updateNamespaceName.ts \
           apps/dashboard/lib/trpc/routers/api/updateName.ts \
           apps/dashboard/lib/trpc/routers/api/updateIpWhitelist.ts; do
    echo "=== $file ==="
    rg "workspaceId.*z\.string|where.*workspaceId" -A 5 "$file"
done

Length of output: 5709

Copy link
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: 0

🧹 Outside diff range and nitpick comments (3)
apps/dashboard/lib/trpc/routers/api/setDefaultBytes.ts (3)

23-33: Improve error message specificity

The error message is generic and doesn't provide context about what operation failed. Consider making it more specific to help with debugging.

-            "We were unable to update the key auth. Please try again or contact support@unkey.dev",
+            "Failed to fetch key authentication details. Please try again or contact support@unkey.dev",

Line range hint 43-58: Consider adding defaultBytes null handling

While the input schema makes defaultBytes optional, the update logic might benefit from explicit null handling to clarify the intended behavior when defaultBytes is undefined.

 .set({
-            defaultBytes: input.defaultBytes,
+            defaultBytes: input.defaultBytes ?? null, // Explicit null handling
 })

Line range hint 59-76: Enhance audit log clarity

The audit log description could be more precise by handling undefined values and using a more structured format.

-          description: `Changed ${keyAuth.id} default byte size for keys from ${keyAuth.defaultBytes} to ${input.defaultBytes}`,
+          description: `Updated key auth ${keyAuth.id} default byte size from ${keyAuth.defaultBytes ?? 'unset'} to ${input.defaultBytes ?? 'unset'}`,
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 0c51ab1 and b1ed43c.

📒 Files selected for processing (2)
  • apps/dashboard/lib/trpc/routers/api/setDefaultBytes.ts (3 hunks)
  • apps/dashboard/lib/trpc/routers/api/setDefaultPrefix.ts (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/dashboard/lib/trpc/routers/api/setDefaultPrefix.ts
🔇 Additional comments (3)
apps/dashboard/lib/trpc/routers/api/setDefaultBytes.ts (3)

Line range hint 8-15: Security improvement: Removed workspaceId from input schema

Good job removing the workspaceId from the input schema. This prevents potential security vulnerabilities by ensuring workspace identification comes from the authenticated context rather than user input.


36-42: LGTM: Proper tenant isolation implemented

Good implementation of tenant isolation by checking keyAuth.workspace.tenantId against ctx.tenant.id. This ensures that users can only modify resources within their tenant.


Line range hint 1-85: Verify complete removal of workspaceId from RPC calls

Let's ensure there are no remaining instances of workspaceId being passed through RPC calls across the codebase.

✅ Verification successful

Based on the search results, I can now generate the final response:

No security concerns with workspaceId usage in RPC calls

The codebase shows that workspaceId is consistently used in a secure manner:

  • It's properly validated through Zod schemas in input validation
  • Access control is enforced by checking tenant/workspace ownership
  • It's primarily used for audit logging and internal database operations
  • No instances found where workspaceId is exposed in unsafe ways through RPC calls
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for potential workspaceId usage in RPC calls
echo "Checking for workspaceId in tRPC procedures..."
ast-grep --pattern 'procedure.input(z.object({ $$$workspaceId: z.string()$$$}))'

echo "Checking for workspaceId in API route handlers..."
rg -l 'workspaceId.*req\.body' 'apps/'

Length of output: 333


Script:

#!/bin/bash
# Let's try a broader search for workspaceId in procedure inputs
echo "Checking for workspaceId in tRPC procedures with a more flexible pattern..."
ast-grep --pattern 'procedure$$$input($$$workspaceId$$$)'

echo "Checking for direct workspaceId references in router files..."
rg -A 3 'workspaceId' 'apps/dashboard/lib/trpc/routers/'

echo "Checking for workspaceId in schema validations..."
rg -A 3 'workspaceId.*z\.' 'apps/dashboard/'

Length of output: 58935

@chronark chronark merged commit c1af9a3 into main Dec 6, 2024
24 of 26 checks passed
@chronark chronark deleted the vuln-fix-key-settings branch December 6, 2024 19:55
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.

3 participants