terrylinooo / psr-http

PSR-7, 15, 17 implementation.
MIT License
19 stars 1 forks source link

Response reason-phrase validation #2

Open bkdotcom opened 3 years ago

bkdotcom commented 3 years ago

https://github.com/terrylinooo/psr-http/blob/master/src/Psr7/Response.php#L257-L262

I don't think this does what it's intended to do.

$escapeChars = [
    '\f', '\r', '\n', '\t', '\v', '\0', '[\b]',
    '\s', '\S', '\w', '\W', '\d', '\D', '\b', '\B', '\cX', '\xhh', '\uhhhh',
];
$filteredPhrase = \str_replace($escapeChars, '', $phrase);

The code is testing/replacing those string literals / not the characters they represent. (preg_replace is being confused with str_replace?)

The test case is also invalid https://github.com/terrylinooo/psr-http/blob/master/tests/Psr7/ResponseTest.php#L77 '\n` and '\r' are in the test string... not "\n" and "\r"

Here's an example of a phrase that should not be allowed:

 $response = new \Shieldon\Psr7\Response();
 $response->withStatus(200, "This reason is invalid\r\nIt should not be allowed");  // this should throw an exception.  It does not

that said, here's how the reason-phrase is defined: https://datatracker.ietf.org/doc/html/rfc7230#section-3.1.2

reason-phrase = *( HTAB / SP / VCHAR / obs-text )

bkdotcom commented 3 years ago

perhaps simply:

        if (\preg_match('/[^\P{C}\t]/u', $phrase, $matches, PREG_OFFSET_CAPTURE) === 1) {
            throw new InvalidArgumentException(\sprintf(
                'Reason phrase contains a prohibited character at position %s.',
                $matches[0][1]
            ));
        }

Which will match any control character except for HTAB ("\t")