|
|
|
|
<?php
|
|
|
|
|
namespace App\Services {
|
|
|
|
|
final class Config {
|
|
|
|
|
public static string $key = '';
|
|
|
|
|
public static function get($name, $default = null) { return $name === 'cloud_data_key' ? self::$key : $default; }
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
namespace {
|
|
|
|
|
require dirname(__DIR__) . '/vendor/autoload.php';
|
|
|
|
|
if (!function_exists('sodium_crypto_aead_xchacha20poly1305_ietf_encrypt')) {
|
|
|
|
|
echo "SKIPPED CloudSecretsTest: runtime lacks sodium; production requires sodium.\n";
|
|
|
|
|
exit(0);
|
|
|
|
|
}
|
|
|
|
|
use App\Services\Config;
|
|
|
|
|
use App\Services\Cloud\CloudSecrets;
|
|
|
|
|
use App\Services\Cloud\CloudError;
|
|
|
|
|
Config::$key = base64_encode(str_repeat('k', 32));
|
|
|
|
|
$value = ['password' => 'test-fixture-password'];
|
|
|
|
|
$first = CloudSecrets::encrypt($value, 'test-record');
|
|
|
|
|
$second = CloudSecrets::encrypt($value, 'test-record');
|
|
|
|
|
if ($first === $second || !str_starts_with($first, 'v1.xc20p.')
|
|
|
|
|
|| str_contains($first, $value['password'])
|
|
|
|
|
|| CloudSecrets::decrypt($first, 'test-record') !== $value) {
|
|
|
|
|
throw new RuntimeException('Encryption, random nonce or roundtrip failed.');
|
|
|
|
|
}
|
|
|
|
|
$prefix = 'v1.xc20p.';
|
|
|
|
|
$encoded = substr($first, strlen($prefix));
|
|
|
|
|
$raw = base64_decode(strtr($encoded, '-_', '+/')
|
|
|
|
|
. str_repeat('=', (4 - strlen($encoded) % 4) % 4), true);
|
|
|
|
|
$raw[strlen($raw) - 1] = chr(ord($raw[strlen($raw) - 1]) ^ 1);
|
|
|
|
|
$tampered = $prefix . rtrim(strtr(base64_encode($raw), '+/', '-_'), '=');
|
|
|
|
|
try { CloudSecrets::decrypt($tampered, 'test-record'); throw new RuntimeException('Tampered ciphertext accepted.'); } catch (CloudError $expected) {}
|
|
|
|
|
try { CloudSecrets::decrypt($first, 'another-purpose'); throw new RuntimeException('Cross-purpose ciphertext accepted.'); } catch (CloudError $expected) {}
|
|
|
|
|
try { CloudSecrets::decrypt(base64_encode('retired'), 'test-record'); throw new RuntimeException('Retired ciphertext format accepted.'); } catch (CloudError $expected) {}
|
|
|
|
|
Config::$key = base64_encode(str_repeat('x', 32));
|
|
|
|
|
try { CloudSecrets::decrypt($first, 'test-record'); throw new RuntimeException('Wrong key accepted.'); } catch (CloudError $expected) {}
|
|
|
|
|
echo "Cloud XChaCha20 nonce, purpose binding, authentication and key isolation passed.\n";
|
|
|
|
|
}
|