Skip to content

WooCommerce Analytics: Improve get_current_url() and URL sanitization #44679

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

Merged
merged 7 commits into from
Aug 11, 2025

Conversation

chihsuan
Copy link
Member

@chihsuan chihsuan commented Aug 7, 2025

Fixes WOOA7S-344

Proposed changes:

Implements security improvements to address potential XSS vulnerabilities in WooCommerce Analytics session cookie handling and URL sanitization identified during code review.

Note: The session management is a new feature that is not yet in production.

The Problem:

During security analysis, theoretical XSS vulnerabilities were identified where user-controlled data (session_id, landing_page, session_expiration) was directly interpolated into JavaScript strings without proper escaping. However, during extensive testing with various payloads, browsers automatically URL-encode special characters (e.g., ' becomes %27), which prevents most practical XSS attacks. Despite multiple attack attempts, no successful XSS execution was achieved through these vectors.

The Solution (Defense in Depth):

Although the vulnerabilities appear largely mitigated by browser behavior, defensive security improvements were implemented following security best practices:

  • Enhanced Session Cookie Security:

    • Refactored cookie creation to use rawurlencode(wp_json_encode()) for proper data encoding
    • Improved cookie retrieval with rawurldecode() and robust validation
    • Added proper error handling for malformed cookie data
  • Improved URL Handling:

    • Replaced direct $_SERVER variable usage with WordPress URL functions (home_url() + add_query_arg())
    • Enhanced get_current_url() method with WordPress-native URL handling: home_url( add_query_arg( null, null ) )
    • Better security through WordPress built-in URL sanitization and validation
    • Eliminated direct access to superglobal variables

Security Improvements:

  • Eliminated direct string interpolation in JavaScript cookie handling
  • Replaced $_SERVER access with secure WordPress URL functions
  • Added defense-in-depth protection against potential XSS vectors
  • Proper WordPress security function usage following core best practices
  • Robust input validation and error handling

Testing instructions:

Security Testing Performed

XSS Attack Attempts:

  • Tested with malicious URLs: /?test=');alert('XSS');//
  • Attempted various payload formats in landing page URLs
  • Tested with crafted HTTP headers and request URIs
  • Result: All attempts automatically URL-encoded by browsers ('%27, )%29)
  • Conclusion: No successful XSS execution achieved through these vectors

Functional Testing

Session Cookie Functionality:

  1. Go to any front end page
  2. Check that woocommerceanalytics_session cookie contains properly encoded JSON
  3. Confirm cookie data includes session_id, landing_page, and expires fields
  4. Go to network tab and check that w.gif request contains the expected landing_page and session_id fields.
  5. Visit another page and check that the woocommerceanalytics_session cookie is updated with the is_engaged field set to true.
Screenshot 2025-08-08 at 16 50 12 Screenshot 2025-08-08 at 16 50 23

Other information:

  • Have you written new tests for your changes, if applicable?
  • Have you checked the E2E test CI results, and verified that your changes do not break them?
  • Have you tested your changes on WordPress.com, if applicable?

Jetpack product discussion

Discussed with Woo Analytics team as part of security hardening review.

Does this pull request change what data or activity we track or use?

No, this PR only improves the security of existing data handling without changing what data is tracked or how it's used.

@chihsuan chihsuan self-assigned this Aug 7, 2025
@chihsuan chihsuan marked this pull request as ready for review August 7, 2025 07:50
Copy link
Contributor

github-actions bot commented Aug 7, 2025

Are you an Automattician? Please test your changes on all WordPress.com environments to help mitigate accidental explosions.

  • To test on WoA, go to the Plugins menu on a WoA dev site. Click on the "Upload" button and follow the upgrade flow to be able to upload, install, and activate the Jetpack Beta plugin. Once the plugin is active, go to Jetpack > Jetpack Beta, select your plugin (Jetpack), and enable the enhance/js-url-sanitize branch.
  • To test on Simple, run the following command on your sandbox:
bin/jetpack-downloader test jetpack enhance/js-url-sanitize

Interested in more tips and information?

  • In your local development environment, use the jetpack rsync command to sync your changes to a WoA dev blog.
  • Read more about our development workflow here: PCYsg-eg0-p2
  • Figure out when your changes will be shipped to customers here: PCYsg-eg5-p2

Copy link
Contributor

github-actions bot commented Aug 7, 2025

Thank you for your PR!

When contributing to Jetpack, we have a few suggestions that can help us test and review your patch:

  • ✅ Include a description of your PR changes.
  • ✅ Add a "[Status]" label (In Progress, Needs Review, ...).
  • ✅ Add a "[Type]" label (Bug, Enhancement, Janitorial, Task).
  • ✅ Add testing instructions.
  • ✅ Specify whether this PR includes any changes to data or privacy.
  • ✅ Add changelog entries to affected projects

This comment will be updated as you work on your PR and make changes. If you think that some of those checks are not needed for your PR, please explain why you think so. Thanks for cooperation 🤖


Follow this PR Review Process:

  1. Ensure all required checks appearing at the bottom of this PR are passing.
  2. Make sure to test your changes on all platforms that it applies to. You're responsible for the quality of the code you ship.
  3. You can use GitHub's Reviewers functionality to request a review.
  4. When it's reviewed and merged, you will be pinged in Slack to deploy the changes to WordPress.com simple once the build is done.

If you have questions about anything, reach out in #jetpack-developers for guidance!

@github-actions github-actions bot added the [Status] Needs Author Reply We need more details from you. This label will be auto-added until the PR meets all requirements. label Aug 7, 2025
$cookie_js = "
const sessionData = JSON.stringify({
session_id: '$this->session_id',
landing_page: encodeURIComponent('$this->landing_page'),
Copy link
Member Author

@chihsuan chihsuan Aug 7, 2025

Choose a reason for hiding this comment

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

If landing_page contains a malicious URL /?test='+window.alert('XSS')+', it would get interpolated directly into the JavaScript:

const sessionData = JSON.stringify({
        session_id: '9a2eabba-0ed7-49f1-b1d4-0d009e487c79',
        landing_page: encodeURIComponent('https://example.com/?test='+window.alert('XSS')+''),
        expires: 'Fri, 08 Aug 2025 08:53:34 GMT',
});

Now, we encode the entire object via PHP to avoid any potential attacks.

Copy link

jp-launch-control bot commented Aug 7, 2025

Code Coverage Summary

No summary data is available for parent commit c3c05df, so cannot calculate coverage changes. 😴

If that commit is a feature branch rather than a trunk commit, this is expected. Otherwise, this should be updated once coverage for c3c05df is available.

Full summary · PHP report · JS report

@chihsuan chihsuan added [Type] Enhancement Changes to an existing feature — removing, adding, or changing parts of it and removed [Status] Needs Author Reply We need more details from you. This label will be auto-added until the PR meets all requirements. [Status] In Progress labels Aug 7, 2025
@github-actions github-actions bot added the [Status] Needs Author Reply We need more details from you. This label will be auto-added until the PR meets all requirements. label Aug 7, 2025
@chihsuan chihsuan force-pushed the enhance/js-url-sanitize branch from dd4ea3d to e0a7d50 Compare August 7, 2025 09:08
'expires' => $session_expiration,
);
$encoded_data = wp_json_encode( $session_data );
$cookie_js = "document.cookie = 'woocommerceanalytics_session={$encoded_data}; expires={$session_expiration}; path=/; secure; samesite=strict';";
Copy link
Member Author

@chihsuan chihsuan Aug 7, 2025

Choose a reason for hiding this comment

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

I considered using PHP to set the cookie, but I realized that it might not be the best approach for our use case since we may want to delay setting the cookie until getting user consent for tracking in the future implementation.

Additionally, PHP cookie can only be set before any output is sent to the browser. When I tried to set the cookie using PHP, I encountered an error message saying “Cannot send session cookie - headers already sent.”.

…URL sanitization

* Refactor session cookie creation to use wp_json_encode for better data handling.
* Enhance get_current_url method to improve URL sanitization and handling of request components.
…data encoding

* Simplify session data creation by directly using an array and encoding it with rawurlencode.
* Update get_session_cookie method to handle cookie decoding more robustly without unnecessary sanitization.
* Ensure proper handling of session data retrieval from cookies.
…ssion data encoding

* Update landing page retrieval to use the method directly instead of a variable.
* Change session data encoding to use wp_json_encode for consistency and improved handling.
* Simplify cookie decoding by removing unnecessary rawurlencode.
@chihsuan chihsuan force-pushed the enhance/js-url-sanitize branch 2 times, most recently from ef7aa48 to 4853b2e Compare August 7, 2025 10:12
@@ -828,7 +835,7 @@ public function get_session_cookie() {
* @return string
*/
public function get_current_url() {
return sanitize_url( wp_unslash( ( empty( $_SERVER['HTTPS'] ) ? 'http' : 'https' ) . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]" ) ); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotValidatedNotSanitized -- actually escaped with sanitize_url.
return home_url( add_query_arg( null, null ) );
Copy link
Member Author

@chihsuan chihsuan Aug 8, 2025

Choose a reason for hiding this comment

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

I replaced usage of the $_SERVER variable with home_url() to retrieve the current URL, as home_url() should generally be more dependable.

Copy link
Member Author

@chihsuan chihsuan Aug 8, 2025

Choose a reason for hiding this comment

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

The sanitize_url does not provide protection against XSS attacks, but it can be useful when storing URLs in a database. In this scenario, however, we are not storing the URL in a database but sending it to an external server.

echo sanitize_url( wp_unslash( ( "https://example.com/?test='+window.alert('XSS')+'' ) );

https://example.com/?test='+window.alert('XSS')+ // nothing is escaped 

* Simplify session engagement handling by directly modifying session data and using wp_json_encode for cookie creation.
* Remove unnecessary cookie decoding logic and streamline JavaScript enqueueing for engagement tracking.
…e tracking

* Add landing page encoding to session data before cookie creation.
* Ensure session engagement flag is set correctly for improved tracking.
@chihsuan chihsuan changed the title WooCommerce Analytics: Improve URL sanitization WooCommerce Analytics: Improve get_current_url() and URL sanitization Aug 8, 2025
@chihsuan chihsuan added [Status] Needs Review This PR is ready for review. and removed [Status] Needs Author Reply We need more details from you. This label will be auto-added until the PR meets all requirements. labels Aug 8, 2025
@chihsuan chihsuan requested a review from a team August 8, 2025 08:56
@chihsuan chihsuan requested a review from louwie17 August 8, 2025 08:56
Copy link
Member

@Nikschavan Nikschavan left a comment

Choose a reason for hiding this comment

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

Tested on a test site, this does work as described!

Image

@chihsuan chihsuan merged commit 207cd57 into release/woocommerce-analytics-0.5.0 Aug 11, 2025
66 of 68 checks passed
@chihsuan chihsuan deleted the enhance/js-url-sanitize branch August 11, 2025 01:37
@github-actions github-actions bot removed the [Status] Needs Review This PR is ready for review. label Aug 11, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
[Feature] WooCommerce Analytics [Package] WooCommerce Analytics Enhanced analytics for WooCommerce users [Type] Enhancement Changes to an existing feature — removing, adding, or changing parts of it
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants