From c0daa4abde0a34b3a2e5a0e5766b3ea6b1be6970 Mon Sep 17 00:00:00 2001 From: Tom Kay Date: Tue, 29 Sep 2026 10:21:38 +0100 Subject: [PATCH 1/2] Add Cubex\Encryption with XChaCha20-Poly1305 and key rotation EncrypterInterface (string in, string out) with an XChaCha20-Poly1305 implementation. Payloads are base64url of a version byte, a random 24 byte nonce and the ciphertext with tag; the version is bound as additional data. Cipher keys are derived with HKDF-SHA256 from configured keys of at least 16 bytes. Keys come from security.encryption_key, a key or a list: the first key encrypts, later keys only decrypt. An empty first entry throws instead of promoting an old key. Cubex registers a lazy EncrypterInterface factory reading the context config. Sodium is suggested (ext-sodium or paragonie/sodium_compat) and checked when an encrypter is constructed. Co-Authored-By: Claude Opus 5.5 --- composer.json | 4 +- src/Cubex.php | 3 + src/Encryption/DecryptException.php | 6 + src/Encryption/Encrypter.php | 151 +++++++++++++++++++ src/Encryption/EncrypterInterface.php | 16 ++ tests/Encryption/EncrypterTest.php | 206 ++++++++++++++++++++++++++ 6 files changed, 385 insertions(+), 1 deletion(-) create mode 100644 src/Encryption/DecryptException.php create mode 100644 src/Encryption/Encrypter.php create mode 100644 src/Encryption/EncrypterInterface.php create mode 100644 tests/Encryption/EncrypterTest.php diff --git a/composer.json b/composer.json index b40784f..4f11c24 100644 --- a/composer.json +++ b/composer.json @@ -36,7 +36,9 @@ "psr/log": "~1.1||^2.0||^3.0" }, "suggest": { - "ext-xdebug": "*" + "ext-xdebug": "*", + "ext-sodium": "Required to use Cubex\\Encryption", + "paragonie/sodium_compat": "Pure-PHP fallback when ext-sodium is unavailable" }, "require-dev": { "phpunit/phpunit": "^9", diff --git a/src/Cubex.php b/src/Cubex.php index dc26d28..d9978e0 100644 --- a/src/Cubex.php +++ b/src/Cubex.php @@ -8,6 +8,8 @@ use Cubex\Context\Context as CubexContext; use Cubex\Context\Events\ConsoleCreatedEvent; use Cubex\Context\Events\ConsoleLaunchedEvent; +use Cubex\Encryption\Encrypter; +use Cubex\Encryption\EncrypterInterface; use Cubex\Events\Handle\HandleCompleteEvent; use Cubex\Events\Handle\ResponsePreparedEvent; use Cubex\Events\Handle\ResponsePrepareEvent; @@ -65,6 +67,7 @@ public function __construct($projectRoot, ?ClassLoader $loader = null, $global = $this->share(ClassLoader::class, $loader); $this->share(DependencyInjector::class, $this); $this->factory(Context::class, $this->_defaultContextFactory()); + $this->factory(EncrypterInterface::class, fn() => Encrypter::fromConfig($this->getContext()->config())); if($global && self::$_cubex === null) { diff --git a/src/Encryption/DecryptException.php b/src/Encryption/DecryptException.php new file mode 100644 index 0000000..1e60ebc --- /dev/null +++ b/src/Encryption/DecryptException.php @@ -0,0 +1,6 @@ +_keys[] = hash_hkdf('sha256', $key, static::KEY_BYTES, static::KDF_INFO); + } + } + + /** + * Build from a key, or list of keys, in configuration, e.g. + * + * [security] + * encryption_key[] = + * encryption_key[] = + * + * @throws \InvalidArgumentException when no key is configured + */ + public static function fromConfig( + ConfigProviderInterface $config, string $section = 'security', string $item = 'encryption_key' + ): static + { + return new static($config->getItem($section, $item, '')); + } + + protected static function _sodiumAvailable(): bool + { + // paragonie/sodium_compat defines the same functions + return function_exists('sodium_crypto_aead_xchacha20poly1305_ietf_encrypt'); + } + + /** + * @param string|string[] $keys + * + * @return string[] the non-empty keys, current key first + * + * @throws \InvalidArgumentException when the current key is empty + */ + public static function normaliseKeys(string|array $keys): array + { + $keys = array_map('strval', is_array($keys) ? array_values($keys) : [$keys]); + + // An empty first entry is usually an unset environment variable. It is + // rejected rather than replaced by the next entry, which would encrypt + // new data with a key that is being retired. + if(!isset($keys[0]) || $keys[0] === '') + { + throw new \InvalidArgumentException('The first encryption key is the current key and must not be empty.'); + } + return array_values(array_filter($keys, 'strlen')); + } + + public function encrypt(string $plaintext): string + { + $nonce = random_bytes(static::NONCE_BYTES); + $ciphertext = sodium_crypto_aead_xchacha20poly1305_ietf_encrypt($plaintext, static::VERSION, $nonce, $this->_keys[0]); + return rtrim(strtr(base64_encode(static::VERSION . $nonce . $ciphertext), '+/', '-_'), '='); + } + + public function decrypt(string $payload): string + { + $binary = false; + if(strlen($payload) % 4 !== 1 && preg_match('/^[A-Za-z0-9_-]*$/', $payload)) + { + $binary = base64_decode(strtr($payload, '-_', '+/'), true); + } + if($binary === false) + { + throw new DecryptException('The payload is not valid base64url.'); + } + + $headerBytes = 1 + static::NONCE_BYTES; + if(strlen($binary) < $headerBytes + static::TAG_BYTES) + { + throw new DecryptException('The payload is too short.'); + } + $version = $binary[0]; + if($version !== static::VERSION) + { + throw new DecryptException('The payload version is not supported.'); + } + + $nonce = substr($binary, 1, static::NONCE_BYTES); + $ciphertext = substr($binary, $headerBytes); + foreach($this->_keys as $key) + { + $plaintext = sodium_crypto_aead_xchacha20poly1305_ietf_decrypt($ciphertext, $version, $nonce, $key); + if($plaintext !== false) + { + return $plaintext; + } + } + throw new DecryptException('The payload could not be decrypted with any configured key.'); + } +} diff --git a/src/Encryption/EncrypterInterface.php b/src/Encryption/EncrypterInterface.php new file mode 100644 index 0000000..4ae9202 --- /dev/null +++ b/src/Encryption/EncrypterInterface.php @@ -0,0 +1,16 @@ +assertInstanceOf(EncrypterInterface::class, $encrypter); + foreach(['', 'value', random_bytes(1000)] as $plaintext) + { + $this->assertSame($plaintext, $encrypter->decrypt($encrypter->encrypt($plaintext))); + } + } + + public function testPayloadFormat() + { + $payload = (new Encrypter(self::CURRENT))->encrypt('value'); + $this->assertMatchesRegularExpression('/^[A-Za-z0-9_-]+$/', $payload); + $binary = self::_decode($payload); + $this->assertSame(Encrypter::VERSION, $binary[0]); + $this->assertSame(1 + 24 + strlen('value') + 16, strlen($binary)); + // 45 plaintext bytes encrypt to 115 characters + $this->assertSame(115, strlen((new Encrypter(self::CURRENT))->encrypt(str_repeat('x', 45)))); + } + + public function testNonceIsRandom() + { + $encrypter = new Encrypter(self::CURRENT); + $this->assertNotSame($encrypter->encrypt('value'), $encrypter->encrypt('value')); + } + + public function testRotation() + { + $old = new Encrypter(self::OLDER); + $rotating = new Encrypter([self::CURRENT, '', self::OLDER]); + $this->assertSame('old', $rotating->decrypt($old->encrypt('old'))); + + $payload = $rotating->encrypt('new'); + $this->assertSame('new', (new Encrypter(self::CURRENT))->decrypt($payload)); + $this->expectException(DecryptException::class); + $old->decrypt($payload); + } + + public function testWrongKeyThrows() + { + $payload = (new Encrypter(self::OLDER))->encrypt('value'); + $this->expectException(DecryptException::class); + $this->expectExceptionMessage('any configured key'); + (new Encrypter(self::CURRENT))->decrypt($payload); + } + + public static function tamperProvider(): array + { + return [ + 'version' => [0], + 'nonce' => [5], + 'ciphertext' => [26], + 'tag' => [-1], + ]; + } + + /** + * @dataProvider tamperProvider + */ + public function testTamperingThrows(int $offset) + { + $encrypter = new Encrypter(self::CURRENT); + $binary = self::_decode($encrypter->encrypt('value')); + $offset = $offset < 0 ? strlen($binary) + $offset : $offset; + $binary[$offset] = chr(ord($binary[$offset]) ^ 1); + $this->expectException(DecryptException::class); + $encrypter->decrypt(self::_encode($binary)); + } + + public function testVersionIsAuthenticated() + { + $encrypter = new Encrypter(self::CURRENT); + $binary = self::_decode($encrypter->encrypt('value')); + $key = hash_hkdf('sha256', self::CURRENT, 32, Encrypter::KDF_INFO); + $nonce = substr($binary, 1, 24); + $forged = sodium_crypto_aead_xchacha20poly1305_ietf_encrypt('value', "\x02", $nonce, $key); + $this->expectException(DecryptException::class); + $encrypter->decrypt(self::_encode(Encrypter::VERSION . $nonce . $forged)); + } + + public static function malformedProvider(): array + { + return [ + 'not base64url' => ['not a payload!', 'base64url'], + 'padded' => ['AQ==', 'base64url'], + 'bad length' => ['AAAAA', 'base64url'], + 'too short' => [self::_encode("\x01short"), 'too short'], + 'bad version' => [self::_encode("\x02" . str_repeat('a', 60)), 'version'], + ]; + } + + /** + * @dataProvider malformedProvider + */ + public function testMalformedPayloadThrows(string $payload, string $message) + { + $this->expectException(DecryptException::class); + $this->expectExceptionMessage($message); + (new Encrypter(self::CURRENT))->decrypt($payload); + } + + public static function invalidKeyProvider(): array + { + return [ + 'empty string' => ['', 'must not be empty'], + 'empty list' => [[], 'must not be empty'], + 'empty first entry' => [['', self::OLDER], 'must not be empty'], + 'all empty' => [['', ''], 'must not be empty'], + 'short current key' => ['fifteen-bytes!!', 'at least 16 bytes'], + 'short previous key' => [[self::CURRENT, 'short'], 'at least 16 bytes'], + ]; + } + + /** + * @dataProvider invalidKeyProvider + */ + public function testInvalidKeysThrow($keys, string $message) + { + $this->expectException(\InvalidArgumentException::class); + $this->expectExceptionMessage($message); + new Encrypter($keys); + } + + public function testNormaliseKeys() + { + $this->assertSame([self::CURRENT], Encrypter::normaliseKeys(self::CURRENT)); + $this->assertSame( + [self::CURRENT, self::OLDER], + Encrypter::normaliseKeys(['x' => self::CURRENT, '', null, self::OLDER]) + ); + } + + public function testMissingSodiumThrows() + { + $this->expectException(\RuntimeException::class); + $this->expectExceptionMessage('ext-sodium or paragonie/sodium_compat'); + new NoSodiumEncrypter(self::CURRENT); + } + + public function testFromIniConfig() + { + $config = new IniConfigProvider(); + $config->loadString("[security]\nencryption_key[] = " . self::CURRENT . "\nencryption_key[] = " . self::OLDER . "\n"); + $encrypter = Encrypter::fromConfig($config); + $this->assertSame('v', (new Encrypter(self::CURRENT))->decrypt($encrypter->encrypt('v'))); + $this->assertSame('v', $encrypter->decrypt((new Encrypter(self::OLDER))->encrypt('v'))); + } + + public function testFromConfigWithoutKeyThrows() + { + $this->expectException(\InvalidArgumentException::class); + Encrypter::fromConfig(new ConfigProvider()); + } + + public function testCubexProvidesEncrypterLazily() + { + $cubex = new Cubex(dirname(__DIR__), null, false); + $cubex->getContext()->config()->addItem('security', 'encryption_key', self::CURRENT); + $encrypter = $cubex->retrieve(EncrypterInterface::class); + $this->assertInstanceOf(Encrypter::class, $encrypter); + $this->assertSame($encrypter, $cubex->retrieve(EncrypterInterface::class)); + $this->assertSame('v', (new Encrypter(self::CURRENT))->decrypt($encrypter->encrypt('v'))); + } + + public function testCubexWithoutKeyOnlyFailsOnRetrieve() + { + $cubex = new Cubex(dirname(__DIR__), null, false); + $this->expectException(\InvalidArgumentException::class); + $cubex->retrieve(EncrypterInterface::class); + } +} + +class NoSodiumEncrypter extends Encrypter +{ + protected static function _sodiumAvailable(): bool + { + return false; + } +} From b16511216700fe0a73e9319bc8354387974ba118 Mon Sep 17 00:00:00 2001 From: Tom Kay Date: Tue, 29 Sep 2026 10:25:01 +0100 Subject: [PATCH 2/2] Enable ext-sodium in CI for the encryption tests The Windows PHP builds from setup-php do not load sodium by default. Also move actions/checkout to its latest major, v7. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/unit-test.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/workflows/unit-test.yml b/.github/workflows/unit-test.yml index b240622..ae22ee2 100644 --- a/.github/workflows/unit-test.yml +++ b/.github/workflows/unit-test.yml @@ -17,10 +17,11 @@ jobs: runs-on: ${{matrix.os}} steps: - - uses: actions/checkout@v5 + - uses: actions/checkout@v7 - uses: shivammathur/setup-php@v2 with: php-version: ${{matrix.php}} + extensions: sodium coverage: xdebug tools: composer, phpunit - run: composer install -n --prefer-dist