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

Refactor Boilerplate project template url escaping (#9869) #9874

Merged
merged 4 commits into from
Feb 12, 2025

Conversation

ysmoradi
Copy link
Member

@ysmoradi ysmoradi commented Feb 12, 2025

closes #9869

Summary by CodeRabbit

  • Bug Fixes

    • Adjusted redirection on sign‐in and sign‐up pages so that users without a specified return link are now routed to the home page.
    • Improved navigation on error and unauthorized pages, ensuring smoother, more consistent user redirection.
  • Refactor

    • Enhanced URL processing by applying proper encoding and decoding to all navigation links.
    • Refined query string management and logging across the application for increased reliability and consistency.

@ysmoradi ysmoradi requested a review from msynk February 12, 2025 13:52
Copy link

coderabbitai bot commented Feb 12, 2025

Important

Review skipped

Auto incremental reviews are disabled on this repository.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

This pull request updates URL handling and query string processing across client and server components. Changes include decoding URLs before assignment and logging, ensuring proper encoding for navigation links, and simplifying URL concatenation logic. Several files now use a new query string parsing class in place of HttpUtility methods. Additionally, default navigation fallbacks have been revised, and a new extension method is added for passing query parameters to controllers.

Changes

File(s) Change Summary
src/…/Components/ClientAppCoordinator.cs, src/…/Services/HttpMessageHandlers/LoggingDelegatingHandler.cs, src/…/Controllers/Identity/IdentityController.cs Updated URL handling to decode URLs (using HttpUtility.UrlDecode or Uri.EscapeDataString) before assignment and logging, and simplified encoding for query parameters.
src/…/Pages/Identity/SignIn/SignInPanel.razor, src/…/Pages/Identity/SignUp/SignUpPage.razor, src/…/Pages/NotAuthorizedPage.razor.cs Revised hyperlink defaults to use Urls.HomePage when return URLs are null and streamlined string interpolation in navigation logic.
src/…/Services/ODataQuery.cs, src/…/Program.Middlewares.cs, src/…/Extensions/UriExtensions.cs, src/…/Services/QueryStringCollection.cs Replaced HttpUtility.ParseQueryString with a new QueryStringCollection for parsing and constructing query strings, and removed unused using directives.
src/…/Pages/AppPageBase.cs Modified URL construction for the Not Found page by applying Uri.EscapeDataString to the relative path.
src/…/Shared/Controllers/IAppController.cs Added a new extension method WithQuery<TAppController> to allow passing a dictionary of query strings to the IAppController.

Sequence Diagram(s)

sequenceDiagram
  participant NM as NavigationManager
  participant CAC as ClientAppCoordinator
  participant LDH as LoggingDelegatingHandler
  participant QSC as QueryStringCollection

  NM->>CAC: Navigate with raw URL
  CAC->>CAC: Decode URL using HttpUtility.UrlDecode
  CAC->>LDH: Log decoded URL update
  NM->>LDH: HTTP request sent with URL
  LDH->>QSC: Parse query string via QueryStringCollection.Parse
  QSC-->>LDH: Return parsed query data
Loading

Poem

I hopped through lines of code so neat,
Decoding paths where raw URLs meet,
Query strings now dance in a brand new light,
Home pages guide when paths aren't outright,
With a skip and a jump in every update,
This bunny cheers changes both small and great!


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 generate docstrings to generate docstrings for this PR. (Beta)
  • @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.

@ysmoradi ysmoradi marked this pull request as draft February 12, 2025 14:07
@ysmoradi ysmoradi changed the title refactor Boilerplate url escaping (#9869) Refactor Boilerplate project template url escaping (#9869) Feb 12, 2025
@ysmoradi ysmoradi marked this pull request as ready for review February 12, 2025 15:16
Copy link

@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)
src/Templates/Boilerplate/Bit.Boilerplate/src/Client/Boilerplate.Client.Core/Components/Pages/NotAuthorizedPage.razor.cs (1)

61-61: Consider extracting duplicated URL construction logic.

While the URL encoding implementation is correct, this logic is duplicated from NotAuthorizedPage.SignOut. Consider extracting it to a shared helper method to improve maintainability.

Example refactor:

+private static class NavigationHelper
+{
+    public static string BuildSignInUrl(string returnUrl)
+    {
+        return $"{Urls.SignInPage}?return-url={Uri.EscapeDataString(returnUrl)}";
+    }
+}

 private async Task SignOut()
 {
     await AuthManager.SignOut(CurrentCancellationToken);
     var returnUrl = ReturnUrl ?? NavigationManager.GetRelativePath();
-    NavigationManager.NavigateTo($"{Urls.SignInPage}?return-url={Uri.EscapeDataString(returnUrl)}");
+    NavigationManager.NavigateTo(NavigationHelper.BuildSignInUrl(returnUrl));
 }

 protected override async Task OnAfterFirstRenderAsync()
 {
     await base.OnAfterFirstRenderAsync();
     await AuthManager.SignOut(CurrentCancellationToken);
     var returnUrl = ReturnUrl ?? NavigationManager.GetRelativePath();
-    NavigationManager.NavigateTo($"{Urls.SignInPage}?return-url={Uri.EscapeDataString(returnUrl)}");
+    NavigationManager.NavigateTo(NavigationHelper.BuildSignInUrl(returnUrl));
 }
src/Templates/Boilerplate/Bit.Boilerplate/src/Shared/Services/QueryStringCollection.cs (1)

14-14: Consider caching the escaped values.

The current implementation performs both escape and unescape operations on every add operation, which could be optimized.

-        keyValues[Uri.EscapeDataString(Uri.UnescapeDataString(key))] = Uri.EscapeDataString(Uri.UnescapeDataString(value ?? ""));
+        var escapedKey = Uri.EscapeDataString(Uri.UnescapeDataString(key));
+        var escapedValue = Uri.EscapeDataString(Uri.UnescapeDataString(value ?? ""));
+        keyValues[escapedKey] = escapedValue;
src/Templates/Boilerplate/Bit.Boilerplate/src/Client/Boilerplate.Client.Core/Components/Pages/Identity/SignUp/SignUpPage.razor (1)

81-82: Consider extracting the URL construction logic.

The confirm link URL construction is complex and could benefit from being moved to a dedicated method or helper class.

+private string GetConfirmUrl(string? email, string? phoneNumber, string? returnUrl) =>
+    $"{Urls.ConfirmPage}?email={Uri.EscapeDataString(email ?? "")}&phoneNumber={Uri.EscapeDataString(phoneNumber ?? "")}&return-url={Uri.EscapeDataString(returnUrl ?? Urls.HomePage)}";

-<BitLink Href="@($"{Urls.ConfirmPage}?email={Uri.EscapeDataString(signUpModel.Email ?? "")}&phoneNumber={Uri.EscapeDataString(signUpModel.PhoneNumber ?? "")}&return-url={Uri.EscapeDataString(ReturnUrlQueryString ?? Urls.HomePage)}")">
+<BitLink Href="@GetConfirmUrl(signUpModel.Email, signUpModel.PhoneNumber, ReturnUrlQueryString)">
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 332071e and b0681a7.

📒 Files selected for processing (12)
  • src/Templates/Boilerplate/Bit.Boilerplate/src/Client/Boilerplate.Client.Core/Components/ClientAppCoordinator.cs (3 hunks)
  • src/Templates/Boilerplate/Bit.Boilerplate/src/Client/Boilerplate.Client.Core/Components/Pages/AppPageBase.cs (1 hunks)
  • src/Templates/Boilerplate/Bit.Boilerplate/src/Client/Boilerplate.Client.Core/Components/Pages/Identity/SignIn/SignInPanel.razor (1 hunks)
  • src/Templates/Boilerplate/Bit.Boilerplate/src/Client/Boilerplate.Client.Core/Components/Pages/Identity/SignUp/SignUpPage.razor (1 hunks)
  • src/Templates/Boilerplate/Bit.Boilerplate/src/Client/Boilerplate.Client.Core/Components/Pages/NotAuthorizedPage.razor.cs (2 hunks)
  • src/Templates/Boilerplate/Bit.Boilerplate/src/Client/Boilerplate.Client.Core/Services/HttpMessageHandlers/LoggingDelegatingHandler.cs (3 hunks)
  • src/Templates/Boilerplate/Bit.Boilerplate/src/Client/Boilerplate.Client.Core/Services/ODataQuery.cs (2 hunks)
  • src/Templates/Boilerplate/Bit.Boilerplate/src/Server/Boilerplate.Server.Api/Controllers/Identity/IdentityController.cs (1 hunks)
  • src/Templates/Boilerplate/Bit.Boilerplate/src/Server/Boilerplate.Server.Web/Program.Middlewares.cs (1 hunks)
  • src/Templates/Boilerplate/Bit.Boilerplate/src/Shared/Controllers/IAppController.cs (1 hunks)
  • src/Templates/Boilerplate/Bit.Boilerplate/src/Shared/Extensions/UriExtensions.cs (2 hunks)
  • src/Templates/Boilerplate/Bit.Boilerplate/src/Shared/Services/QueryStringCollection.cs (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • src/Templates/Boilerplate/Bit.Boilerplate/src/Server/Boilerplate.Server.Api/Controllers/Identity/IdentityController.cs
🔇 Additional comments (13)
src/Templates/Boilerplate/Bit.Boilerplate/src/Client/Boilerplate.Client.Core/Components/Pages/NotAuthorizedPage.razor.cs (1)

47-47: LGTM! Proper URL encoding implementation.

The change correctly uses Uri.EscapeDataString to encode the return URL, preventing potential URL injection vulnerabilities.

src/Templates/Boilerplate/Bit.Boilerplate/src/Shared/Controllers/IAppController.cs (1)

31-36: LGTM! Well-designed extension method.

The new extension method maintains consistency with existing methods while providing a fluent interface for adding multiple query strings. The implementation correctly delegates to the AddQueryStrings method and follows the same generic pattern.

src/Templates/Boilerplate/Bit.Boilerplate/src/Client/Boilerplate.Client.Core/Components/Pages/AppPageBase.cs (1)

23-23: LGTM! Proper URL encoding.

The addition of Uri.EscapeDataString() ensures that special characters in the relative path are properly encoded, preventing potential URL injection vulnerabilities.

src/Templates/Boilerplate/Bit.Boilerplate/src/Client/Boilerplate.Client.Core/Services/HttpMessageHandlers/LoggingDelegatingHandler.cs (1)

11-11: LGTM! Enhanced URL logging.

The addition of HttpUtility.UrlDecode improves the readability of logged URLs by decoding them before logging. The change is consistently applied to both request and response logging.

Also applies to: 27-27

src/Templates/Boilerplate/Bit.Boilerplate/src/Client/Boilerplate.Client.Core/Services/ODataQuery.cs (1)

31-31: LGTM! Modern query string handling.

The replacement of HttpUtility.ParseQueryString with QueryStringCollection aligns with the PR's objective of modernizing URL handling while maintaining the same functionality.

src/Templates/Boilerplate/Bit.Boilerplate/src/Shared/Extensions/UriExtensions.cs (2)

7-8: LGTM! The query string handling has been improved.

The switch to QueryStringCollection provides better control over URL encoding/decoding and maintains consistency with the new query string handling approach across the codebase.

Also applies to: 12-13


27-27: LGTM! Culture parameter extraction has been simplified.

The change to use QueryStringCollection.Parse simplifies the culture parameter extraction while maintaining the same functionality.

src/Templates/Boilerplate/Bit.Boilerplate/src/Shared/Services/QueryStringCollection.cs (1)

71-81: Add validation for malformed query strings.

The current implementation might not handle all edge cases of malformed query strings.

Consider adding validation for:

  • Maximum key/value lengths
  • Invalid characters
  • Duplicate keys
 foreach (var pair in pairs)
 {
     // Split the pair into key and value using '='.
     var parts = pair.Split(['='], 2);
+    if (parts[0].Length > 2048) // Example max length
+        continue;
     string key = parts[0];
     string value = parts.Length > 1 ? parts[1] : string.Empty;
+    if (value.Length > 2048) // Example max length
+        continue;
     qsCollection.Add(key, value);
 }
src/Templates/Boilerplate/Bit.Boilerplate/src/Client/Boilerplate.Client.Core/Components/Pages/Identity/SignIn/SignInPanel.razor (1)

81-81: LGTM! URL escaping and fallback have been improved.

The changes properly escape the return URL and provide a sensible default to the homepage when no return URL is specified.

src/Templates/Boilerplate/Bit.Boilerplate/src/Client/Boilerplate.Client.Core/Components/Pages/Identity/SignUp/SignUpPage.razor (1)

79-79: LGTM! URL escaping and fallback have been improved.

The changes properly escape the return URL and provide a sensible default to the homepage when no return URL is specified.

src/Templates/Boilerplate/Bit.Boilerplate/src/Client/Boilerplate.Client.Core/Components/ClientAppCoordinator.cs (2)

58-58: LGTM! URL decoding added for telemetry.

The addition of URL decoding ensures that telemetry data contains human-readable URLs instead of encoded ones.


90-91: LGTM! Consistent URL decoding in location change handler.

URL decoding is consistently applied to both the telemetry context and logging, improving readability of the logs.

src/Templates/Boilerplate/Bit.Boilerplate/src/Server/Boilerplate.Server.Web/Program.Middlewares.cs (1)

298-298: LGTM! Consistent query string parsing.

The change to use QueryStringCollection.Parse aligns with the broader effort to standardize query string handling across the codebase.

@msynk msynk merged commit f7edf0c into bitfoundation:develop Feb 12, 2025
3 checks passed
@ysmoradi ysmoradi deleted the 9869 branch February 12, 2025 15:42
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.

Boilerplate project template url's escaping codes needs refactoring
2 participants