Skip to content

fix: updating a key's action should not work when it has been deleted#2897

Merged
chronark merged 3 commits intounkeyed:mainfrom
Nelwhix:Nelson-main-2
Feb 26, 2025
Merged

fix: updating a key's action should not work when it has been deleted#2897
chronark merged 3 commits intounkeyed:mainfrom
Nelwhix:Nelson-main-2

Conversation

@Nelwhix
Copy link
Contributor

@Nelwhix Nelwhix commented Feb 15, 2025

What does this PR do?

After a key has been soft-deleted, actions like:

  • updating the key,
  • updating the remaining usage limits
  • adding role/permssions
    still work. This PR eliminates that.

Fixes #2890

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?

  • Run the new test I added

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

  • Bug Fixes

    • Enhanced key management operations by ensuring that keys marked as deleted are now excluded. This change applies across endpoints, improving consistency by processing only active keys.
  • Tests

    • Added a test case to verify that update operations on soft-deleted keys correctly return a "not found" error.

@changeset-bot
Copy link

changeset-bot bot commented Feb 15, 2025

⚠️ No Changeset found

Latest commit: b8704ea

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

@vercel
Copy link

vercel bot commented Feb 15, 2025

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 Feb 26, 2025 8:26am
engineering ✅ Ready (Inspect) Visit Preview 💬 Add feedback Feb 26, 2025 8:26am
play ✅ Ready (Inspect) Visit Preview 💬 Add feedback Feb 26, 2025 8:26am
www ✅ Ready (Inspect) Visit Preview 💬 Add feedback Feb 26, 2025 8:26am

@vercel
Copy link

vercel bot commented Feb 15, 2025

@Nelwhix is attempting to deploy a commit to the Unkey Team on Vercel.

A member of the Team first needs to authorize it.

@github-actions github-actions bot added the Bug Something isn't working label Feb 15, 2025
@github-actions
Copy link
Contributor

github-actions bot commented Feb 15, 2025

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

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Feb 15, 2025

📝 Walkthrough

Walkthrough

This pull request updates multiple API routes that manage key operations by modifying database queries. The updated queries now include an additional condition to check that the deletedAt field is null, ensuring that only active (non-deleted) keys are processed. One new test case was added to verify that attempts to update a deleted key correctly return a 404 response.

Changes

Files Change Summary
apps/api/src/routes/v1_keys_addPermissions.ts
apps/api/src/routes/v1_keys_addRoles.ts
Modified key retrieval queries to include isNull(table.deletedAt) for filtering out deleted keys.
apps/api/src/routes/v1_keys_removePermissions.ts
apps/api/src/routes/v1_keys_removeRoles.ts
Updated query logic to add a condition on deletedAt to ensure only non-deleted keys are processed.
apps/api/src/routes/v1_keys_setPermissions.ts
apps/api/src/routes/v1_keys_setRoles.ts
Enhanced queries by adding a check that deletedAt is null when retrieving keys.
apps/api/src/routes/v1_keys_updateKey.ts
apps/api/src/routes/v1_keys_updateRemaining.ts
Revised queries to include the isNull(table.deletedAt) condition to filter out soft-deleted keys.
apps/api/src/routes/v1_keys_updateKey.error.test.ts Added a new test case to confirm that updating a deleted key returns a 404 error.

Sequence Diagram(s)

sequenceDiagram
  participant C as Client
  participant A as API Endpoint
  participant DB as Database
  participant R as Response Handler

  C->>A: Send request to update key
  A->>DB: Query key with conditions (workspaceId, keyId, isNull(deletedAt))
  DB-->>A: Return key record or null
  alt Key Found
      A->>R: Process update
      R-->>C: Return success response
  else Key Not Found
      A->>R: Return 404 error with key ID not found
      R-->>C: 404 Error Response
  end
Loading

Possibly related PRs

Suggested reviewers

  • mcstepp
  • chronark
  • perkinsjr
  • ogzhanolguncu
✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

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 generate docstrings to generate docstrings for this PR. (Beta)
  • @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.

@vercel vercel bot temporarily deployed to Preview – engineering February 15, 2025 21:52 Inactive
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 comments (2)
apps/api/src/routes/v1_keys_updateRemaining.ts (2)

164-166: 🛠️ Refactor suggestion

Add deletedAt check to final key lookup.

