Skip to content
This repository has been archived by the owner on Jun 29, 2022. It is now read-only.

Commit

Permalink
Fix #250: Automatically encode cookie value
Browse files Browse the repository at this point in the history
  • Loading branch information
samdark authored and devanych committed Feb 1, 2021
1 parent a422c6f commit 9fcc62d
Show file tree
Hide file tree
Showing 2 changed files with 4 additions and 21 deletions.
19 changes: 1 addition & 18 deletions src/Cookie.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,13 +33,6 @@ final class Cookie
*/
private const PATTERN_TOKEN = '/^[a-zA-Z0-9!#$%&\' * +\- .^_`|~]+$/';

/**
* Regular expression used to validate cooke value
* @link https://tools.ietf.org/html/rfc6265#section-4.1.1
* @link https://tools.ietf.org/html/rfc2616#section-2.2
*/
private const PATTERN_OCTET='/^[\x21\x23-\x2B\x2D-\x3A\x3C-\x5B\x5D-\x7E]*$/';

/**
* SameSite policy `Lax` will prevent the cookie from being sent by the browser in all cross-site browsing contexts
* during CSRF-prone request methods (e.g. POST, PUT, PATCH etc).
Expand Down Expand Up @@ -75,11 +68,6 @@ final class Cookie

/**
* @var string value of the cookie.
* A cookie value can include any US-ASCII characters excluding control characters, whitespaces,
* double quotes, comma, semicolon, and backslash.
* If you wish to store arbitrary data in a value, you should encode that data.
* Value will be decoded when parsed from response.
* @see urlencode()
*/
private string $value;

Expand Down Expand Up @@ -200,11 +188,6 @@ public function getValue(): string

private function setValue(string $value): void
{
// @link https://tools.ietf.org/html/rfc6265#section-4.1.1
if (!preg_match(self::PATTERN_OCTET, $value)) {
throw new InvalidArgumentException("The cookie value \"$value\" contains invalid characters.");
}

$this->value = $value;
}

Expand Down Expand Up @@ -451,7 +434,7 @@ public function addToResponse(ResponseInterface $response): ResponseInterface
public function __toString(): string
{
$cookieParts = [
$this->name . '=' . $this->value
$this->name . '=' . urlencode($this->value)
];

if ($this->expires !== null) {
Expand Down
6 changes: 3 additions & 3 deletions tests/CookieTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,10 +34,10 @@ public function testWithValue(): void
$this->assertSame('test=42; Path=/; Secure; HttpOnly; SameSite=Lax', $this->getCookieHeader($cookie));
}

public function testInvalidValue(): void
public function testValueThatIsEncoded(): void
{
$this->expectException(\InvalidArgumentException::class);
(new Cookie('test'))->withValue(';');
$cookieString = (string)(new Cookie('test'))->withValue(';');
$this->assertSame('test=%3B; Path=/; Secure; HttpOnly; SameSite=Lax', $cookieString);
}

public function testWithExpires(): void
Expand Down

0 comments on commit 9fcc62d

Please sign in to comment.