Skip to content

Commit

Permalink
Gracefully handle encryption errors in session
Browse files Browse the repository at this point in the history
  • Loading branch information
joelambert committed Oct 4, 2023
1 parent cf7b261 commit c0aa520
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 3 deletions.
15 changes: 12 additions & 3 deletions src/Session/EncryptedStore.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,20 @@

namespace Rareloop\Lumberjack\Session;

use Rareloop\Lumberjack\Encrypter;
use Exception;
use SessionHandlerInterface;
use Rareloop\Lumberjack\Encrypter;
use Rareloop\Lumberjack\Exceptions\HandlerInterface;

class EncryptedStore extends Store
{
protected $encrypter;
protected $exceptionHandler;

public function __construct($name, SessionHandlerInterface $handler, Encrypter $encrypter, $id = null)
public function __construct($name, SessionHandlerInterface $handler, Encrypter $encrypter, $id = null, HandlerInterface $exceptionHandler = null)
{
$this->encrypter = $encrypter;
$this->exceptionHandler = $exceptionHandler;

parent::__construct($name, $handler, $id);
}
Expand All @@ -23,6 +27,11 @@ protected function prepareForStorage($data)

protected function prepareForUnserialize($data)
{
return $this->encrypter->decrypt($data);
try {
return $this->encrypter->decrypt($data);
} catch (Exception $e) {
$this->exceptionHandler->report($e);
return null;
}
}
}
30 changes: 30 additions & 0 deletions tests/Unit/Session/EncryptedStoreTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
use Mockery;
use PHPUnit\Framework\TestCase;
use Rareloop\Lumberjack\Encrypter;
use Rareloop\Lumberjack\Exceptions\HandlerInterface;
use Rareloop\Lumberjack\Session\EncryptedStore;
use Rareloop\Lumberjack\Session\Store;
use Rareloop\Lumberjack\Test\Unit\Session\NullSessionHandler;
Expand Down Expand Up @@ -50,4 +51,33 @@ public function data_is_decrypted_before_it_is_loaded()

$this->assertSame('bar', $store->get('foo'));
}

/**
* @test
* @dataProvider unexpectedSessionData
*/
public function unexpected_session_data_is_handled_gracefully($previousSessionValue)
{
$encryptionKey = 'encryption-key';

// Use a mock handler to fake a previously stored state
$handler = Mockery::mock(NullSessionHandler::class . '[read]');
$handler->shouldReceive('read')->andReturn($previousSessionValue);

$errorHandler = Mockery::mock(HandlerInterface::class);
$errorHandler->shouldReceive('report')->once();

$store = new EncryptedStore('session-name', $handler, new Encrypter($encryptionKey), 'session-id', $errorHandler);
$store->start();

$this->assertSame(null, $store->get('foo'));
}

private function unexpectedSessionData()
{
return [
[@serialize(['foo' => 'bar'])],
[''],
];
}
}

0 comments on commit c0aa520

Please sign in to comment.