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: set the minimum byte length for the web app to 16 #2584

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

bitbrief
Copy link

@bitbrief bitbrief commented Oct 27, 2024

What does this PR do?

Set the minimum byte length to 16 for api creation on web app

Fixes #2564

Type of change

  • Bug fix (non-breaking change which fixes an issue)
  • [x ] Chore (refactoring code, technical debt, workflow improvements)
  • [x ] 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?

Open the api dashboard on the web app and try to change the default minimum byte length which is now 16 (8 earlier)
Try to create an api with less than 16 minimum byte length

  • Tried to create api with less than 16 minimum byte length
  • Check for default byte length in the api settings.

Checklist

Required

  • [x ] Filled out the "How to test" section in this PR
  • [x ] Read Contributing Guide
  • [x ] Self-reviewed my own code
  • Commented on my code in hard-to-understand areas
  • [x ] Ran pnpm build
  • Ran pnpm fmt
  • [x ] Checked for warnings, there are none
  • [x ] Removed all console.logs
  • My changes don't cause any responsiveness issues

Summary by CodeRabbit

  • New Features

    • Updated validation for the CreateKey component to require a minimum byte value of 16.
    • Changed the minimum value for defaultBytes in the DefaultBytes component from 8 to 16.
  • Bug Fixes

    • Enhanced validation logic for byte size inputs to ensure compliance with new minimum requirements.
  • Documentation

    • Improved clarity in API type definitions for better usability and maintainability.

Copy link

changeset-bot bot commented Oct 27, 2024

⚠️ No Changeset found

Latest commit: 11becc8

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
Contributor

coderabbitai bot commented Oct 27, 2024

📝 Walkthrough

Walkthrough

The pull request introduces changes to the validation logic for byte length fields in the CreateKey component and the DefaultBytes component. Specifically, the bytes field in CreateKey is now required to have a minimum value of 16, and the defaultBytes field in DefaultBytes has been updated to reflect the same minimum requirement. Additionally, there are updates to TypeScript definitions in the openapi.d.ts file, including refinements to type signatures and interface structures.

Changes

File Path Change Summary
apps/dashboard/app/(app)/apis/[apiId]/keys/[keyAuthId]/new/client.tsx Updated formSchema for CreateKey component: bytes field now has a minimum value constraint of 16.
apps/dashboard/app/(app)/apis/[apiId]/settings/default-bytes.tsx Modified validation schema for defaultBytes: minimum value changed from 8 to 16.
packages/api/src/openapi.d.ts Multiple updates to TypeScript definitions, including refinements to XOR, OneOf, and various operation signatures.

Assessment against linked issues

Objective Addressed Explanation
Ensure the web app accepts a minimum 16-byte key in the Create a new key form.
Ensure the web app accepts a minimum 16-byte key in the API settings Default Bytes section.
Align the keys.createKey API behavior with the web app's byte length requirements. The API behavior is not modified in this PR.

Possibly related PRs

Suggested labels

Bug, Feature, Dashboard, 🕹️ oss.gg, :joystick: 300 points

Suggested reviewers

  • mcstepp
  • perkinsjr
  • chronark
  • MichaelUnkey

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

vercel bot commented Oct 27, 2024

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

A member of the Team first needs to authorize it.

Copy link

vercel bot commented Oct 27, 2024

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 Oct 27, 2024 2:19pm

Copy link
Contributor

github-actions bot commented Oct 27, 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

🧹 Outside diff range and nitpick comments (9)
apps/dashboard/app/(app)/apis/[apiId]/settings/default-bytes.tsx (2)

Line range hint 89-99: Add HTML5 validation attributes to improve user experience.

The Input component could benefit from HTML5 validation attributes to provide immediate feedback to users.

Apply this diff to enhance the input constraints:

 <Input
   className="max-w-sm"
   {...field}
   autoComplete="off"
+  type="number"
+  min="16"
+  max="255"
   onChange={(e) => field.onChange(Number(e.target.value))}
 />

Line range hint 57-62: Consider moving validation logic to schema level.

The validation for unchanged values could be handled at the schema level for better separation of concerns and clearer error messages.

Consider updating the schema validation:

 const formSchema = z.object({
   keyAuthId: z.string(),
   workspaceId: z.string(),
   defaultBytes: z
     .number()
     .min(16, "Byte size needs to be at least 16")
     .max(255, "Byte size cannot exceed 255")
+    .refine((val) => val !== keyAuth.defaultBytes, {
+      message: "Please provide a different byte size than the current default"
+    })
     .optional(),
 });

