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

feat: allows user to recover soft-deleted namespaces #2872

Open
wants to merge 2 commits into
base: main
Choose a base branch
from

Conversation

harshsbhat
Copy link
Contributor

@harshsbhat harshsbhat commented Feb 6, 2025

What does this PR do?

Fixes #2869

It allows users to recover the soft-deleted rate limit namespace without manual intervention. It does so by simply allowing users to create a namespace with the same name that was deleted previously.

https://www.loom.com/share/5ac200da139b4812b4cd3d43c85cb28b?sid=a9a427c0-0867-4061-bf2a-b7361a8ce813

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:
  1. Create a ratelimit namespace
  2. Delete the same namespace
  3. Try to create a namespace with the same name. See that your deleted namespace is recovered,

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

    • Introduced the ability to reactivate previously deactivated namespaces, ensuring seamless namespace reuse.
    • Expanded audit logging to capture key details during restoration events.
  • Bug Fixes

    • Enhanced error messaging for namespace operations, providing clearer feedback during failure scenarios.

Copy link

changeset-bot bot commented Feb 6, 2025

⚠️ No Changeset found

Latest commit: 66a0b7d

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 Feb 6, 2025

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

Name Status Preview Comments Updated (UTC)
engineering ✅ Ready (Inspect) Visit Preview 💬 Add feedback Feb 6, 2025 4:28pm

Copy link

vercel bot commented Feb 6, 2025

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

A member of the Team first needs to authorize it.

Copy link
Contributor

coderabbitai bot commented Feb 6, 2025

📝 Walkthrough

Walkthrough

The changes introduce logic in the createNamespace procedure to detect if a namespace exists in a soft-deleted state. If found, the code restores the namespace by setting its deletedAt field to null within a database transaction. Enhanced error handling using specific TRPCError messages and expanded audit logging for the restoration process are also included. The original creation logic remains in place when no soft-deleted namespace exists.

Changes

Files Change Summary
apps/dashboard/lib/trpc/routers/ratelimit/createNamespace.ts Added logic to check for soft-deleted namespaces, restore them by setting deletedAt to null within a transaction, and enhanced error handling and audit logging for restoration.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Server
    participant DB
    participant Audit

    Client->>Server: Request to create namespace (name X)
    Server->>DB: Query for soft-deleted namespace with name X
    alt Soft-deleted namespace exists
       DB-->>Server: Return soft-deleted record
       Server->>DB: Begin transaction to restore namespace (set deletedAt = null)
       DB-->>Server: Confirm update success
       Server->>Audit: Log restoration event
       Server-->>Client: Return restored namespace
    else Namespace not found or active
       Server->>DB: Create new namespace
       DB-->>Server: Return new namespace record
       Server->>Audit: Log creation event
       Server-->>Client: Return new namespace
    end
Loading

Assessment against linked issues

