CaiWuXiTong/tests/Unit/Utilities/UpstreamCredentialCipherTest.php

74 lines
2.5 KiB
PHP

<?php
namespace Tests\Unit\Utilities;
use App\Utilities\UpstreamCredentialCipher;
use Illuminate\Contracts\Encryption\DecryptException;
use Illuminate\Encryption\Encrypter;
use Tests\TestCase;
class UpstreamCredentialCipherTest extends TestCase
{
protected function setUp(): void
{
parent::setUp();
$connection = (string) config('database.default');
config(["database.connections.$connection.password" => 'shared-system-database-secret']);
}
public function test_shared_credential_does_not_depend_on_app_key(): void
{
$cipher = app(UpstreamCredentialCipher::class);
$encrypted = $cipher->encrypt('cloud-readonly-secret');
$originalEncrypter = app('encrypter');
try {
app()->instance(
'encrypter',
new Encrypter(str_repeat('x', 32), (string) config('app.cipher'))
);
$this->assertSame('cloud-readonly-secret', $cipher->decrypt($encrypted));
} finally {
app()->instance('encrypter', $originalEncrypter);
}
}
public function test_different_system_database_password_cannot_decrypt_credential(): void
{
$cipher = app(UpstreamCredentialCipher::class);
$encrypted = $cipher->encrypt('cloud-readonly-secret');
$connection = (string) config('database.default');
config(["database.connections.$connection.password" => 'different-system-database-secret']);
$this->expectException(DecryptException::class);
$cipher->decrypt($encrypted);
}
public function test_ciphertext_does_not_contain_plaintext(): void
{
$encrypted = app(UpstreamCredentialCipher::class)->encrypt('cloud-readonly-secret');
$this->assertStringStartsWith('caiwu-system-db-v1:', $encrypted);
$this->assertStringNotContainsString('cloud-readonly-secret', $encrypted);
}
public function test_candidate_system_database_password_can_be_verified_before_switch(): void
{
$cipher = app(UpstreamCredentialCipher::class);
$encrypted = $cipher->encryptWithSecret(
'cloud-readonly-secret',
'candidate-system-database-secret'
);
$this->assertSame(
'cloud-readonly-secret',
$cipher->decryptWithSecret($encrypted, 'candidate-system-database-secret')
);
$this->expectException(DecryptException::class);
$cipher->decryptWithSecret($encrypted, 'wrong-candidate-secret');
}
}