Skip to content

Commit

Permalink
implement an sslContext class which can be used for passing the sslCo…
Browse files Browse the repository at this point in the history
…ntext to the RedisCluster

Signed-off-by: robin-brabants <[email protected]>
Co-authored-by: robin-brabants <[email protected]>
Signed-off-by: Maximilian Bösing <[email protected]>
  • Loading branch information
boesing and robin-brabants committed Apr 10, 2024
1 parent 468a6b5 commit a195a52
Show file tree
Hide file tree
Showing 5 changed files with 322 additions and 13 deletions.
19 changes: 13 additions & 6 deletions src/RedisClusterOptions.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
use Laminas\Cache\Exception\RuntimeException;
use Laminas\Cache\Storage\Adapter\Exception\InvalidRedisClusterConfigurationException;

use function is_array;

final class RedisClusterOptions extends AdapterOptions
{
public const LIBRARY_OPTIONS = [
Expand Down Expand Up @@ -53,8 +55,8 @@ final class RedisClusterOptions extends AdapterOptions

private string $password = '';

/** @psalm-var array<non-empty-string,mixed>|null */
private ?array $sslContext = null;
/** @psalm-var SslContext|null */
private ?SslContext $sslContext = null;

/**
* @param iterable|null|AdapterOptions $options
Expand Down Expand Up @@ -227,18 +229,23 @@ public function setPassword(string $password): void
}

/**
* @psalm-return array<non-empty-string,mixed>|null
* @psalm-return SslContext|null
*/
public function getSslContext(): ?array
public function getSslContext(): ?SslContext
{
return $this->sslContext;
}

/**
* @psalm-param array<non-empty-string,mixed>|null $sslContext
* @psalm-param array<non-empty-string,mixed>|SslContext|null $sslContext
*/
public function setSslContext(?array $sslContext): void
public function setSslContext(array|SslContext|null $sslContext): void
{
if (is_array($sslContext)) {
$data = $sslContext;
$sslContext = new SslContext();
$sslContext->exchangeArray($data);
}
$this->sslContext = $sslContext;
}
}
6 changes: 3 additions & 3 deletions src/RedisClusterResourceManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ private function createRedisResource(RedisClusterOptions $options): RedisCluster
$options->getReadTimeout(),
$options->isPersistent(),
$password,
$options->getSslContext()
$options->getSslContext()?->getArrayCopy()
);
}

Expand All @@ -111,7 +111,7 @@ private function createRedisResourceFromName(
float $fallbackReadTimeout,
bool $persistent,
string $fallbackPassword,
?array $sslContext
?SslContext $sslContext
): RedisClusterFromExtension {
$options = new RedisClusterOptionsFromIni();
$seeds = $options->getSeeds($name);
Expand All @@ -126,7 +126,7 @@ private function createRedisResourceFromName(
$readTimeout,
$persistent,
$password,
$sslContext
$sslContext?->getArrayCopy()
);
}

Expand Down
200 changes: 200 additions & 0 deletions src/SslContext.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,200 @@
<?php

declare(strict_types=1);

namespace Laminas\Cache\Storage\Adapter;

use InvalidArgumentException;
use Laminas\Stdlib\ArraySerializableInterface;
use Symfony\Component\Serializer\NameConverter\CamelCaseToSnakeCaseNameConverter;

use function boolval;
use function get_object_vars;
use function property_exists;
use function sprintf;

use const OPENSSL_DEFAULT_STREAM_CIPHERS;
use const OPENSSL_TLSEXT_SERVER_NAME;

