Skip to content

fix: allow 0 for ratelimit limit #2948

Merged
chronark merged 3 commits intomainfrom
eng-1661-allow-ratelimit-overrides-to-have-a-limit-of-0-effectively
Mar 12, 2025
Merged

fix: allow 0 for ratelimit limit #2948
chronark merged 3 commits intomainfrom
eng-1661-allow-ratelimit-overrides-to-have-a-limit-of-0-effectively

Conversation

@MichaelUnkey
Copy link
Collaborator

@MichaelUnkey MichaelUnkey commented Mar 11, 2025

What does this PR do?

Fixes # (issue)
Eng-1661

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?

Ensure ratelimit limit can be 0 or greater.
Ratelimit still functions as it should.

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 rate limit setting has been updated to require a positive integer, disallowing a value of 0.
    • Error messages have been refined across API endpoints and dashboard interfaces to clearly indicate that the limit should be greater than 0.

@linear
Copy link

linear bot commented Mar 11, 2025

@changeset-bot
Copy link

changeset-bot bot commented Mar 11, 2025

⚠️ No Changeset found

Latest commit: 862a372

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 Mar 11, 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 Mar 11, 2025 7:44pm
engineering ✅ Ready (Inspect) Visit Preview 💬 Add feedback Mar 11, 2025 7:44pm
play ✅ Ready (Inspect) Visit Preview 💬 Add feedback Mar 11, 2025 7:44pm
www ✅ Ready (Inspect) Visit Preview 💬 Add feedback Mar 11, 2025 7:44pm

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Mar 11, 2025

📝 Walkthrough

Walkthrough

This pull request updates several validation schemas across the API and dashboard codebases. The changes modify the constraint on the limit (or ratelimitLimit) property, changing it from a requirement of a nonnegative integer (including 0) to enforcing that it must be a positive integer (minimum value of 1). These adjustments affect validation logic in both backend routes and frontend form validations, along with corresponding error messaging changes.

Changes

Files Change Summary
apps/api/src/routes/schema.ts, apps/api/src/routes/v1_keys_createKey.ts, apps/api/src/routes/v1_keys_updateKey.ts, apps/api/src/routes/v1_ratelimits_limit.ts, apps/api/src/routes/v1_ratelimits_setOverride.ts Updated validation for the limit property in various API route schemas by changing from nonnegative() to min(1) or positive(), disallowing 0 as a valid value.
apps/dashboard/app/(app)/apis/[apiId]/keys/[keyAuthId]/[keyId]/settings/update-key-ratelimit.tsx, apps/dashboard/app/(app)/apis/[apiId]/keys/[keyAuthId]/new/validation.ts Modified frontend form validation schemas for rate limit settings. Changed error messages and validation rules for ratelimitLimit to require positive integers instead of allowing nonnegative integers.
apps/dashboard/lib/trpc/routers/key/create.ts, apps/dashboard/lib/trpc/routers/key/updateRatelimit.ts Adjusted validation schemas within TRPC procedures to require positive integers for the limit or ratelimitLimit parameter, replacing previous allowances for zero.
apps/dashboard/app/(app)/ratelimits/[namespaceId]/_components/identifier-dialog.tsx Updated validation for the limit field to require a minimum of 1, changing from nonnegative() to min(1), and refined footer rendering for styling consistency.

Possibly related PRs

  • feat: allow-developer-to-set-a-custom-refill-time-when-using-the #2114: The changes in the main PR and the retrieved PR are related as both modify the validation logic for the limit property, enforcing it to be a positive integer, although they are applied in different contexts.
  • fix: updating name does not affect ratelimits #2693: The changes in the main PR and the retrieved PR are related as both modify the validation logic for the limit property in the context of rate limiting, specifically in the v1_keys_updateKey.ts file.
  • fix: create key toggle issue #2711: The changes in the main PR and the retrieved PR are related as both modify the validation logic for the limit property, enforcing that it must be a positive integer, although they are in different contexts (one in a schema and the other in a form validation).

Suggested labels

Bug, Needs Approval

Suggested reviewers

  • mcstepp
  • chronark
  • perkinsjr
  • ogzhanolguncu

📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 09ae21e and 862a372.