For consistency, the final key lookup should also include the deletedAt check to ensure we don't retrieve a key that was deleted during the update operation.

   const keyAfterUpdate = await db.readonly.query.keys.findFirst({
-    where: (table, { eq }) => eq(table.id, req.keyId),
+    where: (table, { eq, isNull, and }) => 
+      and(eq(table.id, req.keyId), isNull(table.deletedAt)),
   });

164-166: 🛠️ Refactor suggestion

Add deletedAt check to verification query.

For consistency, the verification query after the update should also include the deletedAt check.

   const keyAfterUpdate = await db.readonly.query.keys.findFirst({
-    where: (table, { eq }) => eq(table.id, req.keyId),
+    where: (table, { eq, isNull, and }) => and(eq(table.id, req.keyId), isNull(table.deletedAt)),
   });
🧹 Nitpick comments (3)
apps/api/src/routes/v1_keys_updateKey.ts (3)

296-299: Consider improving the error message for deleted keys.

The current error message doesn't distinguish between non-existent keys and deleted keys, which might confuse API consumers.

-      message: `key ${req.keyId} not found`,
+      message: `key ${req.keyId} not found or has been deleted`,

328-339: Consider extracting validation logic into a separate function.

The validation logic for refill settings could be more maintainable if extracted into a dedicated function.

+const validateRefillSettings = (req: V1KeysUpdateKeyRequest) => {
+  if (req.remaining === null && req.refill) {
+    throw new UnkeyApiError({
+      code: "BAD_REQUEST",
+      message: "Cannot set refill on a key with unlimited requests",
+    });
+  }
+  if (req.refill?.interval === "daily" && req.refill.refillDay) {
+    throw new UnkeyApiError({
+      code: "BAD_REQUEST",
+      message: "Cannot set 'refillDay' if 'interval' is 'daily'",
+    });
+  }
+}
+
 // In the route handler:
-if (req.remaining === null && req.refill) {
-  throw new UnkeyApiError({
-    code: "BAD_REQUEST",
-    message: "Cannot set refill on a key with unlimited requests",
-  });
-}
-if (req.refill?.interval === "daily" && req.refill.refillDay) {
-  throw new UnkeyApiError({
-    code: "BAD_REQUEST",
-    message: "Cannot set 'refillDay' if 'interval' is 'daily'",
-  });
-}
+validateRefillSettings(req);

343-405: Consider using a more type-safe approach for tracking changes.

The current implementation uses a generic Partial<Key> type for tracking changes. Consider using a more specific type that only includes the fields that can be updated.

+type UpdateableKeyFields = Pick<Key, 
+  'name' | 'meta' | 'identityId' | 'ownerId' | 'expires' | 
+  'remaining' | 'ratelimitAsync' | 'ratelimitLimit' | 
+  'ratelimitDuration' | 'refillAmount' | 'refillDay' | 
+  'lastRefillAt' | 'enabled'
+>;
-const changes: Partial<Key> = {};
+const changes: Partial<UpdateableKeyFields> = {};
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 20587d7 and d049776.

📒 Files selected for processing (9)
  • apps/api/src/routes/v1_keys_addPermissions.ts (1 hunks)
  • apps/api/src/routes/v1_keys_addRoles.ts (1 hunks)
  • apps/api/src/routes/v1_keys_removePermissions.ts (1 hunks)
  • apps/api/src/routes/v1_keys_removeRoles.ts (1 hunks)
  • apps/api/src/routes/v1_keys_setPermissions.ts (1 hunks)
  • apps/api/src/routes/v1_keys_setRoles.ts (1 hunks)
  • apps/api/src/routes/v1_keys_updateKey.error.test.ts (1 hunks)
  • apps/api/src/routes/v1_keys_updateKey.ts (1 hunks)
  • apps/api/src/routes/v1_keys_updateRemaining.ts (1 hunks)
🧰 Additional context used
🧠 Learnings (1)
apps/api/src/routes/v1_keys_updateKey.error.test.ts (1)
Learnt from: MichaelUnkey
PR: unkeyed/unkey#2114
File: apps/api/src/routes/v1_keys_updateKey.error.test.ts:0-0
Timestamp: 2024-11-10T16:45:16.994Z
Learning: In the `v1/keys.updateKey` endpoint, the server validates the refill configuration before checking if the key exists. Therefore, tests can assert validation errors without needing to create the key first.
🔇 Additional comments (17)
apps/api/src/routes/v1_keys_updateKey.error.test.ts (2)

82-117: LGTM! Well-structured test case.

The test case effectively verifies that attempting to update a deleted key returns a 404 response, aligning with the PR objective.


