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: add permissions for ratelimit overrides #2126

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

Conversation

MichaelUnkey
Copy link
Collaborator

@MichaelUnkey MichaelUnkey commented Sep 23, 2024

What does this PR do?

Fixes # (issue)
eng-1336

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?

Check if I understood the assignment properly.

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

Release Notes

  • New Features

    • Introduced new API routes for managing rate limit overrides:
      • Set Override: POST /v1/ratelimit.setOverride
      • Delete Override: POST /v1/ratelimit.deleteOverride
      • List Overrides: GET /v1/ratelimit.listOverrides
    • Added new permissions for managing rate limits: set_override, read_override, delete_override.
  • Enhancements

    • Updated analytics logging to include new rate limit event types.
    • Improved the structure of analytics key verification methods.
  • Bug Fixes

    • Deprecated old key verification method in favor of an improved version.

Copy link

linear bot commented Sep 23, 2024

Copy link

changeset-bot bot commented Sep 23, 2024

⚠️ No Changeset found

Latest commit: 5974580

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 Sep 23, 2024

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

Name Status Preview Comments Updated (UTC)
dashboard ❌ Failed (Inspect) Nov 4, 2024 3:27pm
engineering ✅ Ready (Inspect) Visit Preview 💬 Add feedback Nov 4, 2024 3:27pm
planetfall ✅ Ready (Inspect) Visit Preview 💬 Add feedback Nov 4, 2024 3:27pm
play ✅ Ready (Inspect) Visit Preview 💬 Add feedback Nov 4, 2024 3:27pm
unkey-engineering ❌ Failed (Inspect) Nov 4, 2024 3:27pm
workflows ✅ Ready (Inspect) Visit Preview 💬 Add feedback Nov 4, 2024 3:27pm
www ✅ Ready (Inspect) Visit Preview 💬 Add feedback Nov 4, 2024 3:27pm

Copy link
Contributor

coderabbitai bot commented Sep 23, 2024

📝 Walkthrough
📝 Walkthrough

Walkthrough

This pull request introduces several new API routes for managing rate limit overrides, including the ability to set, delete, and list these overrides. The routes require bearer authentication and handle various request and response formats, including JSON payloads. Additionally, it updates the analytics logging for rate limit actions and introduces new permissions related to these functionalities. The changes also include modifications to the existing Analytics class and the addition of new event types for audit logging.

Changes

File Path Change Summary
apps/api/src/routes/v1_ratelimit_deleteOverride.ts Added a POST endpoint for deleting rate limit overrides with input validation and response handling.
apps/api/src/routes/v1_ratelimit_listOverrides.ts Added a GET endpoint for listing rate limit overrides, including query parameter validation and response formatting.
apps/api/src/routes/v1_ratelimit_setOverride.ts Introduced a POST endpoint for setting rate limit overrides, with schema validation and database transaction handling.
apps/api/src/worker.ts Registered new rate limit-related functions for handling the newly created routes.
apps/api/src/pkg/analytics.ts Updated Analytics class with new logging capabilities and deprecated an old method for key verification.
apps/dashboard/app/(app)/settings/root-keys/[keyId]/permissions/permissions.ts Added three new permissions under the Ratelimit category for managing overrides.
internal/schema/src/auditlog.ts Enhanced the unkeyAuditLogEvents enum with new event types for rate limit actions.
packages/api/src/client.ts Introduced a commented-out method setOverride in the Unkey class for handling rate limit overrides.

Possibly related PRs

Suggested labels

Feature, 🕹️ oss.gg, :joystick: 750 points, hacktoberfest

Suggested reviewers

  • mcstepp
  • chronark
  • perkinsjr

📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 652b5d3 and 5974580.

📒 Files selected for processing (5)
  • apps/api/src/routes/v1_ratelimit_deleteOverride.ts (1 hunks)
  • apps/api/src/routes/v1_ratelimit_listOverrides.ts (1 hunks)
  • apps/api/src/routes/v1_ratelimit_setOverride.ts (1 hunks)
  • internal/schema/src/auditlog.ts (1 hunks)
  • packages/api/src/client.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (4)
  • apps/api/src/routes/v1_ratelimit_deleteOverride.ts
  • apps/api/src/routes/v1_ratelimit_listOverrides.ts
  • internal/schema/src/auditlog.ts
  • packages/api/src/client.ts
🧰 Additional context used
🪛 Biome
apps/api/src/routes/v1_ratelimit_setOverride.ts

[error] 116-116: This variable is unused.

Unused variables usually are result of incomplete refactoring, typos and other source of bugs.
Unsafe fix: If this is intentional, prepend auditType with an underscore.

(lint/correctness/noUnusedVariables)

🔇 Additional comments (7)
apps/api/src/routes/v1_ratelimit_setOverride.ts (7)

28-32: Add documentation link for wildcard rules

As mentioned in the past review, the identifier description should include a link explaining how wildcards work. While the current description mentions wildcards, it would be more helpful to include specific documentation.


72-78: LGTM: Type exports are well-defined

The type exports are properly structured and provide good type safety for the API contract.


122-162: Consider refactoring duplicated audit logging code

The audit logging code is duplicated between insertUnkeyAuditLog and analytics.ingestUnkeyAuditLogsTinybird. While this duplication is acceptable for now as mentioned in the past review (due to planned migration to ClickHouse), it would be good to track this technical debt.


85-91: ⚠️ Potential issue

Fix incorrect permissions in query

As noted in the past review, the query includes unnecessary permissions. Remove read_override and other unneeded permissions.

buildUnkeyQuery(({ or }) =>
  or(
    "*",
-   "ratelimit.*.set_override",
-   "ratelimit.*.read_override",
+   "ratelimit.*.set_override"
  ),
),

95-96: ⚠️ Potential issue

Add namespace ownership verification

Critical security issue: The code needs to verify that the requested namespace belongs to the authenticated workspace before allowing operations. Currently, users could potentially insert overrides into other workspaces' namespaces by guessing the ID.

Add verification before the transaction:

const { db, analytics } = c.get("services");
+ const namespace = await db.primary
+   .select()
+   .from(schema.namespaces)
+   .where(sql`id = ${req.namespaceId} AND workspace_id = ${auth.authorizedWorkspaceId}`)
+   .limit(1)
+   .execute();
+
+ if (!namespace.length) {
+   throw new Error("Namespace not found or not authorized");
+ }

