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(rest-api): validate synapseTxId #3317

Merged
merged 1 commit into from
Oct 22, 2024
Merged

Conversation

abtestingalpha
Copy link
Collaborator

@abtestingalpha abtestingalpha commented Oct 21, 2024

Validates synapseTxId for sanitation before hitting controller.

Summary by CodeRabbit

  • New Features

    • Enhanced transaction ID handling for improved robustness.
    • Introduced a new validation function to ensure synapseTxId is a valid hexadecimal string.
  • Bug Fixes

    • Improved error messaging for invalid synapseTxId inputs.
  • Tests

    • Added a test case to validate the error handling for invalid synapseTxId.

Copy link
Contributor

coderabbitai bot commented Oct 21, 2024

Walkthrough

The changes involve modifications to the bridgeTxStatusController and related files to enhance the handling and validation of the synapseTxId parameter. A new validation function, validateKappa, has been introduced to ensure that synapseTxId is a valid hexadecimal string. The route and controller logic have been updated to incorporate this validation, and a new test case has been added to verify the handling of invalid inputs.

Changes

File Path Change Summary
packages/rest-api/src/controllers/bridgeTxStatusController.ts Modified to handle synapseTxId by ensuring it starts with 0x and creating a txIdWithout0x variable for further processing.
packages/rest-api/src/routes/bridgeTxStatusRoute.ts Updated validation for synapseTxId to check if it is a string and apply validateKappa for hexadecimal validation. Error messages were also modified to reflect these checks.
packages/rest-api/src/tests/bridgeTxStatusRoute.test.ts Added a new test case to check for invalid synapseTxId inputs, ensuring that the API returns a 400 status with the appropriate error message for invalid hexadecimal strings.
packages/rest-api/src/validations/validateKappa.ts Introduced a new function validateKappa that checks if synapseTxId is a valid hexadecimal string, accommodating both prefixed and non-prefixed formats.

Possibly related PRs

Suggested labels

size/s, Sol, Typescript, M-deps

Suggested reviewers

  • trajan0x
  • Defi-Moses
  • bigboydiamonds

🐰 In the land of code where rabbits play,
A new function hops in to save the day.
With synapseTxId, we check it right,
Valid hex strings now shine so bright!
Validation's here, making sure it's true,
In our API garden, we flourish anew! 🌼


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.

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.

@abtestingalpha abtestingalpha changed the title Validate synapseTxId fix(rest-api): validate synapseTxId Oct 21, 2024
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: 1

🧹 Outside diff range and nitpick comments (5)
packages/rest-api/src/validations/validateKappa.ts (1)

1-1: Add input validation for the synapseTxId parameter.

The function assumes that synapseTxId is always a string. To make the function more robust, consider adding a type check at the beginning of the function.

Here's a suggested improvement:

export const validateKappa = (synapseTxId: string) => {
  if (typeof synapseTxId !== 'string') {
    return false
  }
  // ... rest of the function
}

This addition ensures that the function handles non-string inputs gracefully, returning false instead of potentially throwing an error.

packages/rest-api/src/controllers/bridgeTxStatusController.ts (2)

18-21: Ensure consistent format, but consider additional validation.

The introduction of txIdWith0x ensures that the synapseTxId always starts with '0x', which is a good practice for consistency. However, consider adding validation to ensure that synapseTxId is a valid hexadecimal string before processing it.

You could add a validation function like this:

function isValidHex(value: string): boolean {
  return /^(0x)?[0-9A-Fa-f]+$/.test(value);
}

// Then use it before processing synapseTxId
if (!isValidHex(synapseTxId)) {
  return res.status(400).json({ error: 'Invalid synapseTxId format' });
}

Line range hint 1-93: Consider implementing comprehensive input validation.

The changes to handle synapseTxId improve consistency by ensuring the '0x' prefix. However, to further enhance data integrity and security, consider implementing a more comprehensive validation approach for all input parameters at the beginning of the function.

You could create a separate validation function:

function validateInputs(query: any): { valid: boolean; errors: string[] } {
  const errors = [];
  if (!isValidChainId(query.destChainId)) errors.push('Invalid destChainId');
  if (!isValidBridgeModule(query.bridgeModule)) errors.push('Invalid bridgeModule');
  if (!isValidHex(query.synapseTxId)) errors.push('Invalid synapseTxId');
  return { valid: errors.length === 0, errors };
}

