Skip to content

Commit

Permalink
Merge pull request #5941 from ampproject/fix/server-timing-header-values
Browse files Browse the repository at this point in the history
Sanitize keys in Server-Timing instead of adding slashes for escaping
  • Loading branch information
westonruter committed Mar 4, 2021
2 parents 1a1ad95 + db0ddd2 commit 6bf5dd4
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 4 deletions.
16 changes: 13 additions & 3 deletions src/Instrumentation/Event.php
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,16 @@ public function add_properties( $properties ) {
}
}

/**
* Sanitize key to use it for an HTTP header label (alphanumeric and dashes/underscores only).
*
* @param string $key Unsanitized key.
* @return string Sanitized key.
*/
private function sanitize_key( $key ) {
return preg_replace( '/[^a-zA-Z0-9_-]+/', '_', $key );
}

/**
* Get the server timing header string.
*
Expand All @@ -108,19 +118,19 @@ public function get_header_string() {
if ( is_float( $value ) ) {
$property_strings[] = sprintf(
';%s="%.1f"',
addslashes( $property ),
$this->sanitize_key( $property ),
$value
);
} else {
$property_strings[] = sprintf(
';%s="%s"',
addslashes( $property ),
$this->sanitize_key( $property ),
addslashes( $value )
);
}
}

$event_string = addslashes( $this->get_name() );
$event_string = $this->sanitize_key( $this->get_name() );

$description = $this->get_description();
if ( ! empty( $description ) ) {
Expand Down
2 changes: 1 addition & 1 deletion src/Instrumentation/ServerTiming.php
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,7 @@ public function get_header_string() {
return implode(
',',
array_map(
static function ( $event ) {
static function ( Event $event ) {
return $event->get_header_string();
},
$this->events
Expand Down

0 comments on commit 6bf5dd4

Please sign in to comment.