82-117: LGTM! Well-structured test case.

The test case effectively verifies that attempting to update a deleted key returns a 404 response, which aligns with the PR objective.

apps/api/src/routes/v1_keys_removeRoles.ts (2)

88-93: LGTM! Correctly prevents role removal from deleted keys.

The added isNull(table.deletedAt) check ensures that role removal operations cannot be performed on deleted keys.


88-93: LGTM! Correctly prevents role removal from deleted keys.

The query now includes the deletedAt check, ensuring that roles cannot be removed from soft-deleted keys.

apps/api/src/routes/v1_keys_removePermissions.ts (2)

88-93: LGTM! Correctly prevents permission removal from deleted keys.

The added isNull(table.deletedAt) check ensures that permission removal operations cannot be performed on deleted keys.


88-93: LGTM! Correctly prevents permission removal from deleted keys.

The query now includes the deletedAt check, ensuring that permissions cannot be removed from soft-deleted keys.

apps/api/src/routes/v1_keys_updateRemaining.ts (2)

70-71: LGTM! Correctly prevents updating remaining count for deleted keys.

The added isNull(table.deletedAt) check ensures that remaining count updates cannot be performed on deleted keys.


71-71: LGTM! Correctly prevents updating remaining count for deleted keys.

The query now includes the deletedAt check, ensuring that the remaining count cannot be updated for soft-deleted keys.

apps/api/src/routes/v1_keys_addPermissions.ts (1)

102-107: LGTM! Properly prevents operations on deleted keys.

The query now correctly checks for deletedAt being null, ensuring that permissions cannot be added to soft-deleted keys.

apps/api/src/routes/v1_keys_addRoles.ts (1)

115-120: LGTM! Properly prevents operations on deleted keys.

The query now correctly checks for deletedAt being null, ensuring that roles cannot be added to soft-deleted keys.

apps/api/src/routes/v1_keys_setRoles.ts (1)

129-134: LGTM! Properly prevents operations on deleted keys.

The query now correctly checks for deletedAt being null, ensuring that roles cannot be set on soft-deleted keys.

apps/api/src/routes/v1_keys_setPermissions.ts (1)

133-138: LGTM! Properly prevents operations on deleted keys.

The query now correctly checks for deletedAt being null, ensuring that permissions cannot be set on soft-deleted keys.

apps/api/src/routes/v1_keys_updateKey.ts (5)

284-293: LGTM! Query now correctly handles soft-deleted keys.

The addition of isNull(table.deletedAt) ensures that soft-deleted keys cannot be updated, which aligns with the PR objective.


295-307: Verify if identical error messages are intentional.

Both the "not found" and "wrong workspace" scenarios return the same error message. While this might be a security measure to prevent workspace enumeration, it could make debugging harder.

Please confirm if this is intentional. If not, consider using different error messages:

 if (key.workspaceId !== auth.authorizedWorkspaceId) {
   throw new UnkeyApiError({
     code: "NOT_FOUND",
-    message: `key ${req.keyId} not found`,
+    message: `key ${req.keyId} does not belong to this workspace`,
   });
 }

309-326: LGTM! Robust RBAC implementation.

The RBAC evaluation is thorough, with proper error handling and clear permission checks.


406-437: LGTM! Thorough audit logging and cache invalidation.

The implementation properly handles:

  • Audit logging with detailed metadata
  • Cache invalidation for both key hash and ID

439-446: LGTM! Efficient role and permission updates.

The implementation efficiently handles role and permission updates using Promise.all for concurrent execution.

@vercel vercel bot temporarily deployed to Preview – engineering February 17, 2025 15:36 Inactive
@chronark chronark enabled auto-merge February 26, 2025 08:22
@vercel vercel bot temporarily deployed to Preview – play February 26, 2025 08:24 Inactive
@vercel vercel bot temporarily deployed to Preview – www February 26, 2025 08:25 Inactive
@vercel vercel bot temporarily deployed to Preview – dashboard February 26, 2025 08:26 Inactive
@chronark chronark added this pull request to the merge queue Feb 26, 2025
Merged via the queue into unkeyed:main with commit dfb2660 Feb 26, 2025
25 checks passed
@coderabbitai coderabbitai bot mentioned this pull request Mar 17, 2025
18 tasks
@coderabbitai coderabbitai bot mentioned this pull request Jul 4, 2025
18 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Bug: Various Update Key endpoints allow for updating of deleted keys

2 participants