Commit a4416ea690c for woocommerce
commit a4416ea690c3383609ca51b9e4844fbc228381c7
Author: Luigi Teschio <gigitux@gmail.com>
Date: Fri Nov 20 16:01:56 2026 +0100
Omit call arguments from fatal and Store API error logs (#71238)
(cherry picked from commit 07b3b82dd3d72f0a3c42ffb189039367a02310f5)
Co-authored-by: Ján Mikláš <neosinner@gmail.com>
diff --git a/plugins/woocommerce/includes/class-woocommerce.php b/plugins/woocommerce/includes/class-woocommerce.php
index 4a8f32d56db..1620d057e02 100644
--- a/plugins/woocommerce/includes/class-woocommerce.php
+++ b/plugins/woocommerce/includes/class-woocommerce.php
@@ -540,14 +540,22 @@ final class WooCommerce {
);
if ( false !== strpos( $message, 'Stack trace:' ) ) {
- $segments = explode( 'Stack trace:', $message );
- $message = str_replace( PHP_EOL, ' ', trim( $segments[0] ) );
- $backtrace = array_map(
- 'trim',
- explode( PHP_EOL, $segments[1] )
- );
-
- $context['backtrace'] = $backtrace;
+ $segments = explode( 'Stack trace:', $message, 2 );
+ $message = str_replace( PHP_EOL, ' ', trim( $segments[0] ) );
+
+ $context['backtrace'] = array();
+ foreach ( explode( "\n", trim( $segments[1] ) ) as $line ) {
+ // Cap each line so one huge line cannot hit the PCRE backtrack limit.
+ $line = substr( $line, 0, 4096 );
+ // Keep only frame headers, including eval, anonymous class and PHP 8.4 closure frames, and drop their arguments.
+ // PHP escapes newlines inside trace arguments, so an argument cannot start a frame line of its own.
+ if ( preg_match( '/^#\d+ (?:(?:\[internal function\]|.*?\(\d+\)): (?:\{closure[^{}\'\r\n]*+\}|[^(\r\n])++\(|\{main\})/', $line, $frame ) ) {
+ $context['backtrace'][] = '(' === substr( $frame[0], -1 ) ? $frame[0] . ')' : $frame[0];
+ } elseif ( preg_match( '/^Next ([\w\\\\]+): /', $line, $next ) ) {
+ // Keep the chained exception class, not its message.
+ $context['backtrace'][] = 'Next ' . $next[1];
+ }
+ }
} else {
$context['backtrace'] = true;
}
diff --git a/plugins/woocommerce/src/StoreApi/Utilities/UnexpectedErrorResponse.php b/plugins/woocommerce/src/StoreApi/Utilities/UnexpectedErrorResponse.php
index 133e835325d..fce78babbd0 100644
--- a/plugins/woocommerce/src/StoreApi/Utilities/UnexpectedErrorResponse.php
+++ b/plugins/woocommerce/src/StoreApi/Utilities/UnexpectedErrorResponse.php
@@ -53,8 +53,8 @@ final class UnexpectedErrorResponse {
'file' => $error->getFile(),
'line' => $error->getLine(),
),
- // Same shape the fatal-error shutdown handler logs, so log handlers and readers see one trace format.
- 'backtrace' => array_slice( explode( "\n", $error->getTraceAsString() ), 0, self::MAX_BACKTRACE_FRAMES ),
+ // Same frame format the fatal-error shutdown handler logs, so log handlers and readers see one trace format.
+ 'backtrace' => self::get_backtrace( $error ),
// These failures reached remote logging as fatals before the dispatchers caught them.
'remote-logging' => true,
)
@@ -75,6 +75,28 @@ final class UnexpectedErrorResponse {
return new WP_Error( 'woocommerce_rest_unknown_server_error', $message, $data );
}
+ /**
+ * Format the original call sites without exposing argument values.
+ *
+ * @param \Throwable $error Caught failure.
+ * @return string[]
+ */
+ private static function get_backtrace( \Throwable $error ): array {
+ $backtrace = array();
+ foreach ( array_slice( $error->getTrace(), 0, self::MAX_BACKTRACE_FRAMES ) as $index => $frame ) {
+ $backtrace[] = sprintf(
+ '#%d %s: %s%s%s()',
+ $index,
+ isset( $frame['file'], $frame['line'] ) ? $frame['file'] . '(' . $frame['line'] . ')' : '[internal function]',
+ // Anonymous class names continue past a NUL byte with the declaring path; PHP's own traces stop there.
+ explode( "\0", $frame['class'] ?? '' )[0],
+ $frame['type'] ?? '',
+ explode( "\0", $frame['function'] )[0]
+ );
+ }
+ return $backtrace;
+ }
+
/**
* Whether the current request may receive the failure message and class.
*
diff --git a/plugins/woocommerce/tests/legacy/mockable-functions.php b/plugins/woocommerce/tests/legacy/mockable-functions.php
index 974619882e0..e4873e7e6e2 100644
--- a/plugins/woocommerce/tests/legacy/mockable-functions.php
+++ b/plugins/woocommerce/tests/legacy/mockable-functions.php
@@ -9,6 +9,7 @@
return array(
'current_user_can',
+ 'error_get_last',
'get_bloginfo',
'get_woocommerce_currencies',
'get_woocommerce_currency_symbol',
diff --git a/plugins/woocommerce/tests/php/includes/class-woocommerce-test.php b/plugins/woocommerce/tests/php/includes/class-woocommerce-test.php
index 6f042493b32..a965bd0c989 100644
--- a/plugins/woocommerce/tests/php/includes/class-woocommerce-test.php
+++ b/plugins/woocommerce/tests/php/includes/class-woocommerce-test.php
@@ -3,11 +3,137 @@
declare( strict_types = 1 );
use Automattic\WooCommerce\Internal\Utilities\LegacyRestApiStub;
+use Automattic\WooCommerce\RestApi\UnitTests\LoggerSpyTrait;
+use Automattic\WooCommerce\Testing\Tools\CodeHacking\Hacks\FunctionsMockerHack;
/**
* Unit tests for the WooCommerce class.
*/
class WooCommerce_Test extends \WC_Unit_Test_Case {
+ use LoggerSpyTrait;
+
+ /**
+ * @testdox Should omit arguments from fatal error backtraces while preserving call sites.
+ * @testWith ["#0 /tmp/gateway.php(12): Processor->charge('378282246310005', '2440')", "#0 /tmp/gateway.php(12): Processor->charge()"]
+ * ["#0 /tmp/商店/café.php(12): Paiement\\支付->دفع('378282246310005', '2440')", "#0 /tmp/商店/café.php(12): Paiement\\支付->دفع()"]
+ * ["#0 /tmp/gateway.php(12): {closure:/tmp/gateway.php:8}('378282246310005', '2440')", "#0 /tmp/gateway.php(12): {closure:/tmp/gateway.php:8}()"]
+ * ["#0 [internal function]: call_user_func('378282246310005', '2440')", "#0 [internal function]: call_user_func()"]
+ * ["#0 [internal function]: pay('378282246310005', 'x(1): y(', '2440')", "#0 [internal function]: pay()"]
+ * ["#0 /tmp/gateway.php(12): Processor->charge('378282246310005', '2440'", "#0 /tmp/gateway.php(12): Processor->charge()"]
+ * ["#0 /tmp/gateway.php(12): Processor->{closure:Processor::charge():8}('378282246310005', '2440')", "#0 /tmp/gateway.php(12): Processor->{closure:Processor::charge():8}()"]
+ * ["#0 /tmp/gateway.php(12): Processor->charge('a(1): b', '378282246310005', '2440(')", "#0 /tmp/gateway.php(12): Processor->charge()"]
+ * ["#0 C:\\gateway.php(12): Processor->charge('378282246310005', '2440')\r\n#1 {main}", "#0 C:\\gateway.php(12): Processor->charge()"]
+ * ["#0 /tmp/gateway.php(12): Processor->charge('378282246310005', '\\n2440')", "#0 /tmp/gateway.php(12): Processor->charge()"]
+ * ["#0 /tmp/gateway.php(12): Processor->charge('x\\n#1 a(1): b', '378282246310005', '2440', Object(Foo))", "#0 /tmp/gateway.php(12): Processor->charge()"]
+ * ["#0 /tmp/gateway.php(12): Processor->charge('x\\n#1 a', '378282246310005', '(1): foo(', '2440')", "#0 /tmp/gateway.php(12): Processor->charge()"]
+ * ["#0 /tmp/gateway.php(12): class@anonymous->charge('378282246310005', '2440')", "#0 /tmp/gateway.php(12): class@anonymous->charge()"]
+ * ["#0 /tmp/gateway.php(12) : eval()'d code(1): Processor->charge('378282246310005', '2440')", "#0 /tmp/gateway.php(12) : eval()'d code(1): Processor->charge()"]
+ * ["#0 /tmp/gateway.php(12): Processor->{closure:{closure:Processor::charge():8}:9}('378282246310005', '2440')", "#0 /tmp/gateway.php(12): Processor->{closure:{closure:Processor::charge():8}:9}()"]
+ * ["#0 /tmp/gateway.php(12): class@anonymous->{closure:class@anonymous('378282246310005', '2440')", "#0 /tmp/gateway.php(12): class@anonymous->{closure:class@anonymous()"]
+ * ["#0 /tmp/gateway.php(12): Processor->charge('x\n#1 a(1): {closure:a}{closure:a}{closure:a}{closure:a}{closure:a}{closure:a}{closure:a}{closure:a}{closure:a}{closure:a}{closure:a}{closure:a}{closure:a}{closure:a}{closure:a}{closure:a}{closure:a}{closure:a}{closure:a}{closure:a}{closure:a}{closure:a}{closure:a}{closure:a}{closure:a}', '378282246310005', '2440')", "#0 /tmp/gateway.php(12): Processor->charge()"]
+ * ["#0 /srv/John's \"Store\", Inc/gateway.php(12): {closure:/srv/John's \"Store\", Inc/gateway.php:8}('378282246310005', '2440')", "#0 /srv/John's \"Store\", Inc/gateway.php(12): {closure:/srv/John's \"Store\", Inc/gateway.php:8}()"]
+ * ["#0 /tmp/gateway.php(12): Processor->charge('378282246310005', '2440')\nNext Exception: 378282246310005 in /tmp/gateway.php:12\n thrown in /tmp/gateway.php on line 12", "#0 /tmp/gateway.php(12): Processor->charge()"]
+ *
+ * @param string $frame PHP fatal error trace frame.
+ * @param string $expected_frame Trace frame without arguments.
+ */
+ public function test_omits_arguments_from_fatal_error_backtraces( string $frame, string $expected_frame ): void {
+ FunctionsMockerHack::add_function_mocks(
+ array(
+ 'error_get_last' => static function () use ( $frame ) {
+ return array(
+ 'type' => E_ERROR,
+ 'message' => 'Uncaught TypeError: Fixture payment failure.' . PHP_EOL . 'Stack trace:' . PHP_EOL . $frame . PHP_EOL . '#1 {main}',
+ 'file' => '/tmp/gateway.php',
+ 'line' => 12,
+ );
+ },
+ )
+ );
+
+ WC()->log_errors();
+
+ $this->assertLogged( 'critical', 'Fixture payment failure.', array( 'source' => 'fatal-errors' ) );
+ $context = $this->captured_logs[0]['context'];
+ $this->assertContains( $expected_frame, $context['backtrace'], 'Fatal logs must preserve call sites without arguments.' );
+ $this->assertContains( '#1 {main}', $context['backtrace'], 'The final frame must remain available.' );
+ $this->assertStringNotContainsString( '378282246310005', wp_json_encode( $this->captured_logs ), 'Fatal logs must omit card numbers.' );
+ $this->assertStringNotContainsString( '2440', wp_json_encode( $this->captured_logs ), 'Fatal logs must omit CVCs.' );
+ }
+
+ /**
+ * @testdox Should keep frames from every chained exception when a message contains "Stack trace:".
+ */
+ public function test_keeps_chained_fatal_error_frames(): void {
+ FunctionsMockerHack::add_function_mocks(
+ array(
+ 'error_get_last' => static function () {
+ return array(
+ 'type' => E_ERROR,
+ 'message' => implode(
+ PHP_EOL,
+ array(
+ 'Uncaught RuntimeException: See Stack trace: below.',
+ 'Stack trace:',
+ "#0 /tmp/gateway.php(12): Processor->charge('378282246310005')",
+ '#1 {main}',
+ '',
+ 'Next Exception: Payment failed.',
+ 'Stack trace:',
+ "#0 /tmp/checkout.php(30): Checkout->pay('2440')",
+ '#1 {main}',
+ )
+ ),
+ 'file' => '/tmp/checkout.php',
+ 'line' => 30,
+ );
+ },
+ )
+ );
+
+ WC()->log_errors();
+
+ $backtrace = $this->captured_logs[0]['context']['backtrace'];
+ $this->assertContains( '#0 /tmp/gateway.php(12): Processor->charge()', $backtrace, 'Frames after a message that contains "Stack trace:" must be kept.' );
+ $this->assertContains( '#0 /tmp/checkout.php(30): Checkout->pay()', $backtrace, 'Frames of chained exceptions must be kept.' );
+ $this->assertContains( 'Next Exception', $backtrace, 'Chained exception classes must be kept without their messages.' );
+ $this->assertStringNotContainsString( 'Payment failed.', wp_json_encode( $this->captured_logs ), 'Chained exception messages must be omitted.' );
+ $this->assertStringNotContainsString( '378282246310005', wp_json_encode( $this->captured_logs ), 'Fatal logs must omit card numbers.' );
+ $this->assertStringNotContainsString( '2440', wp_json_encode( $this->captured_logs ), 'Fatal logs must omit CVCs.' );
+ }
+
+ /**
+ * @testdox Should keep the frames after a very long trace line.
+ */
+ public function test_keeps_frames_after_very_long_trace_line(): void {
+ FunctionsMockerHack::add_function_mocks(
+ array(
+ 'error_get_last' => static function () {
+ return array(
+ 'type' => E_ERROR,
+ 'message' => implode(
+ PHP_EOL,
+ array(
+ 'Uncaught Exception: Fixture payment failure.',
+ 'Stack trace:',
+ '#0 ' . str_repeat( 'a', 1000000 ),
+ "#1 /tmp/gateway.php(12): Processor->charge('378282246310005')",
+ '#2 {main}',
+ )
+ ),
+ 'file' => '/tmp/gateway.php',
+ 'line' => 12,
+ );
+ },
+ )
+ );
+
+ WC()->log_errors();
+
+ $backtrace = $this->captured_logs[0]['context']['backtrace'];
+ $this->assertContains( '#1 /tmp/gateway.php(12): Processor->charge()', $backtrace, 'A very long line must not drop the frames after it.' );
+ $this->assertContains( '#2 {main}', $backtrace, 'The final frame must remain available.' );
+ }
/**
* Setup test data. Called before every test.
diff --git a/plugins/woocommerce/tests/php/src/Blocks/StoreApi/Utilities/UnexpectedErrorResponseTest.php b/plugins/woocommerce/tests/php/src/Blocks/StoreApi/Utilities/UnexpectedErrorResponseTest.php
index 49b0a42cd0c..f06d7930c62 100644
--- a/plugins/woocommerce/tests/php/src/Blocks/StoreApi/Utilities/UnexpectedErrorResponseTest.php
+++ b/plugins/woocommerce/tests/php/src/Blocks/StoreApi/Utilities/UnexpectedErrorResponseTest.php
@@ -93,6 +93,58 @@ class UnexpectedErrorResponseTest extends WC_Unit_Test_Case {
$this->assertStringStartsWith( '#0 ', $backtrace[0] );
}
+ /**
+ * @testdox Should omit payment arguments from local and remote error logs.
+ */
+ public function test_omits_payment_arguments_from_error_logs(): void {
+ $previous_ignore_args = ini_set( 'zend.exception_ignore_args', '0' ); // phpcs:ignore WordPress.PHP.IniSet.Risky -- Exercise PHP traces that contain arguments.
+ try {
+ $customer = 'Žluťoučký kôň – العربية – 日本語 – 🛒';
+ $error = ( static function ( $number, $expiry, $cvc, $name ) {
+ $error = new \TypeError( 'Fixture payment failure.' );
+ unset( $number, $expiry, $cvc, $name );
+ return $error;
+ } )( '378282246310005', '12 / 30', '2440', $customer );
+ } finally {
+ ini_set( 'zend.exception_ignore_args', $previous_ignore_args ); // phpcs:ignore WordPress.PHP.IniSet.Risky -- Restore the process setting.
+ }
+
+ $this->assertStringContainsString( '378282246310005', $error->getTraceAsString(), 'The fixture must capture payment arguments.' );
+ $this->assertSame( $customer, $error->getTrace()[0]['args'][3], 'The fixture must capture multilingual customer data.' );
+ UnexpectedErrorResponse::create( $error, self::class );
+
+ $logged = $this->captured_logs[0];
+ $record = wc_get_container()->get( RemoteLogger::class )->get_formatted_log( 'critical', $logged['message'], $logged['context'] );
+ foreach ( array( '378282246310005', '12 / 30', '2440', $customer ) as $secret ) {
+ $this->assertStringNotContainsString( $secret, wp_json_encode( $logged, JSON_UNESCAPED_UNICODE ), 'Local logs must omit call arguments.' );
+ $this->assertStringNotContainsString( $secret, wp_json_encode( $record, JSON_UNESCAPED_UNICODE ), 'Remote logs must omit call arguments.' );
+ }
+ $this->assertStringContainsString( basename( __FILE__ ), $logged['context']['backtrace'][0], 'The trace must retain the call site.' );
+ $this->assertStringStartsWith( '#0 ', $record['trace'], 'Remote logs must retain their existing trace format.' );
+ }
+
+ /**
+ * @testdox Should log anonymous class frames without the hidden declaring path.
+ */
+ public function test_logs_anonymous_class_frames_without_hidden_path(): void {
+ $thrower = new class() {
+ /**
+ * Create a failure from inside an anonymous class method.
+ *
+ * @return \TypeError
+ */
+ public function fail(): \TypeError {
+ return new \TypeError( 'Fixture anonymous failure.' );
+ }
+ };
+
+ UnexpectedErrorResponse::create( $thrower->fail(), self::class );
+
+ $frame = $this->captured_logs[0]['context']['backtrace'][0];
+ $this->assertStringContainsString( 'class@anonymous->fail()', $frame, 'The frame must keep the call site.' );
+ $this->assertStringNotContainsString( "\0", $frame, 'The frame must not contain the NUL byte or the path after it.' );
+ }
+
/**
* @testdox Should log the PHP error type the failure would have produced if uncaught.
* @dataProvider uncaught_error_type_provider