await db.primary.transaction(async (tx) => {

116-120: ⚠️ Potential issue

Fix unreliable operation type detection

The current method of checking res.statement.startsWith("insert") is not reliable for determining the operation type. Additionally, the auditType variable is unused.

As suggested in the past review, fetch the override first to determine if it's a create or update operation:

await db.primary.transaction(async (tx) => {
+ const existing = await tx
+   .select()
+   .from(schema.ratelimitOverrides)
+   .where(sql`namespace_id = ${req.namespaceId} AND identifier = ${req.identifier}`)
+   .limit(1)
+   .execute();

+ const isUpdate = existing.length > 0;
+ const overrideId = isUpdate ? existing[0].id : newId("ratelimitOverride");

  const res = await tx
    .insert(schema.ratelimitOverrides)
    .values({
-     id: newId("ratelimitOverride"),
+     id: overrideId,
      // ... other fields
    })
    .onDuplicateKeyUpdate({
      set: {
        // ... update fields
      },
    });

- let auditType: "ratelimitOverride.create" | "ratelimitOverride.update" =
-   "ratelimitOverride.create";
- if (!res.statement.startsWith("insert")) {
-   auditType = "ratelimitOverride.update";
- }
🧰 Tools
🪛 Biome

[error] 116-116: This variable is unused.

Unused variables usually are result of incomplete refactoring, typos and other source of bugs.
Unsafe fix: If this is intentional, prepend auditType with an underscore.

(lint/correctness/noUnusedVariables)


109-115: ⚠️ Potential issue

Add updatedAt timestamp

As noted in the past review, the updatedAt timestamp should be set when updating the record.

.onDuplicateKeyUpdate({
  set: {
    limit: req.limit,
    duration: req.duration,
    async: req.async,
+   updatedAt: new Date(),
  },
}),

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 Sep 23, 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: 2

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 5828b35 and 56b8c75.

📒 Files selected for processing (1)
  • apps/api/src/routes/v1_ratelimit_listOverrides.ts (1 hunks)
🧰 Additional context used
🔇 Additional comments (4)
apps/api/src/routes/v1_ratelimit_listOverrides.ts (4)

59-62: LGTM: Type exports are well-defined

The type exports for the route and response are correctly defined, providing good type safety for consumers of this module.


63-71: LGTM: Route handler setup and authentication

The route handler is correctly set up using app.openapi, and the authentication check is properly implemented using rootKeyAuth with the correct permissions.


43-47: ⚠️ Potential issue

Consider implementing proper pagination logic

The response schema includes a cursor field for pagination, but the current implementation doesn't handle pagination in the query or modify the dataset based on pagination parameters. This may lead to confusion for API consumers.

Consider implementing pagination by:

  1. Accepting limit and cursor parameters in the request query.
  2. Modifying the database queries to use these parameters.
  3. Updating the response to include the next cursor only if there are more results.

If pagination is not required, update the response schema to remove the cursor field to avoid misleading API consumers.


116-116: 🛠️ Refactor suggestion

Simplify the handling of the async field

The current code uses r.async ?? undefined, which is redundant. Since r.async will already be undefined if not present, you can simplify this line.

Apply this change:

- async: r.async ?? undefined,
+ async: r.async,

Comment on lines +72 to +96
if (!identifier) {
const overrides = await db.readonly.query.ratelimitOverrides.findMany({
where: (table, { eq, and }) =>
and(
eq(table.workspaceId, auth.authorizedWorkspaceId),
eq(table.namespaceId, namespaceId),
),
with: {
namespace: true,
},
});

return c.json({
overrides: overrides.map((r) => ({
id: r.id,
namespace: r.namespace.name,
identifier: r.identifier,
limit: r.limit,
duration: r.duration,
async: r.async,
})),
total: overrides.length,
cursor: overrides.at(-1)?.id ?? undefined,
});
}
Copy link
Contributor

@coderabbitai coderabbitai bot Oct 16, 2024

Choose a reason for hiding this comment

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

⚠️ Potential issue

Implement proper pagination logic

While the code sets a cursor to the ID of the last override, there's no actual pagination logic implemented. This means that subsequent requests won't use this cursor to fetch the next set of results.

Consider implementing proper pagination:

  1. Accept a cursor parameter in the request.
  2. Use this cursor to filter results in the database query.
  3. Limit the number of results returned (e.g., using a LIMIT clause).
  4. Only include the cursor in the response if there are more results to fetch.

This will ensure that clients can efficiently paginate through large sets of overrides.

Copy link
Collaborator

Choose a reason for hiding this comment

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

yup

Copy link
Contributor

Choose a reason for hiding this comment

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

@chronark, understood.

(_/)
( •_•)
/>💧

Comment on lines +97 to +121
const overrides = await db.readonly.query.ratelimitOverrides.findMany({
where: (table, { eq, and }) =>
and(
eq(table.workspaceId, auth.authorizedWorkspaceId),
eq(table.namespaceId, namespaceId),
eq(table.identifier, identifier),
),
with: {
namespace: true,
},
});

return c.json({
overrides: overrides.map((r) => ({
id: r.id,
namespace: r.namespace.name,
identifier: r.identifier,
limit: r.limit,
duration: r.duration,
async: r.async ?? undefined,
})),
total: overrides.length,
cursor: overrides.at(-1)?.id ?? undefined,
});
});
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

Implement consistent pagination logic

Similar to the case without an identifier, this section lacks proper pagination logic. To ensure consistency and efficiency, implement pagination here as well:

  1. Accept and use a cursor parameter in the request.
  2. Modify the database query to use this cursor for filtering.
  3. Limit the number of results returned.
  4. Include the cursor in the response only if there are more results to fetch.

This will provide a consistent pagination experience across both cases (with and without identifier).

apps/api/src/routes/v1_ratelimit_deleteOverride.ts Outdated Show resolved Hide resolved
example: "eyJrZXkiOiJrZXlfMTIzNCJ9",
}),
total: z.number().int().openapi({
description: "The total number of keys for this api",
Copy link
Collaborator

Choose a reason for hiding this comment

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

wrong description

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

My bad missed that, Changed to "The total number of overrides for the namespace and optional identifier"

buildUnkeyQuery(({ or }) => or("*", "ratelimit.*.read_override")),
);
if (!identifier) {
const overrides = await db.readonly.query.ratelimitOverrides.findMany({
Copy link
Collaborator

Choose a reason for hiding this comment

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

this doesn't use the cursor for pagination

Copy link
Collaborator

Choose a reason for hiding this comment

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

we also want a page size limit

check out how we did it for listing api keys, or ping me and we can talk it through

duration: r.duration,
async: r.async,
})),
total: overrides.length,
Copy link
Collaborator

Choose a reason for hiding this comment

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

this needs to load all overrides in the namespace, not just the ones you return

let's say a user has 200 overrides.
We return the first 100 in the overrides field, but also let them know that in total there are 200

Comment on lines +114 to +118
duration: req.duration,
async: req.async,
},
});
let auditType: "ratelimitOverride.create" | "ratelimitOverride.update" =
Copy link
Collaborator

Choose a reason for hiding this comment

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

we should fetch the override, mutate it and then write it back to the db inside the transaction.
that also solves this issue becaues we clearly know whether it's a create or update

apps/api/src/routes/v1_ratelimit_setOverride.ts Outdated Show resolved Hide resolved
internal/schema/src/auditlog.ts Show resolved Hide resolved
internal/schema/src/auditlog.ts Show resolved Hide resolved
Co-authored-by: Andreas Thomas <dev@chronark.com>
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