Then simplify the onSubmit function:

 async function onSubmit(values: z.infer<typeof formSchema>) {
-  if (values.defaultBytes === keyAuth.defaultBytes || !values.defaultBytes) {
-    return toast.error(
-      "Please provide a different byte-size than already existing one as default",
-    );
-  }
   await setDefaultBytes.mutateAsync(values);
 }
apps/dashboard/app/(app)/apis/[apiId]/keys/[keyAuthId]/new/client.tsx (1)

Line range hint 350-356: Enhance the form field description to mention the minimum requirement.

The description explains that longer keys are more secure, but it would be helpful to explicitly mention the minimum requirement of 16 bytes to users.

Consider updating the description:

-                          <FormDescription>
-                            How long the key will be. Longer keys are harder to guess and more
-                            secure.
-                          </FormDescription>
+                          <FormDescription>
+                            How long the key will be (minimum 16 bytes). Longer keys are harder to guess and more
+                            secure.
+                          </FormDescription>
packages/api/src/openapi.d.ts (6)

Line range hint 1303-1303: Typographical Error: Correct 'Asnyc' to 'Async'

In the description for the async property, 'Asnyc ratelimiting' should be corrected to 'Async ratelimiting'.

Apply this diff to fix the typo:

- * @description Asnyc ratelimiting doesn't add latency, while sync ratelimiting is slightly more accurate.
+ * @description Async ratelimiting doesn't add latency, while sync ratelimiting is slightly more accurate.

1379-1381: Clarify the comment: Replace 'permissions' with 'roles'

The description mentions 'permissions' instead of 'roles'. Since this block is about roles, it should refer to 'roles' for clarity.

Apply this diff to correct the description:

- * @description Set to true to automatically create the permissions they do not exist yet. Only works when specifying `name`.
- *                     Autocreating roles requires your root key to have the `rbac.*.create_permission` permission, otherwise the request will get rejected
+ * @description Set to true to automatically create the roles if they do not exist yet. Only works when specifying `name`.
+ *                     Autocreating roles requires your root key to have the `rbac.*.create_role` permission, otherwise the request will get rejected

1560-1580: Specify data types explicitly in 'verifications' schema

For better type safety and clarity, explicitly define the data types for numerical fields such as time, success, rateLimited, and usageExceeded.

Ensure TypeScript type annotations are added:

 time: number;
 success: number;
 rateLimited: number;
 usageExceeded: number;

2804-3020: Improve documentation for migration endpoints

The additions in v1.migrations.createKeys and v1.migrations.enqueueKeys could benefit from clearer descriptions and consistent formatting to enhance understanding.

Review the documentation comments to ensure all fields are properly described, and deprecated fields are clearly indicated.


3291-3306: Typographical Error: Correct 'Sucessfully' to 'Successfully'

There is a typo in the response description: 'Sucessfully created a permission' should be 'Successfully created a permission'.

Apply this diff to fix the typo:

- /** @description Sucessfully created a permission */
+ /** @description Successfully created a permission */

3641-3642: Update documentation formatting for 'externalId'

In the description for externalId, ensure that formatting is consistent and extraneous characters are removed.

Apply this diff:

- * `externalId`s are unique across your workspace and therefore a `PRECONDITION_FAILED` error is returned when you try to create duplicates.
+ * `externalId`s are unique across your workspace, so a `PRECONDITION_FAILED` error is returned when you try to create duplicates.
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between ca805ac and 11becc8.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (3)
  • apps/dashboard/app/(app)/apis/[apiId]/keys/[keyAuthId]/new/client.tsx (1 hunks)
  • apps/dashboard/app/(app)/apis/[apiId]/settings/default-bytes.tsx (1 hunks)
  • packages/api/src/openapi.d.ts (35 hunks)
🔇 Additional comments (7)
apps/dashboard/app/(app)/apis/[apiId]/settings/default-bytes.tsx (2)

25-25: LGTM: Minimum byte length requirement updated correctly.

The validation change aligns with the PR objective to enforce a minimum of 16 bytes for API keys.


Line range hint 16-28: Verify integration with key creation endpoint.

Let's ensure that the default byte length is properly applied when creating new keys.

✅ Verification successful

Integration with key creation is properly implemented.

The verification shows that:

  1. The default bytes setting is correctly stored in the keyAuth configuration
  2. The default bytes value is properly passed to the key creation form (defaultBytes prop)
  3. The key creation form uses the default bytes value as its initial value (defaultValues.bytes: defaultBytes || 16)
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for key creation implementations that should use this default value
ast-grep --pattern 'createKey($$$)' 

# Search for any direct references to byte length in key creation
rg -l 'byteLength|defaultBytes' --type ts --type tsx

Length of output: 1014


Script:

#!/bin/bash
# Search for key creation related code with proper file extensions
rg -l "byteLength|defaultBytes" --type-add 'tsx:*.tsx' --type-add 'ts:*.ts' .

# Look for API endpoints or mutations handling key creation
rg -A 5 "createKey|mutation.*Key" --type-add 'tsx:*.tsx' --type-add 'ts:*.ts' .

# Find form submissions or handlers in the settings component
fd "settings.*\.(tsx|ts)$" . --exec rg -l "onSubmit|handleSubmit|mutation"

Length of output: 115070


Script:

#!/bin/bash
# Look for the implementation of the form submission in the default-bytes settings component
rg -A 10 "onSubmit|handleSubmit" ./apps/dashboard/app/\(app\)/apis/\[apiId\]/settings/default-bytes.tsx

# Look for the API endpoint that handles the default bytes update
rg -A 10 "setDefaultBytes" ./apps/dashboard/lib/trpc/routers/api/

Length of output: 1044


Script:

#!/bin/bash
# Look for the implementation of key creation that uses defaultBytes
rg -A 10 "defaultBytes.*createKey|createKey.*defaultBytes" .

# Check for the setDefaultBytes implementation in the API router
rg -A 10 "export.*setDefaultBytes" ./apps/dashboard/lib/trpc/routers/api/setDefaultBytes.ts

# Look for where defaultBytes is used in key creation
ast-grep --pattern 'bytes: $defaultBytes' .

Length of output: 202


Script:

#!/bin/bash
# Look for the key creation implementation in the dashboard
rg -A 10 "createKey.*keyAuthId" ./apps/dashboard/lib/trpc/routers/key/create.ts

# Check for defaultBytes usage in key creation
rg -A 10 "defaultBytes" ./apps/dashboard/app/\(app\)/apis/\[apiId\]/keys/\[keyAuthId\]/new/

# Look for the setDefaultBytes mutation usage
rg -A 5 "setDefaultBytes" ./apps/dashboard/app/\(app\)/apis/\[apiId\]/settings/

Length of output: 4424

apps/dashboard/app/(app)/apis/[apiId]/keys/[keyAuthId]/new/client.tsx (1)

56-57: LGTM: Minimum byte length requirement implemented correctly.

The change correctly implements the minimum byte length requirement of 16 bytes, aligning with the API requirements as specified in issue #2564.

packages/api/src/openapi.d.ts (4)

9-10: LGTM!

The updated type definitions for XOR and OneOf improve readability and maintain correct logic.


552-556: Verify the recursive 'PermissionQuery' type definition

Ensure that the recursive type definition for PermissionQuery using OneOf correctly models the intended permission query logic and does not introduce any TypeScript type errors.

To check for potential type errors, consider running a TypeScript type check on this definition in the context of its usage.


601-615: Review optional properties in 'ratelimits' schema

The properties limit and duration are marked as optional, but the example suggests they are important for proper functioning. Verify whether these fields should be optional or required to avoid unintended behaviors.

If these fields are required, update their definitions to reflect that by removing the ? to indicate they are mandatory.


2561-2580: Ensure consistency in 'resources' field descriptions

In the 'limit' operation, verify that the descriptions and types of the resources array fields are accurate and consistent with their intended use.

Review the resources schema to confirm that all fields are documented correctly, and consider adding any missing descriptions or examples.

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.

We need to validate these on the server as well (in trpc)

@bitbrief
Copy link
Author

Also I was also trying to fix this on the api, but I was receiving server error running it locally.

@chronark
Copy link
Collaborator

can you elaborate?

@bitbrief
Copy link
Author

Screenshot 2024-10-27 at 10 40 45 AM

This was the error

@BadriVishalPadhy
Copy link
Contributor

@chronark any updates?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Inconsistent minimum Byte Length validation between web app and createKey API endpoint
3 participants