Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions packages/http/src/Session/InvalidSessionId.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<?php

declare(strict_types=1);

namespace Tempest\Http\Session;

use Exception;

final class InvalidSessionId extends Exception
{
public function __construct(string $id)
{
parent::__construct(
sprintf('The session identifier `%s` is not a valid session id.', $id),
);
}
}
12 changes: 11 additions & 1 deletion packages/http/src/Session/SessionId.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,19 @@
*/
final readonly class SessionId implements Stringable
{
/**
* Restricts session IDs to safe characters to prevent path traversal
* when used as filenames (e.g., by {@see Managers\FileSessionManager}).
*/
private const string PATTERN = '/^[A-Za-z0-9_-]{1,128}\z/';

public function __construct(
private string $id,
) {}
) {
if (preg_match(self::PATTERN, $id) !== 1) {
throw new InvalidSessionId($id);
}
}

public function __toString(): string
{
Expand Down
50 changes: 50 additions & 0 deletions packages/http/tests/Session/SessionIdTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
<?php

declare(strict_types=1);

namespace Tempest\Http\Tests\Session;

use PHPUnit\Framework\Attributes\Test;
use PHPUnit\Framework\Attributes\TestWith;
use PHPUnit\Framework\TestCase;
use Tempest\Http\Session\InvalidSessionId;
use Tempest\Http\Session\SessionId;

/**
* @internal
*/
final class SessionIdTest extends TestCase
{
#[Test]
#[TestWith(['0197c5f0-8b3a-7c2e-9d1f-2a3b4c5d6e7f'])] // UUID (cookie/header resolver)
#[TestWith(['test-session'])]
#[TestWith(['abcDEF_123-456'])]
public function accepts_valid_identifiers(string $id): void
{
$this->assertSame($id, (string) new SessionId($id));
}

#[Test]
#[TestWith(['../../../../etc/passwd'])]
#[TestWith(['../../tmp/marker'])]
#[TestWith(['foo/bar'])]
#[TestWith(['with space'])]
#[TestWith(['with.dot'])]
#[TestWith(["null\0byte"])]
#[TestWith(["trailing-newline\n"])]
#[TestWith([''])]
public function rejects_traversal_and_unsafe_identifiers(string $id): void
{
$this->expectException(InvalidSessionId::class);

new SessionId($id);
}

#[Test]
public function rejects_overly_long_identifiers(): void
{
$this->expectException(InvalidSessionId::class);

new SessionId(str_repeat('a', 129));
}
}
Loading