// Use it at the beginning of the controller
const { valid, errors } = validateInputs(req.query);
if (!valid) {
  return res.status(400).json({ errors });
}

This approach would centralize input validation, making it easier to maintain and extend in the future.

packages/rest-api/src/tests/bridgeTxStatusRoute.test.ts (1)

67-79: LGTM! Consider adding more test cases for edge cases.

The new test case effectively checks for invalid synapseTxId input, which aligns with the PR objective of implementing validation for synapseTxId. The use of a SQL injection attempt as an invalid input is a good security-conscious choice.

Consider adding more test cases to cover other edge cases, such as:

  1. An empty string
  2. A very long string
  3. A string with special characters but no hex digits

This will ensure a more comprehensive validation of the synapseTxId parameter.

packages/rest-api/src/routes/bridgeTxStatusRoute.ts (1)

138-141: LGTM: Enhanced validation for synapseTxId.

The updated validation logic for synapseTxId is well-implemented:

  1. It checks if the input is a string.
  2. It uses the custom validateKappa function to ensure it's a valid hex string.
  3. Clear error messages are provided for each validation step.

These changes align well with the PR objectives to implement validation for synapseTxId.

Consider combining the string check and the custom validation into a single error message for a more concise user experience:

check('synapseTxId')
  .exists()
  .withMessage('synapseTxId is required')
  .isString()
  .custom((value) => validateKappa(value))
  .withMessage('synapseTxId must be a valid hex string')

This change would reduce the number of potential error messages while still providing clear feedback.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 7cf772e and fa5ba7b.

📒 Files selected for processing (4)
  • packages/rest-api/src/controllers/bridgeTxStatusController.ts (1 hunks)
  • packages/rest-api/src/routes/bridgeTxStatusRoute.ts (2 hunks)
  • packages/rest-api/src/tests/bridgeTxStatusRoute.test.ts (1 hunks)
  • packages/rest-api/src/validations/validateKappa.ts (1 hunks)
🧰 Additional context used
🔇 Additional comments (4)
packages/rest-api/src/validations/validateKappa.ts (1)

1-11: LGTM! The implementation is correct and secure.

The validateKappa function correctly validates 64-character hexadecimal strings, handling both cases with and without the '0x' prefix. The implementation is secure as it strictly limits input length and format.

packages/rest-api/src/controllers/bridgeTxStatusController.ts (1)

25-25: Correct usage of txIdWith0x.

The use of txIdWith0x in the Synapse.getBridgeTxStatus call is consistent with the earlier change and ensures that the transaction ID always has the '0x' prefix when passed to this function.

packages/rest-api/src/routes/bridgeTxStatusRoute.ts (2)

8-8: LGTM: New import statement for validateKappa.

The import statement for the custom validation function validateKappa is correctly added.


Line range hint 1-146: Summary: Successful implementation of synapseTxId validation.

The changes in this file successfully implement the validation for synapseTxId as outlined in the PR objectives:

  1. A new custom validation function validateKappa is imported.
  2. The validation logic for synapseTxId is enhanced to ensure it's a string and a valid hex value.

These changes improve the integrity and security of the data being handled by the /bridgeTxStatus endpoint. The implementation is correct, and no security issues or major concerns were identified.

Copy link

Deploying sanguine-fe with  Cloudflare Pages  Cloudflare Pages

Latest commit: fa5ba7b
Status: ✅  Deploy successful!
Preview URL: https://38bf1f9f.sanguine-fe.pages.dev
Branch Preview URL: https://rest-api-validate-kappa.sanguine-fe.pages.dev

View logs

Copy link

codecov bot commented Oct 21, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 26.98386%. Comparing base (6415acd) to head (fa5ba7b).
Report is 25 commits behind head on master.

Additional details and impacted files
@@                 Coverage Diff                 @@
##              master       #3317         +/-   ##
===================================================
- Coverage   31.92469%   26.98386%   -4.94083%     
===================================================
  Files            238         178         -60     
  Lines          14553       11833       -2720     
  Branches         356          82        -274     
===================================================
- Hits            4646        3193       -1453     
+ Misses          9614        8357       -1257     
+ Partials         293         283         -10     
Flag Coverage Δ
packages 90.44834% <ø> (ø)
promexporter ?
solidity ?

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

@abtestingalpha abtestingalpha merged commit e4c67ec into master Oct 22, 2024
36 checks passed
@abtestingalpha abtestingalpha deleted the rest-api/validate-kappa branch October 22, 2024 23:37
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants