Last active
November 27, 2023 18:11
-
-
Save barryhughes/d2a10265b0905989edffb2b969edf725 to your computer and use it in GitHub Desktop.
Detect usage of WooCommerce's legacy REST API. Logs any attempts, and displays an admin notice.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Plugin name: Detect Legacy REST API Usage (WooCommerce) | |
* Description: Attempts to detect and log usage of WooCommerce's legacy REST API. | |
* Version: 2023-11-24.1 | |
*/ | |
function detect_and_log_wc_legacy_api_requests() { | |
global $wp; | |
if ( ! function_exists( 'wc_get_logger' ) ) { | |
return; | |
} | |
$legacy_api_version = esc_html( $_GET['wc-api-version'] ?? $wp->query_vars['wc-api-version'] ?? '' ); | |
$legacy_api_route = esc_html( $_GET['wc-api-route'] ?? $wp->query_vars['wc-api-route'] ?? '' ); | |
$user_agent = $_SERVER['HTTP_USER_AGENT'] ?? 'unknown user agent'; | |
if ( empty( $legacy_api_version ) && empty( $legacy_api_route ) ) { | |
return; | |
} | |
wc_get_logger()->info( "đź’ˇ LEGACY REST API USAGE DETECTED (version $legacy_api_version): $legacy_api_route ($user_agent)" ); | |
update_option( 'wc_legacy_rest_usage', array( | |
'version' => $legacy_api_version, | |
'route' => $legacy_api_route, | |
'user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? 'unknown', | |
'datetime' => wp_date( 'Y-m-d H:i:s' ), | |
) ); | |
} | |
function display_legacy_wc_api_usage_notice() { | |
$legacy_usage = get_option( 'wc_legacy_rest_usage' ); | |
if ( ! is_array( $legacy_usage ) ) { | |
return; | |
} | |
$defaults = array( 'version' => 'unknown', 'route' => 'unknown', 'user_agent' => 'unknown', 'datetime' => 'unknown' ); | |
$usage = array_map( 'esc_html', array_merge( $defaults, $legacy_usage ) ); | |
echo " | |
<div class='notice'> | |
<p><strong>đź’ˇ LEGACY REST API USAGE DETECTED</strong> at {$usage['datetime']}</p> | |
<p> | |
Version <kbd>{$usage['version']}</kbd> | | |
Route <kbd>{$usage['route']}</kbd> | | |
Agent <kbd>{$usage['user_agent']}</kbd> | |
</p> | |
</p></div> | |
"; | |
} | |
add_action( 'parse_request', 'detect_and_log_wc_legacy_api_requests', -1 ); | |
add_action( 'admin_notices', 'display_legacy_wc_api_usage_notice' ); |
Good suggestions ... we could definitely store a dictionary of user agents or something (probably the chief value is in—hopefully—helping to identify the sources of the requests).
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Also might want to add a unique
source
prop to the log entry context. That way these log entries could be kept in a separate file from other logs.