Skip to content

Commit

Permalink
fix: allow numeric header names
Browse files Browse the repository at this point in the history
RFC 7230 allows for numeric header names, both integers and floats, though the expectation is that they are provided as string values.
Since PHP casts integer strings into integers for purposes of array keys, this can lead to a scenario where `HeaderSecurity` was then flagging the value as invalid - despite the fact that the regex used on strings clearly allows the value.
This patch modifies `HeaderSecurity::assertValidName()` to allow for numeric names, and casts them to a string when performing validations.

Fixes laminas#11

Signed-off-by: Matthew Weier O'Phinney <[email protected]>
  • Loading branch information
weierophinney committed May 2, 2023
1 parent 9b7432e commit f1c6449
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 4 deletions.
8 changes: 4 additions & 4 deletions src/HeaderSecurity.php
Original file line number Diff line number Diff line change
Expand Up @@ -148,16 +148,16 @@ public static function assertValid(mixed $value): void
*/
public static function assertValidName(mixed $name): void
{
if (! is_string($name)) {
if (! is_string($name) && ! is_numeric($name)) {
throw new Exception\InvalidArgumentException(sprintf(
'Invalid header name type; expected string; received %s',
'Invalid header name type; expected string or numeric value; received %s',
is_object($name) ? $name::class : gettype($name)
));
}
if (! preg_match('/^[a-zA-Z0-9\'`#$%&*+.^_|~!-]+$/D', $name)) {
if (! preg_match('/^[a-zA-Z0-9\'`#$%&*+.^_|~!-]+$/D', (string) $name)) {
throw new Exception\InvalidArgumentException(sprintf(
'"%s" is not valid header name',
$name
(string) $name
));
}
}
Expand Down
17 changes: 17 additions & 0 deletions test/HeaderSecurityTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -130,4 +130,21 @@ public function testAssertValidNameRaisesExceptionForInvalidName(string $value):

HeaderSecurity::assertValidName($value);
}

/** @psalm-return non-empty-array<non-empty-string, array{0: int|float}> */
public function provideValidNumericHeaderNameValues(): array
{
return [
'zero' => [0],
'int' => [1],
'zero-float' => [0.0],
'float' => [1.1],
];
}

/** @dataProvider provideValidNumericHeaderNameValues */
public function testAssertValidNameDoesNotRaiseExceptionForValidNumericValues(int|float $value): void
{
$this->assertNull(HeaderSecurity::assertValidName($value));
}
}

0 comments on commit f1c6449

Please sign in to comment.