robotstxt-telemetry/includes/class-robotstxt-telemetry-logger.php
2026-08-20 14:31:43 +00:00

448 lines
12 KiB
PHP

<?php
/**
* Request logger.
*
* @package RobotstxtTelemetry
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
if ( ! class_exists( 'Robotstxt_Telemetry_Logger' ) ) {
/**
* Class Robotstxt_Telemetry_Logger
*/
class Robotstxt_Telemetry_Logger {
/**
* Maximum JSON size to store.
*
* @var int
*/
private $max_json_bytes = 65535;
/**
* Maximum raw body size to store.
*
* @var int
*/
private $max_raw_body_bytes = 65535;
/**
* Maximum caller summary size.
*
* @var int
*/
private $max_caller_bytes = 16000;
/**
* Register hooks.
*
* @return void
*/
public function register() {
add_filter( 'http_request_args', array( $this, 'capture_request' ), 10, 2 );
}
/**
* Capture outbound request arguments.
*
* @param array<string,mixed> $args HTTP request arguments.
* @param string $url Request URL.
* @return array<string,mixed>
*/
public function capture_request( $args, $url ) {
if ( empty( $url ) ) {
return $args;
}
try {
Robotstxt_Telemetry_DB::maybe_upgrade();
$log_data = $this->prepare_log_data( $args, $url );
if ( ! empty( $log_data ) ) {
Robotstxt_Telemetry_DB::insert_log( $log_data );
}
} catch ( Exception $exception ) {
// Never interrupt outbound requests if logging fails.
do_action( 'robotstxt_telemetry_logging_failed', $exception, $args, $url );
}
return $args;
}
/**
* Prepare log data for storage.
*
* @param array<string,mixed> $args Request args.
* @param string $url Request URL.
* @return array<string,mixed>
*/
private function prepare_log_data( $args, $url ) {
$method = isset( $args['method'] ) && is_string( $args['method'] ) ? strtoupper( sanitize_text_field( $args['method'] ) ) : 'GET';
$url = esc_url_raw( $url );
$parsed_url = wp_parse_url( $url );
if ( ! is_array( $parsed_url ) ) {
$parsed_url = array();
}
$host = isset( $parsed_url['host'] ) ? sanitize_text_field( $parsed_url['host'] ) : '';
$path = isset( $parsed_url['path'] ) ? sanitize_text_field( $parsed_url['path'] ) : '';
$query_params = array();
if ( ! empty( $parsed_url['query'] ) ) {
$query_params = $this->normalize_keys( wp_parse_args( $parsed_url['query'] ) );
}
$query_params = $this->redact_array( $query_params );
// Rebuild the URL with redacted query parameters and without credentials.
if ( ! empty( $parsed_url['query'] ) || ! empty( $parsed_url['user'] ) ) {
$redacted_url = $this->build_redacted_url( $parsed_url, http_build_query( $query_params ) );
if ( '' !== $redacted_url ) {
$url = $redacted_url;
}
}
$query_json = $this->encode_json_limited( $query_params, $this->max_json_bytes );
if ( empty( $query_json ) && ! empty( $query_params ) ) {
$query_json = http_build_query( $query_params );
}
$body_json = null;
$raw_body = null;
if ( isset( $args['body'] ) ) {
$body_data = $args['body'];
if ( is_array( $body_data ) ) {
$redacted_body = $this->redact_array( $this->normalize_keys( $body_data ) );
$body_json = $this->encode_json_limited( $redacted_body, $this->max_json_bytes );
if ( empty( $body_json ) ) {
$body_json = http_build_query( $redacted_body );
$raw_body = $this->truncate_string(
http_build_query( $redacted_body ),
$this->max_raw_body_bytes
);
}
} elseif ( is_string( $body_data ) ) {
$parsed_body = $this->parse_body_string( $body_data );
if ( null !== $parsed_body ) {
$redacted_body = $this->redact_array( $parsed_body );
$body_json = $this->encode_json_limited( $redacted_body, $this->max_json_bytes );
if ( empty( $body_json ) ) {
$body_json = http_build_query( $redacted_body );
$raw_body = $this->truncate_string(
http_build_query( $redacted_body ),
$this->max_raw_body_bytes
);
}
} else {
$raw_body = $this->truncate_string( $body_data, $this->max_raw_body_bytes );
}
}
}
$headers_args = isset( $args['headers'] ) && is_array( $args['headers'] ) ? $args['headers'] : array();
$headers = $this->normalize_headers( $headers_args );
$headers = $this->redact_array( $headers );
$headers_json = $this->encode_json_limited( $headers, $this->max_json_bytes );
$user_agent = $this->extract_user_agent( $args );
// phpcs:ignore WordPress.PHP.DevelopmentFunctions -- Needed for caller context logging.
$caller = wp_debug_backtrace_summary( null, 0, false );
$caller = wp_json_encode( $caller );
$caller = $this->truncate_string( is_string( $caller ) ? $caller : '', $this->max_caller_bytes );
return array(
'created_at' => current_time( 'mysql', true ),
'method' => $method,
'url' => $url,
'host' => $host,
'path' => $path,
'query_json' => $query_json,
'body_json' => $body_json,
'headers_json' => $headers_json,
'user_agent' => $user_agent,
'raw_body' => $raw_body,
'caller' => $caller,
'redacted' => 1,
);
}
/**
* Rebuild a URL with a redacted query string and without credentials.
*
* @param array<string,mixed> $parts URL parts from wp_parse_url().
* @param string $query Redacted query string.
* @return string
*/
private function build_redacted_url( $parts, $query ) {
$scheme = isset( $parts['scheme'] ) && is_string( $parts['scheme'] ) ? $parts['scheme'] : '';
$host = isset( $parts['host'] ) && is_string( $parts['host'] ) ? $parts['host'] : '';
if ( '' === $scheme || '' === $host ) {
return '';
}
$url = $scheme . '://' . $host;
if ( isset( $parts['port'] ) && is_int( $parts['port'] ) ) {
$url .= ':' . $parts['port'];
}
$url .= isset( $parts['path'] ) && is_string( $parts['path'] ) ? $parts['path'] : '';
if ( '' !== $query ) {
$url .= '?' . $query;
}
if ( isset( $parts['fragment'] ) && is_string( $parts['fragment'] ) ) {
$url .= '#' . $parts['fragment'];
}
return $url;
}
/**
* Normalize request headers into a simple array.
*
* @param mixed $headers Headers value.
* @return array<string,mixed>
*/
private function normalize_headers( $headers ) {
if ( is_object( $headers ) && method_exists( $headers, 'getAll' ) ) {
$headers = $headers->getAll();
}
if ( ! is_array( $headers ) ) {
return array();
}
$normalized = array();
foreach ( $headers as $key => $value ) {
$sanitized_key = sanitize_text_field( (string) $key );
$normalized[ $sanitized_key ] = $this->normalize_value( $value );
}
return $normalized;
}
/**
* Extract the user agent from request args.
*
* @param array<string,mixed> $args Request args.
* @return string|null
*/
private function extract_user_agent( $args ) {
$user_agent = '';
if ( isset( $args['user-agent'] ) && is_string( $args['user-agent'] ) ) {
$user_agent = $args['user-agent'];
} elseif ( isset( $args['user_agent'] ) && is_string( $args['user_agent'] ) ) {
$user_agent = $args['user_agent'];
} elseif ( isset( $args['headers'] ) && is_array( $args['headers'] ) ) {
$headers = $args['headers'];
if ( isset( $headers['user-agent'] ) && is_string( $headers['user-agent'] ) ) {
$user_agent = $headers['user-agent'];
} elseif ( isset( $headers['User-Agent'] ) && is_string( $headers['User-Agent'] ) ) {
$user_agent = $headers['User-Agent'];
}
}
if ( '' === $user_agent ) {
return null;
}
return sanitize_text_field( $this->truncate_string( $user_agent, 512 ) );
}
/**
* Parse body strings into arrays when possible.
*
* @param string $body Raw body.
* @return array<int|string,mixed>|null
*/
private function parse_body_string( $body ) {
$decoded = json_decode( $body, true );
if ( is_array( $decoded ) ) {
return $this->normalize_keys( $decoded );
}
$parsed = wp_parse_args( $body );
if ( ! empty( $parsed ) ) {
return $this->normalize_keys( $parsed );
}
return null;
}
/**
* Normalize an array to integer or string keys.
*
* @param array<mixed,mixed> $data Input array.
* @return array<int|string,mixed>
*/
private function normalize_keys( array $data ) {
$normalized = array();
foreach ( $data as $key => $value ) {
$normalized[ $key ] = $value;
}
return $normalized;
}
/**
* Redact sensitive keys in arrays.
*
* @param array<int|string,mixed> $data Data to sanitize.
* @return array<int|string,mixed>
*/
private function redact_array( $data ) {
$redacted = array();
foreach ( $data as $key => $value ) {
$normalized_key = strtolower( (string) $key );
if ( $this->is_sensitive_key( $normalized_key ) ) {
$redacted[ $key ] = '[redacted]';
continue;
}
if ( is_array( $value ) ) {
$redacted[ $key ] = $this->redact_array( $value );
continue;
}
$redacted[ $key ] = $this->normalize_value( $value );
}
return $redacted;
}
/**
* Check if a key should be redacted.
*
* @param string $key Key name.
* @return bool
*/
private function is_sensitive_key( $key ) {
$sensitive_keys = array(
'authorization',
'password',
'pass',
'token',
'secret',
'api_key',
'api-key',
'apikey',
'nonce',
'cookie',
'session',
'private-key',
'private_key',
);
foreach ( $sensitive_keys as $sensitive_key ) {
if ( false !== strpos( $key, $sensitive_key ) ) {
return true;
}
}
return false;
}
/**
* Normalize values to safe strings or scalars.
*
* @param mixed $value Value to normalize.
* @return mixed
*/
private function normalize_value( $value ) {
if ( is_scalar( $value ) || null === $value ) {
if ( is_string( $value ) ) {
return sanitize_text_field( $value );
}
return $value;
}
$encoded = wp_json_encode( $value );
return false === $encoded ? '' : sanitize_text_field( $encoded );
}
/**
* Encode JSON with size limits.
*
* @param array<int|string,mixed> $data Data to encode.
* @param int $limit Max size in bytes.
* @return string|null
*/
private function encode_json_limited( $data, $limit ) {
$encoded = wp_json_encode( $this->truncate_array_values( $data, 2048 ) );
if ( false === $encoded ) {
return null;
}
if ( strlen( $encoded ) > $limit ) {
return $this->truncate_string( $encoded, $limit );
}
return $encoded;
}
/**
* Truncate array values to keep payloads manageable.
*
* @param array<int|string,mixed> $data Data to trim.
* @param int $max_len Max length per string value.
* @return array<int|string,mixed>
*/
private function truncate_array_values( $data, $max_len ) {
$trimmed = array();
foreach ( $data as $key => $value ) {
if ( is_array( $value ) ) {
$trimmed[ $key ] = $this->truncate_array_values( $value, $max_len );
continue;
}
if ( is_string( $value ) ) {
$trimmed[ $key ] = $this->truncate_string( $value, $max_len );
continue;
}
$trimmed[ $key ] = $value;
}
return $trimmed;
}
/**
* Truncate a string safely.
*
* @param string $value String to truncate.
* @param int $limit Max length in bytes.
* @return string
*/
private function truncate_string( $value, $limit ) {
if ( strlen( $value ) > $limit ) {
$value = substr( $value, 0, $limit );
}
// wp_check_invalid_utf8() requires WordPress 4.2.3.
if ( function_exists( 'wp_check_invalid_utf8' ) ) {
return wp_check_invalid_utf8( $value, true );
}
return $value;
}
}
}