📒 Files selected for processing (2)
  • apps/dashboard/app/(app)/ratelimits/[namespaceId]/_components/identifier-dialog.tsx (3 hunks)
  • apps/dashboard/app/(app)/ratelimits/[namespaceId]/_components/identifier-dialog.tsx (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • apps/dashboard/app/(app)/ratelimits/[namespaceId]/_components/identifier-dialog.tsx
  • apps/dashboard/app/(app)/ratelimits/[namespaceId]/_components/identifier-dialog.tsx
⏰ Context from checks skipped due to timeout of 90000ms (7)
  • GitHub Check: Test API / API Test Local
  • GitHub Check: Test Go API Local / test_agent_local
  • GitHub Check: Test Agent Local / test_agent_local
  • GitHub Check: Test Packages / Test ./internal/clickhouse
  • GitHub Check: Build / Build
  • GitHub Check: autofix
  • GitHub Check: Analyze (javascript-typescript)

🪧 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.
  • @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
Copy link
Contributor

github-actions bot commented Mar 11, 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: 0

🧹 Nitpick comments (3)
apps/dashboard/app/(app)/apis/[apiId]/keys/[keyAuthId]/[keyId]/settings/update-key-ratelimit.tsx (1)

47-47: Validation updated to allow zero rate limit.

The validation for the ratelimitLimit field has been changed to accept non-negative values (including zero) instead of strictly positive values. However, the error message still mentions "positive number" while adding "or 0" which could be slightly confusing.

Consider updating the error message to be more precise:

-    .nonnegative({ message: "This refill limit must be a positive number or 0." })
+    .nonnegative({ message: "This refill limit must be a non-negative number." })
apps/api/src/routes/v1_keys_createKey.ts (2)

168-168: Update to allow zero-value rate limits

The validation has been changed from requiring a minimum of 1 to allowing any non-negative integer (including 0) for the rate limit. This change aligns with the PR objective to "fix: allow 0 for ratelimit limit".

While the implementation is correct, consider adding documentation to clarify what a rate limit of 0 means in this context (e.g., does it mean unlimited requests or no requests allowed?).

 limit: z.number().int().nonnegative().openapi({
   description: "The total amount of requests in a given interval.",
+  example: 10,
+  // A rate limit of 0 means [explain behavior here]
 }),

311-316:

Details

❓ Verification inconclusive

Consider aligning validation logic for consistency

The code allows ratelimit.limit to be 0 but explicitly disallows remaining to be 0. This inconsistency could be confusing for API users.

Consider either:

  1. Aligning the validation to allow 0 for both properties
  2. Adding a comment explaining why these properties have different validation rules

🏁 Script executed:

#!/bin/bash
# Search for any other instances where similar validation happens for ratelimit properties
rg -A 3 "if \(.*ratelimit.*limit.*===.*0\)" --glob "*.ts"
rg -A 3 "if \(.*remaining.*===.*0\)" --glob "*.ts"

Length of output: 422


Action Required: Clarify/Align Validation for remaining vs ratelimit.limit

It appears that while the code enforces a strict rule for req.remaining (rejecting a value of 0), there is no similar validation for ratelimit.limit (which implicitly allows 0). This inconsistency could lead to confusion for API users regarding what constitutes valid input.

Please consider either of the following:

  • Align the validation logic: Adjust the code so that both remaining and ratelimit.limit are treated consistently (e.g., allowing 0 values if that’s the intended behavior).
  • Document the divergence: Add an inline comment explaining why 0 is disallowed for remaining but permitted for ratelimit.limit to clarify the design intent for future maintainers and API consumers.

File: apps/api/src/routes/v1_keys_createKey.ts (Lines 311-316)

    if (req.remaining === 0) {
      throw new UnkeyApiError({
        code: "BAD_REQUEST",
        message: "remaining must be greater than 0.",
      });
    }

Please verify that the current behavior is intentional and update either the validation logic or documentation as needed.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 6434efd and f530a9c.

📒 Files selected for processing (9)
  • apps/api/src/routes/schema.ts (1 hunks)
  • apps/api/src/routes/v1_keys_createKey.ts (1 hunks)
  • apps/api/src/routes/v1_keys_updateKey.ts (1 hunks)
  • apps/api/src/routes/v1_ratelimits_limit.ts (1 hunks)
  • apps/api/src/routes/v1_ratelimits_setOverride.ts (1 hunks)
  • apps/dashboard/app/(app)/apis/[apiId]/keys/[keyAuthId]/[keyId]/settings/update-key-ratelimit.tsx (1 hunks)
  • apps/dashboard/app/(app)/apis/[apiId]/keys/[keyAuthId]/new/validation.ts (1 hunks)
  • apps/dashboard/lib/trpc/routers/key/create.ts (1 hunks)
  • apps/dashboard/lib/trpc/routers/key/updateRatelimit.ts (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (14)
  • GitHub Check: Test Packages / Test ./internal/keys
  • GitHub Check: Test Packages / Test ./packages/rbac
  • GitHub Check: Test Packages / Test ./internal/clickhouse
  • GitHub Check: Test Packages / Test ./packages/cache
  • GitHub Check: Test Packages / Test ./internal/resend
  • GitHub Check: Test Go API Local / test_agent_local
  • GitHub Check: Test Packages / Test ./packages/api
  • GitHub Check: Test Packages / Test ./packages/hono
  • GitHub Check: Test Packages / Test ./packages/nextjs
  • GitHub Check: Test Agent Local / test_agent_local
  • GitHub Check: Test API / API Test Local
  • GitHub Check: Build / Build
  • GitHub Check: autofix
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (10)
apps/api/src/routes/v1_ratelimits_setOverride.ts (1)

38-38: Correct implementation for allowing zero as a valid rate limit.

The change from positive() to nonnegative() properly allows the rate limit to be set to 0, aligning with the PR objective to fix issue Eng-1661.

apps/dashboard/lib/trpc/routers/key/create.ts (1)

42-42: LGTM - Validation properly updated to allow zero rate limits.

The schema validation now correctly accepts zero as a valid rate limit value while maintaining type safety.

apps/dashboard/lib/trpc/routers/key/updateRatelimit.ts (1)

14-14: Validation correctly updated to allow zero rate limits.

The change to use nonnegative() instead of positive() appropriately allows the rate limit to be set to 0, while maintaining the optional nature of the field.

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

107-107: Schema correctly updated to allow zero rate limits.

Good change from min(1) to nonnegative() in the keySchema. This change is consistent with the other files and correctly implements the fix for Eng-1661.

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

35-35: Validation updated to allow zero rate limit.

The validation for the limit field now allows zero as a valid value, which is consistent with the PR objective of fixing issue Eng-1661. This change provides greater flexibility by enabling users to set a rate limit of 0, effectively creating a way to block all requests in a namespace when needed.

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

94-94: Validation updated to allow zero rate limit.

The validation for the limit property within the ratelimit object now accepts non-negative integers (including zero) instead of requiring strictly positive values. This change is consistent with the PR objective and with similar changes across other route handlers.

apps/dashboard/app/(app)/apis/[apiId]/keys/[keyAuthId]/[keyId]/settings/update-key-ratelimit.tsx (2)

40-43: Error message updated to reflect new validation constraint.

The error message has been updated to indicate that the limit value must be greater than or equal to zero, which aligns with the changed validation logic allowing zero as a valid input.


127-127: UI input correctly configured for new validation.

The min attribute on the Input component is already set to 0, which is consistent with the updated validation constraint allowing zero as a valid value.

apps/dashboard/app/(app)/apis/[apiId]/keys/[keyAuthId]/new/validation.ts (2)

108-110: Error message updated to reflect new validation constraint.

The error message has been updated to indicate that the limit value must be greater than or equal to zero, which aligns with the changed validation logic allowing zero as a valid input.


113-113: Validation updated to allow zero rate limit.

The validation for the limit field has been changed to accept non-negative values (including zero) instead of strictly positive values. The error message has been appropriately updated to reflect this change.

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.

Caution

Inline review comments failed to post. This is likely due to GitHub's limits when posting large numbers of comments. If you are seeing this consistently it is likely a permissions issue. Please check "Moderation" -> "Code review limits" under your organization settings.

Actionable comments posted: 1

🛑 Comments failed to post (1)
apps/dashboard/lib/trpc/routers/key/create.ts (1)

42-42: 💡 Verification agent

🧩 Analysis chain

Critical issue: Code change contradicts PR objective

The PR objective is to "fix: allow 0 for ratelimit limit", but this change does the opposite. Changing from z.number().nonnegative() (which allows 0) to z.number().int().positive() (which requires values > 0) actually prevents using 0 as a valid limit value.

If the intent is to allow 0 as stated in the PR objectives, this should be:

-      limit: z.number().int().positive(),
+      limit: z.number().int().nonnegative(),

🏁 Script executed:

#!/bin/bash
# Check if PR title or description confirms the intended behavior for ratelimit limit

echo "Checking PR description to confirm intent..."
gh pr view 2948 --json title,body | jq -r '.title, .body'

# Search for related issue Eng-1661 mentioned in PR
echo "Searching for related issue..."
gh issue view Eng-1661 --json title,body 2>/dev/null || echo "Issue not accessible or found"

Length of output: 2774


Action Required: Correct the ratelimit validation to allow 0

The PR is intended to allow a ratelimit limit of 0 or greater, but the current validation using z.number().int().positive() only permits values greater than 0. To align with the PR objective, please update the validation to use nonnegative().

  • File: apps/dashboard/lib/trpc/routers/key/create.ts (Line 42)

  • Issue: The current Zod schema disallows 0, contradicting the intended behavior as confirmed in the PR description.

  • Proposed diff:

    -      limit: z.number().int().positive(),
    +      limit: z.number().int().nonnegative(),
📝 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.

          limit: z.number().int().nonnegative(),

@MichaelUnkey MichaelUnkey enabled auto-merge March 11, 2025 19:42
@chronark chronark disabled auto-merge March 12, 2025 07:52
@chronark chronark merged commit 7af9208 into main Mar 12, 2025
29 checks passed
@chronark chronark deleted the eng-1661-allow-ratelimit-overrides-to-have-a-limit-of-0-effectively branch March 12, 2025 07:52
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