You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
virt/web/tests/AccountEmailChangeTest.php

265 lines
10 KiB
PHTML

<?php
require dirname(__DIR__) . '/vendor/autoload.php';
use App\Models\User;
use App\Services\AccountEmailChangeService;
use App\Services\RedisClient;
use Illuminate\Database\Capsule\Manager as Capsule;
use Illuminate\Database\Schema\Blueprint;
$System_Config = [];
$assert = static function ($condition, string $message): void {
if (!$condition) {
throw new RuntimeException($message);
}
};
final class AccountEmailChangeFakeRedisBackend
{
private array $values = [];
private array $expiresAt = [];
public function get($key)
{
$this->purge((string) $key);
return $this->values[(string) $key] ?? null;
}
public function set($key, $value, ...$options)
{
$key = (string) $key;
$this->purge($key);
if (in_array('NX', $options, true) && array_key_exists($key, $this->values)) {
return null;
}
$this->values[$key] = (string) $value;
$expiryIndex = array_search('EX', $options, true);
if ($expiryIndex !== false && isset($options[$expiryIndex + 1])) {
$this->expiresAt[$key] = time() + (int) $options[$expiryIndex + 1];
}
return 'OK';
}
public function setex($key, $seconds, $value)
{
$this->values[(string) $key] = (string) $value;
$this->expiresAt[(string) $key] = time() + (int) $seconds;
return 'OK';
}
public function ttl($key): int
{
$key = (string) $key;
$this->purge($key);
return isset($this->expiresAt[$key])
? max(0, $this->expiresAt[$key] - time())
: -1;
}
public function incr($key): int
{
$key = (string) $key;
$this->purge($key);
$this->values[$key] = (string) (((int) ($this->values[$key] ?? 0)) + 1);
return (int) $this->values[$key];
}
public function expire($key, $seconds): int
{
$key = (string) $key;
if (!array_key_exists($key, $this->values)) {
return 0;
}
$this->expiresAt[$key] = time() + (int) $seconds;
return 1;
}
public function del(...$keys): int
{
$deleted = 0;
foreach ($keys as $key) {
$key = (string) $key;
if (array_key_exists($key, $this->values)) {
unset($this->values[$key], $this->expiresAt[$key]);
$deleted++;
}
}
return $deleted;
}
private function purge(string $key): void
{
if (isset($this->expiresAt[$key]) && $this->expiresAt[$key] <= time()) {
unset($this->values[$key], $this->expiresAt[$key]);
}
}
}
final class AccountEmailChangeFakeRedis extends RedisClient
{
public function __construct(private AccountEmailChangeFakeRedisBackend $backend)
{
}
public function getClient()
{
return $this->backend;
}
public function del($key)
{
return $this->backend->del($key);
}
}
$capsule = new Capsule();
$capsule->addConnection(['driver' => 'sqlite', 'database' => ':memory:'], 'default');
$capsule->setAsGlobal();
$capsule->bootEloquent();
$schema = $capsule->getConnection('default')->getSchemaBuilder();
$schema->create('configurations', static function (Blueprint $table): void {
$table->increments('id');
$table->string('name')->unique();
$table->text('value')->nullable();
});
$schema->create('user', static function (Blueprint $table): void {
$table->increments('id');
$table->string('email', 254)->unique();
$table->string('pass');
$table->unsignedBigInteger('login_session_version')->default(0);
});
$schema->create('email_verify', static function (Blueprint $table): void {
$table->increments('id');
$table->text('email');
$table->text('ip');
$table->text('code');
$table->bigInteger('expire_in');
});
Capsule::table('configurations')->insert(['name' => 'email_blacklist', 'value' => '']);
$currentPassword = 'Current#Pass123';
$passwordHash = password_hash($currentPassword, PASSWORD_BCRYPT, ['cost' => 4]);
Capsule::table('user')->insert([
['id' => 1, 'email' => 'old@example.com', 'pass' => $passwordHash,
'login_session_version' => 0],
['id' => 2, 'email' => 'used@example.com', 'pass' => $passwordHash,
'login_session_version' => 0],
]);
Capsule::table('email_verify')->insert([
['email' => 'new@example.com', 'ip' => '127.0.0.1',
'code' => 'email_change:1:123456', 'expire_in' => time() + 600],
['email' => 'new@example.com', 'ip' => '127.0.0.1',
'code' => 'email_change:1:654321', 'expire_in' => time() + 600],
['email' => 'old@example.com', 'ip' => '127.0.0.1',
'code' => 'password_change:777777', 'expire_in' => time() + 600],
['email' => 'new@example.com', 'ip' => '127.0.0.1',
'code' => 'email_change:2:999999', 'expire_in' => time() + 600],
]);
$backend = new AccountEmailChangeFakeRedisBackend();
$sharedClient = (new ReflectionClass(RedisClient::class))->getProperty('sharedClient');
$sharedClient->setValue(null, $backend);
$redis = new AccountEmailChangeFakeRedis($backend);
$user = User::findOrFail(1);
$invalid = AccountEmailChangeService::change(
$user, 'not-an-email', $currentPassword, '123456', $redis
);
$assert(!$invalid['ok'] && $invalid['status'] === 422,
'An invalid target email was accepted.');
$assert(Capsule::table('email_verify')->where('email', 'new@example.com')->count() === 3,
'Validation consumed a new-email code before the transaction.');
$same = AccountEmailChangeService::change(
$user, 'OLD@example.com', $currentPassword, '123456', $redis
);
$assert(!$same['ok'] && $same['status'] === 422,
'The current email was accepted as a replacement.');
$duplicate = AccountEmailChangeService::change(
$user, 'used@example.com', $currentPassword, '123456', $redis
);
$assert(!$duplicate['ok'] && $duplicate['status'] === 409,
'An email owned by another account was accepted.');
$assert(Capsule::table('email_verify')->where('code', 'email_change:1:123456')->exists(),
'A rejected duplicate target consumed the new-email code.');
$wrongPassword = AccountEmailChangeService::change(
$user, 'new@example.com', 'Wrong#Pass123', '123456', $redis
);
$assert(!$wrongPassword['ok'] && $wrongPassword['status'] === 422
&& User::findOrFail(1)->email === 'old@example.com',
'An invalid current password changed the account email.');
$assert(Capsule::table('email_verify')->where('code', 'email_change:1:123456')->exists(),
'An invalid current password consumed the new-email verification code.');
$wrong = AccountEmailChangeService::change(
$user, 'new@example.com', $currentPassword, '000000', $redis
);
$assert(!$wrong['ok'] && $wrong['status'] === 422
&& User::findOrFail(1)->email === 'old@example.com',
'An invalid new-email code changed the account email.');
$changed = AccountEmailChangeService::change(
$user, ' New@Example.com ', $currentPassword, '123456', $redis
);
$updated = User::findOrFail(1);
$assert($changed['ok'] && $changed['email'] === 'new@example.com'
&& $updated->email === 'new@example.com'
&& (int) $updated->login_session_version === 1,
'A valid new-email code did not atomically replace the email and revoke sessions.');
$assert(Capsule::table('email_verify')
->where('email', 'new@example.com')->where('code', 'like', 'email_change:1:%')->count() === 0,
'Codes issued to the changed account remained usable after success.');
$assert(Capsule::table('email_verify')->where('code', 'email_change:2:999999')->exists(),
'Changing one account email deleted another account verification code.');
$assert(Capsule::table('email_verify')->where('code', 'password_change:777777')->exists(),
'Changing an email deleted an unrelated password verification code.');
$replay = AccountEmailChangeService::change(
$user, 'second@example.com', $currentPassword, '123456', $redis
);
$assert(!$replay['ok'] && User::findOrFail(1)->email === 'new@example.com',
'A consumed new-email code was replayed.');
$root = dirname(__DIR__);
$routes = file_get_contents($root . '/config/routes.php');
$controller = file_get_contents($root . '/app/Controllers/AccountSecurityController.php');
$service = file_get_contents($root . '/app/Services/AccountEmailChangeService.php');
$template = file_get_contents($root . '/resources/views/venix/user/edit.tpl');
$runtime = file_get_contents($root . '/public/theme/venix/js/user-home.js');
$mail = file_get_contents($root . '/resources/email/auth/verify.tpl');
foreach (compact('routes', 'controller', 'service', 'template', 'runtime', 'mail') as $name => $source) {
$assert(is_string($source), 'Unable to read email-change source: ' . $name);
}
$assert(str_contains($routes, "'/email/verify/send'")
&& str_contains($routes, "'/email'")
&& str_contains($controller, 'AdminCsrf::verify')
&& str_contains($controller, "getParam('oldpwd', '')")
&& str_contains($controller, 'Auth::logout()'),
'The email-change API lost its password, CSRF or logout boundary.');
$assert(str_contains($service, "private const CODE_PREFIX = 'email_change:'")
&& str_contains($service, 'sendNewEmailCode')
&& str_contains($service, '$verification->email = $newEmail')
&& str_contains($service, "'msg' => '验证码已发送至新邮箱'")
&& str_contains($service, 'lockForUpdate()')
&& str_contains($service, 'LoginSessionRevocationService::revokeUser')
&& str_contains($service, "self::codePrefixForUser(\$userId) . \$emailCode")
&& str_contains($service, "EmailVerify::where('email', '=', \$newEmail)"),
'The email-change service lost code isolation, locking, cleanup or session revocation.');
$assert(str_contains($template, 'id="vuEmailForm"')
&& str_contains($template, 'id="account-email-current-password"')
&& str_contains($template, 'autocomplete="current-password"')
&& str_contains($template, '新邮箱验证码')
&& str_contains($runtime, 'post("/user/email/verify/send"')
&& str_contains($runtime, '{ email: email }')
&& str_contains($runtime, 'post("/user/email"')
&& str_contains($runtime, 'oldpwd: currentPassword')
&& str_contains($runtime, 'window.top.location.href = loginUrl')
&& str_contains($mail, "\$scene == 'email_change'"),
'The account drawer, current-password submission, browser behavior or email scene is not fully wired.');
RedisClient::resetSharedClient();
echo "Account email change new-address verification checks passed.\n";