Objective Addressed Explanation
Allow recreation or restoration of a soft-deleted ratelimit namespace (#2869)

Tip

🌐 Web search-backed reviews and chat
  • We have enabled web search-based reviews and chat for all users. This feature allows CodeRabbit to access the latest documentation and information on the web.
  • You can disable this feature by setting web_search: false in the knowledge_base settings.
  • Please share any feedback in the Discord discussion.
✨ 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.

@github-actions github-actions bot added Bug Something isn't working Needs Approval Needs approval from Unkey labels Feb 6, 2025
Copy link
Contributor

github-actions bot commented Feb 6, 2025

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: 2

🧹 Nitpick comments (2)
apps/dashboard/lib/trpc/routers/ratelimit/createNamespace.ts (2)

82-98: Remove commented-out code

There is a block of commented-out code that appears to be unnecessary. It's generally a good practice to remove unused code to keep the codebase clean and maintainable. If this code is needed for future reference, consider adding a comment explaining its purpose.


165-165: Typo in error message

The error message has a typo: "We are unable to create namspace." The word "namespace" is misspelled.

Apply this diff to correct the typo:

   message:
-    "We are unable to create namspace. Please try again or contact support@unkey.dev",
+    "We are unable to create namespace. Please try again or contact support@unkey.dev",
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 3b7d228 and 66a0b7d.

📒 Files selected for processing (1)
  • apps/dashboard/lib/trpc/routers/ratelimit/createNamespace.ts (2 hunks)

Comment on lines +36 to +39
const isSoftDeleted = await db.query.ratelimitNamespaces
.findFirst({
where: (table, { and, eq }) => and(eq(table.name, input.name)),
})
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Security Issue: Scope namespace queries and updates to the workspace

The current implementation does not scope the namespace queries and updates to the current workspace. This could potentially allow users to access or restore namespaces from other workspaces, leading to a security vulnerability. Please ensure that all namespace queries and updates include a condition to match the workspaceId to ws.id.

Apply these diffs to scope the namespace queries and updates to the workspace:

Lines 36-39:

 const isSoftDeleted = await db.query.ratelimitNamespaces
   .findFirst({
-    where: (table, { and, eq }) => and(eq(table.name, input.name)),
+    where: (table, { and, eq }) => and(eq(table.name, input.name), eq(table.workspaceId, ws.id)),
   })
   .catch((_err) => {

Lines 50-53:

 const namespace = await db.query.ratelimitNamespaces
   .findFirst({
-    where: eq(schema.ratelimitNamespaces.name, input.name),
+    where: and(eq(schema.ratelimitNamespaces.name, input.name), eq(schema.ratelimitNamespaces.workspaceId, ws.id)),
   })
   .catch((_err) => {

Lines 69-73:

 await tx
   .update(schema.ratelimitNamespaces)
   .set({
     deletedAt: null,
   })
-  .where(eq(schema.ratelimitNamespaces.name, input.name))
+  .where(and(eq(schema.ratelimitNamespaces.name, input.name), eq(schema.ratelimitNamespaces.workspaceId, ws.id)))
   .catch((_err) => {

Also applies to: 50-53, 69-73

Comment on lines +36 to +123
const isSoftDeleted = await db.query.ratelimitNamespaces
.findFirst({
where: (table, { and, eq }) => and(eq(table.name, input.name)),
})
.catch((_err) => {
throw new TRPCError({
code: "INTERNAL_SERVER_ERROR",
message:
"We are unable to create a new namespace. Please try again or contact support@unkey.dev",
});
});

if (isSoftDeleted) {
const namespace = await db.query.ratelimitNamespaces
.findFirst({
where: eq(schema.ratelimitNamespaces.name, input.name),
})
.catch((_err) => {
throw new TRPCError({
code: "INTERNAL_SERVER_ERROR",
message:
"We were unable to find the namespace. Please try again or contact support@unkey.dev.",
});
});
if (!namespace) {
throw new TRPCError({
code: "NOT_FOUND",
message:
"We are unable to find the correct namespace. Please try again or contact support@unkey.dev.",
});
}
await db.transaction(async (tx) => {
await tx
.update(schema.ratelimitNamespaces)
.set({
deletedAt: null,
})
.where(eq(schema.ratelimitNamespaces.name, input.name))
.catch((_err) => {
throw new TRPCError({
code: "INTERNAL_SERVER_ERROR",
message:
"We were unable to update the namespace. Please try again or contact support@unkey.dev.",
});
});

// const overrides = await tx.query.ratelimitOverrides.findMany({
// where: (table, { eq }) => eq(table.namespaceId, namespace.id),
// columns: { id: true },
// });
// if (overrides.length > 0) {
// await tx
// .update(schema.ratelimitOverrides)
// .set({ deletedAt: null })
// .where(eq(schema.ratelimitOverrides.namespaceId, namespace.id))
// .catch((_err) => {
// throw new TRPCError({
// code: "INTERNAL_SERVER_ERROR",
// message:
// "We are unable to recover the namespaces. Please try again or contact support@unkey.dev",
// });
// });
// }

await insertAuditLogs(tx, {
workspaceId: ws.id,
actor: {
type: "user",
id: ctx.user.id,
},
event: "ratelimitNamespace.create",
description: `Restored ${namespace.id}`,
resources: [
{
type: "ratelimitNamespace",
id: namespace.id,
},
],
context: {
location: ctx.audit.location,
userAgent: ctx.audit.userAgent,
},
});
});
return {
id: namespace.id,
};
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Logic Error: Handle existing namespaces that are not deleted

The current implementation restores any namespace with the given name, without checking if it is already active (i.e., not soft-deleted). This can lead to unexpected behavior if a namespace with the same name already exists and is not deleted. Before attempting to restore a soft-deleted namespace, you should check if an active namespace with the same name already exists in the current workspace. If it does, throw a PRECONDITION_FAILED error indicating that the namespace name is already in use.

Apply this diff to correct the logic:

Modify the initial namespace lookup to include the workspace ID and fetch the deletedAt field:

Lines 36-39:

 const existingNamespace = await db.query.ratelimitNamespaces
   .findFirst({
+    where: (table, { and, eq }) => and(eq(table.name, input.name), eq(table.workspaceId, ws.id)),
+    columns: {
+      id: true,
+      deletedAt: true,
+    },
   })
   .catch((_err) => {

Then, adjust the logic to handle different cases:

Lines 48-123:

 if (existingNamespace) {
+  if (existingNamespace.deletedAt === null) {
+    throw new TRPCError({
+      code: "PRECONDITION_FAILED",
+      message: "Duplicate namespace name. Please use a unique name for each namespace.",
+    });
+  }

-  const namespace = await db.query.ratelimitNamespaces
-    .findFirst({
-      where: eq(schema.ratelimitNamespaces.name, input.name),
-    })
-    .catch((_err) => {
-      throw new TRPCError({
-        code: "INTERNAL_SERVER_ERROR",
-        message:
-          "We were unable to find the namespace. Please try again or contact support@unkey.dev.",
-      });
-    });
-  if (!namespace) {
-    throw new TRPCError({
-      code: "NOT_FOUND",
-      message:
-        "We are unable to find the correct namespace. Please try again or contact support@unkey.dev.",
-    });
-  }

   await db.transaction(async (tx) => {
     await tx
       .update(schema.ratelimitNamespaces)
       .set({
         deletedAt: null,
       })
       .where(
         and(
           eq(schema.ratelimitNamespaces.name, input.name),
           eq(schema.ratelimitNamespaces.workspaceId, ws.id)
         )
       )
       .catch((_err) => {
         throw new TRPCError({
           code: "INTERNAL_SERVER_ERROR",
           message:
             "We were unable to update the namespace. Please try again or contact support@unkey.dev.",
         });
       });

     await insertAuditLogs(tx, {
       workspaceId: ws.id,
       actor: {
         type: "user",
         id: ctx.user.id,
       },
       event: "ratelimitNamespace.create",
-      description: `Restored ${namespace.id}`,
+      description: `Restored ${existingNamespace.id}`,
       resources: [
         {
           type: "ratelimitNamespace",
-          id: namespace.id,
+          id: existingNamespace.id,
         },
       ],
       context: {
         location: ctx.audit.location,
         userAgent: ctx.audit.userAgent,
       },
     });
   });
   return {
-    id: namespace.id,
+    id: existingNamespace.id,
   };
 }
📝 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 isSoftDeleted = await db.query.ratelimitNamespaces
.findFirst({
where: (table, { and, eq }) => and(eq(table.name, input.name)),
})
.catch((_err) => {
throw new TRPCError({
code: "INTERNAL_SERVER_ERROR",
message:
"We are unable to create a new namespace. Please try again or contact support@unkey.dev",
});
});
if (isSoftDeleted) {
const namespace = await db.query.ratelimitNamespaces
.findFirst({
where: eq(schema.ratelimitNamespaces.name, input.name),
})
.catch((_err) => {
throw new TRPCError({
code: "INTERNAL_SERVER_ERROR",
message:
"We were unable to find the namespace. Please try again or contact support@unkey.dev.",
});
});
if (!namespace) {
throw new TRPCError({
code: "NOT_FOUND",
message:
"We are unable to find the correct namespace. Please try again or contact support@unkey.dev.",
});
}
await db.transaction(async (tx) => {
await tx
.update(schema.ratelimitNamespaces)
.set({
deletedAt: null,
})
.where(eq(schema.ratelimitNamespaces.name, input.name))
.catch((_err) => {
throw new TRPCError({
code: "INTERNAL_SERVER_ERROR",
message:
"We were unable to update the namespace. Please try again or contact support@unkey.dev.",
});
});
// const overrides = await tx.query.ratelimitOverrides.findMany({
// where: (table, { eq }) => eq(table.namespaceId, namespace.id),
// columns: { id: true },
// });
// if (overrides.length > 0) {
// await tx
// .update(schema.ratelimitOverrides)
// .set({ deletedAt: null })
// .where(eq(schema.ratelimitOverrides.namespaceId, namespace.id))
// .catch((_err) => {
// throw new TRPCError({
// code: "INTERNAL_SERVER_ERROR",
// message:
// "We are unable to recover the namespaces. Please try again or contact support@unkey.dev",
// });
// });
// }
await insertAuditLogs(tx, {
workspaceId: ws.id,
actor: {
type: "user",
id: ctx.user.id,
},
event: "ratelimitNamespace.create",
description: `Restored ${namespace.id}`,
resources: [
{
type: "ratelimitNamespace",
id: namespace.id,
},
],
context: {
location: ctx.audit.location,
userAgent: ctx.audit.userAgent,
},
});
});
return {
id: namespace.id,
};
}
const existingNamespace = await db.query.ratelimitNamespaces
.findFirst({
where: (table, { and, eq }) => and(eq(table.name, input.name), eq(table.workspaceId, ws.id)),
columns: {
id: true,
deletedAt: true,
},
})
.catch((_err) => {
throw new TRPCError({
code: "INTERNAL_SERVER_ERROR",
message:
"We are unable to create a new namespace. Please try again or contact support@unkey.dev",
});
});
if (existingNamespace) {
if (existingNamespace.deletedAt === null) {
throw new TRPCError({
code: "PRECONDITION_FAILED",
message: "Duplicate namespace name. Please use a unique name for each namespace.",
});
}
await db.transaction(async (tx) => {
await tx
.update(schema.ratelimitNamespaces)
.set({
deletedAt: null,
})
.where(
and(
eq(schema.ratelimitNamespaces.name, input.name),
eq(schema.ratelimitNamespaces.workspaceId, ws.id)
)
)
.catch((_err) => {
throw new TRPCError({
code: "INTERNAL_SERVER_ERROR",
message:
"We were unable to update the namespace. Please try again or contact support@unkey.dev.",
});
});
await insertAuditLogs(tx, {
workspaceId: ws.id,
actor: {
type: "user",
id: ctx.user.id,
},
event: "ratelimitNamespace.create",
description: `Restored ${existingNamespace.id}`,
resources: [
{
type: "ratelimitNamespace",
id: existingNamespace.id,
},
],
context: {
location: ctx.audit.location,
userAgent: ctx.audit.userAgent,
},
});
});
return {
id: existingNamespace.id,
};
}

Copy link
Collaborator

chronark commented Feb 6, 2025

Don’t think we can do it like that

Now we reuse the id, which shows up in audit logs and logs

Rather than recovering it, we should have a way to permanently delete it

Copy link
Collaborator

chronark commented Feb 6, 2025

That’s why I asked about your approach before you tried to implement it.

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.

See replies

@harshsbhat
Copy link
Contributor Author

@chronark

It's alright. I was having a hard time explaining the approach. So decided to create PR so that we can have something visual to discuss.

By permanent delete you mean deleting it completely instead of keeping track of the soft delete using deleted_at? That would not allow the users to ever recover the namespace without manual intervention.

@chronark
Copy link
Collaborator

@harshsbhat yes, we should return an error explianing why there's a conflict and offer a solution

  • either a way to hard delete it
  • ask support

I'm not yet sure how I'd like to let users do it themselves, we're open to suggestions.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Bug Something isn't working Needs Approval Needs approval from Unkey
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Soft deleting a ratelimit namespace causes an error if the same name is used again.
2 participants