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

ESC 399 - Enhance redirect URL handling and MentionParser functionality #639

Merged
merged 1 commit into from
Dec 10, 2024

Conversation

chiragchhatrala
Copy link
Collaborator

@chiragchhatrala chiragchhatrala commented Dec 5, 2024

  • Updated the redirect_url validation in UserFormRequest to accept strings instead of just max length.
  • Modified MentionParser to include a urlFriendlyOutput method, allowing for URL encoding of special characters in parsed values.
  • Adjusted the PublicFormController to utilize the new urlFriendlyOutput method for redirect URLs.
  • Created a migration to change the redirect_url field type in the database from string to text, accommodating longer URLs.
  • Added tests to ensure proper handling of long redirect URLs and the functionality of the new URL-friendly output feature in MentionParser.

This update improves the flexibility and robustness of form handling and URL processing.

Summary by CodeRabbit

Release Notes

  • New Features

    • Enhanced form submission handling with improved redirect URL processing.
    • Introduced URL-friendly output formatting option in the MentionParser.
  • Bug Fixes

    • Updated validation for redirect URLs to accept longer strings without a character limit.
  • Tests

    • Added tests to validate handling of long and null redirect URLs.
    • Created tests for the new URL-friendly output functionality in MentionParser.

- Updated the `redirect_url` validation in `UserFormRequest` to accept strings instead of just max length.
- Modified `MentionParser` to include a `urlFriendlyOutput` method, allowing for URL encoding of special characters in parsed values.
- Adjusted the `PublicFormController` to utilize the new `urlFriendlyOutput` method for redirect URLs.
- Created a migration to change the `redirect_url` field type in the database from string to text, accommodating longer URLs.
- Added tests to ensure proper handling of long redirect URLs and the functionality of the new URL-friendly output feature in `MentionParser`.

This update improves the flexibility and robustness of form handling and URL processing.
Copy link
Contributor

coderabbitai bot commented Dec 5, 2024

Walkthrough

The pull request introduces several changes across multiple files, primarily focusing on the handling of the redirect_url in forms. The PublicFormController updates the URL processing logic and tracks the submission state. The UserFormRequest validation rule for redirect_url is modified to allow longer strings. The MentionParser class adds functionality for URL-friendly output formatting. A migration alters the redirect_url column type in the database, and new tests validate these changes, ensuring the application can handle various redirect_url scenarios.

Changes