/**
* Class containing the SSL context options in its fields.
*
* @link https://www.php.net/manual/en/context.ssl.php
*/
final class SslContext implements ArraySerializableInterface
{
/**
* Peer name to be used.
* If this value is not set, then the name is guessed based on the hostname used when opening the stream.
*/
private ?string $peerName;

/**
* Require verification of SSL certificate used.
*/
private bool $verifyPeer;

/**
* Require verification of peer name.
*/
private bool $verifyPeerName;

/**
* Allow self-signed certificates. Requires verifyPeer.
*/
private bool $allowSelfSigned;

/**
* Location of Certificate Authority file on local filesystem which should be used with the verifyPeer
* context option to authenticate the identity of the remote peer.
*/
private ?string $cafile;

/**
* If cafile is not specified or if the certificate is not found there, the directory pointed to by capath is
* searched for a suitable certificate. capath must be a correctly hashed certificate directory.
*/
private ?string $capath;

/**
* Path to local certificate file on filesystem. It must be a PEM encoded file which contains your certificate and
* private key. It can optionally contain the certificate chain of issuers.
* The private key also may be contained in a separate file specified by localPk.
*/
private ?string $localCert;

/**
* Path to local private key file on filesystem in case of separate files for certificate (localCert)
* and private key.
*/
private ?string $localPk;

/**
* Passphrase with which your localCert file was encoded.
*/
private ?string $passphrase;

/**
* Abort if the certificate chain is too deep.
* If not set, defaults to no verification.
*/
private ?int $verifyDepth;

/**
* Sets the list of available ciphers. The format of the string is described in
* https://www.openssl.org/docs/manmaster/man1/ciphers.html#CIPHER-LIST-FORMAT
*/
private string $ciphers;

/**
* If set to true server name indication will be enabled. Enabling SNI allows multiple certificates on the same
* IP address.
* If not set, will automatically be enabled if SNI support is available.
*/
private ?bool $sniEnabled;

/**
* If set, disable TLS compression. This can help mitigate the CRIME attack vector.
*/
private bool $disableCompression;

/**
* Aborts when the remote certificate digest doesn't match the specified hash.
*
* When a string is used, the length will determine which hashing algorithm is applied,
* either "md5" (32) or "sha1" (40).
*
* When an array is used, the keys indicate the hashing algorithm name and each corresponding
* value is the expected digest.
*/
private string|array|null $peerFingerprint;

/**
* Sets the security level. If not specified the library default security level is used. The security levels are
* described in https://www.openssl.org/docs/man1.1.1/man3/SSL_CTX_get_security_level.html.
*/
private ?int $securityLevel;

public function __construct(
?string $peerName = null,
bool $verifyPeer = true,
bool $verifyPeerName = true,
bool $allowSelfSigned = false,
?string $cafile = null,
?string $capath = null,
?string $localCert = null,
?string $localPk = null,
?string $passphrase = null,
?int $verifyDepth = null,
string $ciphers = OPENSSL_DEFAULT_STREAM_CIPHERS,
?bool $sniEnabled = null,
bool $disableCompression = true,
array|string|null $peerFingerprint = null,
?int $securityLevel = null
) {
$this->peerName = $peerName;
$this->verifyPeer = $verifyPeer;
$this->verifyPeerName = $verifyPeerName;
$this->allowSelfSigned = $allowSelfSigned;
$this->cafile = $cafile;
$this->capath = $capath;
$this->localCert = $localCert;
$this->localPk = $localPk;
$this->passphrase = $passphrase;
$this->verifyDepth = $verifyDepth;
$this->ciphers = $ciphers;
$this->sniEnabled = $sniEnabled;
$this->disableCompression = $disableCompression;
$this->peerFingerprint = $peerFingerprint;
$this->securityLevel = $securityLevel;
if ($sniEnabled === null) {
$this->sniEnabled = boolval(OPENSSL_TLSEXT_SERVER_NAME);
}
}

public function exchangeArray(array $array): void
{
foreach ($array as $key => $value) {
$property = $this->mapArrayKeyToPropertyName($key);
if (! property_exists($this, $property)) {
throw new InvalidArgumentException(
sprintf(
'%s does not contain the property "%s" corresponding to the array key "%s"',
self::class,
$property,
$key
)
);
}
$this->$property = $value;
}
}

public function getArrayCopy(): array
{
$array = [];
foreach (get_object_vars($this) as $property => $value) {
if ($value !== null) {
$key = $this->mapPropertyNameToArrayKey($property);
$array[$key] = $value;
}
}
return $array;
}

private function mapArrayKeyToPropertyName(string $key): string
{
if ($key === 'SNI_enabled') {
return 'sniEnabled';
}
return (new CamelCaseToSnakeCaseNameConverter())->denormalize($key);
}

private function mapPropertyNameToArrayKey(string $property): string
{
if ($property === 'sniEnabled') {
return 'SNI_enabled';
}
return (new CamelCaseToSnakeCaseNameConverter())->normalize($property);
}
}
27 changes: 23 additions & 4 deletions test/unit/RedisClusterOptionsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
use Laminas\Cache\Storage\Adapter\AdapterOptions;
use Laminas\Cache\Storage\Adapter\Exception\InvalidRedisClusterConfigurationException;
use Laminas\Cache\Storage\Adapter\RedisClusterOptions;
use Laminas\Cache\Storage\Adapter\SslContext;
use Redis as RedisFromExtension;
use ReflectionClass;

Expand All @@ -29,6 +30,28 @@ protected function createAdapterOptions(): AdapterOptions
return new RedisClusterOptions(['seeds' => ['localhost']]);
}

public function testCanHandleOptionsWithSslContextObject(): void
{
$options = new RedisClusterOptions([
'name' => 'foo',
'ssl_context' => new SslContext(localCert: '/path/to/localcert'),
]);

$this->assertEquals('foo', $options->getName());
$this->assertEquals(new SslContext(localCert: '/path/to/localcert'), $options->getSslContext());
}

public function testCanHandleOptionsWithSslContextArray(): void
{
$options = new RedisClusterOptions([
'name' => 'foo',
'ssl_context' => ['local_cert' => '/path/to/localcert'],
]);

$this->assertEquals('foo', $options->getName());
$this->assertEquals(new SslContext(localCert: '/path/to/localcert'), $options->getSslContext());
}

public function testCanHandleOptionsWithNodename(): void
{
$options = new RedisClusterOptions([
Expand All @@ -38,7 +61,6 @@ public function testCanHandleOptionsWithNodename(): void
'persistent' => false,
'redis_version' => '1.0',
'password' => 'secret',
'ssl_context' => ['verify_peer' => false],
]);

$this->assertEquals('foo', $options->getName());
Expand All @@ -47,7 +69,6 @@ public function testCanHandleOptionsWithNodename(): void
$this->assertEquals(false, $options->isPersistent());
$this->assertEquals('1.0', $options->getRedisVersion());
$this->assertEquals('secret', $options->getPassword());
$this->assertEquals(['verify_peer' => false], $options->getSslContext());
}

public function testCanHandleOptionsWithSeeds(): void
Expand All @@ -59,7 +80,6 @@ public function testCanHandleOptionsWithSeeds(): void
'persistent' => false,
'redis_version' => '1.0',
'password' => 'secret',
'ssl_context' => ['verify_peer' => false],
]);

$this->assertEquals(['localhost:1234'], $options->getSeeds());
Expand All @@ -68,7 +88,6 @@ public function testCanHandleOptionsWithSeeds(): void
$this->assertEquals(false, $options->isPersistent());
$this->assertEquals('1.0', $options->getRedisVersion());
$this->assertEquals('secret', $options->getPassword());
$this->assertEquals(['verify_peer' => false], $options->getSslContext());
}

public function testWillDetectSeedsAndNodenameConfiguration(): void
Expand Down
Loading

0 comments on commit a195a52

Please sign in to comment.