File Path Change Summary
api/app/Http/Controllers/Forms/PublicFormController.php Updated getRedirectData method to modify URL handling; added $isFirstSubmission variable in answer method.
api/app/Http/Requests/UserFormRequest.php Changed redirect_url validation rule from `nullable
api/app/Open/MentionParser.php Introduced $urlFriendly property and urlFriendlyOutput method; updated parse and getData methods for URL-friendly output.
api/database/migrations/2024_12_05_121609_change_redirect_url_to_text_in_forms_table.php Migration to change redirect_url column type from string to text.
api/tests/Feature/Forms/RedirectUrlLengthTest.php Added tests for handling long and null redirect_url values.
api/tests/Unit/Service/Forms/MentionParserTest.php Added tests for urlFriendlyOutput method in MentionParser.

Possibly related PRs

  • Right to left mode #611: The changes in the UserFormRequest class regarding the redirect_url validation rules are related to the main PR, as both involve handling the redirect_url field, which is central to the modifications in the PublicFormController.

Suggested reviewers

  • JhumanJ

Poem

In fields of code where rabbits play,
A redirect_url leads the way.
With hops of logic, we refine,
A friendly format, oh so fine!
From tests to forms, we make it right,
In our burrow, code takes flight! 🐇✨


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

@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 (5)
api/tests/Feature/Forms/RedirectUrlLengthTest.php (1)

3-17: Consider enhancing the long URL test case.

While the test verifies basic functionality, consider these improvements:

  1. Remove withoutExceptionHandling() to ensure proper error handling
  2. Use a more realistic long URL with actual query parameters
  3. Add edge cases for special characters and URL encoding

Here's a suggested improvement:

-    $this->withoutExceptionHandling();
     $user = $this->actingAsUser();
     $workspace = $this->createUserWorkspace($user);
     $form = $this->createForm($user, $workspace);

-    // Create a very long URL (more than 255 characters)
-    $longUrl = 'https://example.com/?' . str_repeat('very-long-parameter=value&', 50);
+    // Real-world long URL with special characters
+    $longUrl = 'https://example.com/callback?' . http_build_query([
+        'token' => str_repeat('t', 100),
+        'data' => json_encode(['key' => str_repeat('value', 30)]),
+        'special' => '[email protected]&other=value',
+        'unicode' => '테스트'
+    ]);
api/app/Open/MentionParser.php (1)

50-50: Consider URL parsing implications of the '+' separator.

Using '+' as an array separator might cause issues as it's a special character in URLs (represents space). Consider using a more URL-safe separator like '%2C' (encoded comma).

-                $textNode = $doc->createTextNode(is_array($value) ? implode($this->urlFriendly ? ',+' : ', ', $value) : $value);
+                $textNode = $doc->createTextNode(is_array($value) ? implode($this->urlFriendly ? '%2C' : ', ', $value) : $value);
api/app/Http/Controllers/Forms/PublicFormController.php (2)

119-119: Consider adding error handling for parsing failures.

While the addition of urlFriendlyOutput() improves URL handling, consider adding error handling for potential parsing failures.

-        $redirectUrl = ($form->redirect_url) ? (new MentionParser($form->redirect_url, $formattedData))->urlFriendlyOutput()->parseAsText() : null;
+        try {
+            $redirectUrl = ($form->redirect_url) 
+                ? (new MentionParser($form->redirect_url, $formattedData))
+                    ->urlFriendlyOutput()
+                    ->parseAsText() 
+                : null;
+        } catch (\Exception $e) {
+            \Log::warning('Failed to parse redirect URL', [
+                'form_id' => $form->id,
+                'error' => $e->getMessage()
+            ]);
+            $redirectUrl = null;
+        }

Line range hint 121-123: Consider validating URL before parsing.

The URL validation happens after parsing, which might make it harder to identify the root cause of invalid URLs. Consider validating the original URL before parsing.

+        if ($form->redirect_url && !filter_var($form->redirect_url, FILTER_VALIDATE_URL)) {
+            \Log::warning('Invalid redirect URL format before parsing', [
+                'form_id' => $form->id,
+                'url' => $form->redirect_url
+            ]);
+        }
+
         if ($redirectUrl && !filter_var($redirectUrl, FILTER_VALIDATE_URL)) {
+            \Log::warning('Invalid redirect URL format after parsing', [
+                'form_id' => $form->id,
+                'url' => $redirectUrl
+            ]);
             $redirectUrl = null;
         }
api/tests/Unit/Service/Forms/MentionParserTest.php (1)

177-217: Consider adding edge case tests.

The test suite is comprehensive but could benefit from additional edge cases:

  1. Empty string values
  2. Null values
  3. Very long values
+        test('it handles empty values', function () {
+            $content = '<p>Empty: <span mention mention-field-id="123">Placeholder</span></p>';
+            $data = [['id' => '123', 'value' => '']];
+
+            $parser = new MentionParser($content, $data);
+            $result = $parser->urlFriendlyOutput()->parse();
+
+            expect($result)->toBe('<p>Empty: </p>');
+        });
+
+        test('it handles null values', function () {
+            $content = '<p>Null: <span mention mention-field-id="123">Placeholder</span></p>';
+            $data = [['id' => '123', 'value' => null]];
+
+            $parser = new MentionParser($content, $data);
+            $result = $parser->urlFriendlyOutput()->parse();
+
+            expect($result)->toBe('<p>Null: </p>');
+        });
+
+        test('it handles very long values', function () {
+            $content = '<p>Long: <span mention mention-field-id="123">Placeholder</span></p>';
+            $data = [['id' => '123', 'value' => str_repeat('a ', 1024)]];
+
+            $parser = new MentionParser($content, $data);
+            $result = $parser->urlFriendlyOutput()->parse();
+
+            expect($result)->toContain(str_repeat('a+', 1024));
+        });
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between daca692 and 02833bf.

📒 Files selected for processing (6)
  • api/app/Http/Controllers/Forms/PublicFormController.php (1 hunks)
  • api/app/Http/Requests/UserFormRequest.php (1 hunks)
  • api/app/Open/MentionParser.php (3 hunks)
  • api/database/migrations/2024_12_05_121609_change_redirect_url_to_text_in_forms_table.php (1 hunks)
  • api/tests/Feature/Forms/RedirectUrlLengthTest.php (1 hunks)
  • api/tests/Unit/Service/Forms/MentionParserTest.php (1 hunks)
🔇 Additional comments (3)
api/database/migrations/2024_12_05_121609_change_redirect_url_to_text_in_forms_table.php (1)

13-15: LGTM! Verify existing data integrity.

The migration correctly changes the redirect_url column type from string to text while maintaining nullability. This change supports the requirement to handle longer URLs.

Let's verify the existing data in the forms table:

✅ Verification successful

Migration is safe and well-justified by test requirements

The change from string to text for redirect_url is well-justified and safe because:

  1. The original migration shows redirect_url was created as a nullable string column
  2. The test file demonstrates a clear requirement to support URLs longer than 255 characters
  3. The change maintains nullability, ensuring backward compatibility
  4. Text type can safely store all existing string data without truncation
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any existing redirect_url values that might be affected
ast-grep --pattern 'Schema::table($_, function ($table) {
  $table->string("redirect_url")$$$
})'

Length of output: 99


Script:

#!/bin/bash
# Let's search for the initial migration that created the redirect_url column
fd -e php -x grep -l "redirect_url" {} \;

# Also search for any string patterns related to redirect_url column creation
ast-grep --pattern 'Schema::create($_, function ($table) {
  $$$
  $table->string("redirect_url")$$$
})'

Length of output: 654


Script:

#!/bin/bash
# Let's check the content of the initial migration file to understand the original column definition
cat ./api/database/migrations/2021_05_19_140326_create_forms_table.php

# Also check the test file that might provide insights about the change requirement
cat ./api/tests/Feature/Forms/RedirectUrlLengthTest.php

Length of output: 4425

api/tests/Feature/Forms/RedirectUrlLengthTest.php (1)

19-29: LGTM! Test covers null handling.

The test properly verifies that null values are accepted for the redirect_url field.

api/app/Open/MentionParser.php (1)

20-24: LGTM! Method enables URL-friendly output.

The urlFriendlyOutput method provides a clean way to toggle URL encoding behavior.

Comment on lines +140 to +143
if ($this->urlFriendly && $value !== null) {
return is_array($value)
? array_map('urlencode', $value)
: urlencode($value);
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add safeguards against double URL encoding.

The current implementation might double-encode values if they're already URL-encoded. Consider adding a check to prevent this.

     if ($this->urlFriendly && $value !== null) {
+        $encode = function($str) {
+            return rawurlencode(rawurldecode($str));
+        };
         return is_array($value)
-            ? array_map('urlencode', $value)
-            : urlencode($value);
+            ? array_map($encode, $value)
+            : $encode($value);
     }
📝 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
if ($this->urlFriendly && $value !== null) {
return is_array($value)
? array_map('urlencode', $value)
: urlencode($value);
if ($this->urlFriendly && $value !== null) {
$encode = function($str) {
return rawurlencode(rawurldecode($str));
};
return is_array($value)
? array_map($encode, $value)
: $encode($value);

@@ -55,7 +55,7 @@ public function rules()
're_fillable' => 'boolean',
're_fill_button_text' => 'string|min:1|max:50',
'submitted_text' => 'string|max:2000',
'redirect_url' => 'nullable|max:255',
'redirect_url' => 'nullable|string',
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

Consider adding URL validation and reasonable length constraints.

While removing the 255-character limit is necessary for longer URLs, consider:

  1. Adding URL format validation at the request level
  2. Setting a reasonable maximum length to prevent potential DoS attacks
-            'redirect_url' => 'nullable|string',
+            'redirect_url' => 'nullable|string|url|max:2048',
📝 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
'redirect_url' => 'nullable|string',
'redirect_url' => 'nullable|string|url|max:2048',

@JhumanJ JhumanJ merged commit ea4cd85 into main Dec 10, 2024
5 checks passed
@JhumanJ JhumanJ deleted the ESC-399_redirect-is-showing-limit branch December 10, 2024 11:26
JonBons pushed a commit to JonBons/OpnForm that referenced this pull request Dec 10, 2024
…J#639)

- Updated the `redirect_url` validation in `UserFormRequest` to accept strings instead of just max length.
- Modified `MentionParser` to include a `urlFriendlyOutput` method, allowing for URL encoding of special characters in parsed values.
- Adjusted the `PublicFormController` to utilize the new `urlFriendlyOutput` method for redirect URLs.
- Created a migration to change the `redirect_url` field type in the database from string to text, accommodating longer URLs.
- Added tests to ensure proper handling of long redirect URLs and the functionality of the new URL-friendly output feature in `MentionParser`.

This update improves the flexibility and robustness of form handling and URL processing.
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