Files
zyt/identity-admin/tests/password-race.php
T
2026-11-11 13:53:14 +08:00

134 lines
6.7 KiB
PHP

<?php
declare(strict_types=1);
use app\exception\ApiError;
use app\repository\Database;
use app\repository\IdentityRepository;
use app\service\AuthService;
/** Service regression: both requests authenticate before the first password change. */
final class PasswordRaceFailure extends RuntimeException
{
}
function raceCheck(bool $condition, string $message): void
{
global $checks;
if (!$condition) {
throw new PasswordRaceFailure($message);
}
$checks++;
}
function raceExpectUnauthorized(callable $request, string $message): void
{
try {
$request();
} catch (ApiError $error) {
raceCheck($error->status === 401, $message . ' (expected HTTP 401)');
return;
}
throw new PasswordRaceFailure($message . ' (request unexpectedly succeeded)');
}
$checks = 0;
$exitCode = 0;
$previousEnvironment = [];
try {
$project = dirname(__DIR__);
$server = $project . '/server';
if (!is_file($server . '/vendor/autoload.php')) {
throw new PasswordRaceFailure('Install the independent server Composer dependencies first');
}
if (!extension_loaded('pdo_sqlite')) {
throw new PasswordRaceFailure('Run PHP with the pdo_sqlite extension enabled');
}
$runtime = $project . '/.test-runtime/password-race-' . bin2hex(random_bytes(12));
if (!mkdir($runtime, 0700, true) && !is_dir($runtime)) {
throw new PasswordRaceFailure('Cannot create the isolated test runtime');
}
foreach (['IAM_DB_DRIVER' => 'sqlite', 'IAM_SQLITE_PATH' => $runtime . '/identity.sqlite',
'IAM_RUNTIME_PATH' => $runtime, 'IAM_SESSION_TTL' => '3600'] as $key => $value) {
$previousEnvironment[$key] = getenv($key);
putenv($key . '=' . $value);
}
require $server . '/vendor/autoload.php';
// No application .env is loaded, including the independent server's own file.
$application = new class($server . DIRECTORY_SEPARATOR) extends think\App {
public function loadEnv(string $envName = ''): void
{
}
};
$application->setRuntimePath($runtime . DIRECTORY_SEPARATOR);
$application->initialize();
require $server . '/scripts/schema.php';
require $server . '/scripts/seed.php';
$database = new Database(true);
$repository = new IdentityRepository($database);
$account = 'race_' . bin2hex(random_bytes(8));
$originalPassword = bin2hex(random_bytes(24));
$passwordA = bin2hex(random_bytes(24));
$passwordB = bin2hex(random_bytes(24));
$passwordExpired = bin2hex(random_bytes(24));
$database->transaction(static function () use ($database, $repository, $account, $originalPassword): void {
identitySchema($database);
identitySeed($repository, $account, $originalPassword, '改密竞态回归');
});
$tables = $database->all("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'");
raceCheck(count($tables) === 8, 'The isolated database must contain exactly eight application tables');
$auth = new AuthService($repository);
$tokenA = $auth->login(['account' => $account, 'password' => $originalPassword], '127.0.0.1')['token'];
$tokenB = $auth->login(['account' => $account, 'password' => $originalPassword], '127.0.0.1')['token'];
// Capture both old identities BEFORE A changes anything. B deliberately does not reauthenticate later.
$snapshotA = $auth->authenticate('Bearer ' . $tokenA);
$snapshotB = $auth->authenticate('Bearer ' . $tokenB);
raceCheck($snapshotA['token_hash'] !== $snapshotB['token_hash'], 'A and B must hold different sessions');
raceCheck($snapshotA['admin']['password_hash'] === $snapshotB['admin']['password_hash'], 'A and B must authenticate against the same original password state');
$auth->password($snapshotA['admin'], ['old_password' => $originalPassword,
'password' => $passwordA, 'password_confirm' => $passwordA], $snapshotA['token_hash']);
$adminId = (int) $snapshotA['admin']['id'];
$hashAfterA = $repository->require('admin', $adminId)['password_hash'];
raceCheck(password_verify($passwordA, $hashAfterA), 'A must successfully set the new password');
raceCheck(!password_verify($originalPassword, $hashAfterA), 'The original password must no longer match after A succeeds');
raceExpectUnauthorized(static fn () => $auth->password($snapshotB['admin'], ['old_password' => $originalPassword,
'password' => $passwordB, 'password_confirm' => $passwordB], $snapshotB['token_hash']),
'B must not overwrite A using its already-authenticated, revoked snapshot');
$hashAfterB = $repository->require('admin', $adminId)['password_hash'];
raceCheck(hash_equals($hashAfterA, $hashAfterB), 'The persisted hash must remain byte-for-byte unchanged after B is rejected');
raceCheck(!password_verify($passwordB, $hashAfterB), 'The rejected replacement password must not become valid');
raceExpectUnauthorized(static fn () => $auth->authenticate('Bearer ' . $tokenA), 'A old token must be revoked');
raceExpectUnauthorized(static fn () => $auth->authenticate('Bearer ' . $tokenB), 'B old token must be revoked');
$tokenC = $auth->login(['account' => $account, 'password' => $passwordA], '127.0.0.1')['token'];
$snapshotC = $auth->authenticate('Bearer ' . $tokenC);
raceCheck((int) $snapshotC['admin']['id'] === $adminId, 'The accepted new password must create a normal authenticated session');
$expired = $database->execute('UPDATE admin_session SET expire_time=? WHERE token_hash=?', [time() - 1, $snapshotC['token_hash']]);
raceCheck($expired === 1, 'Exactly the third captured session must be expired');
raceExpectUnauthorized(static fn () => $auth->password($snapshotC['admin'], ['old_password' => $passwordA,
'password' => $passwordExpired, 'password_confirm' => $passwordExpired], $snapshotC['token_hash']),
'An expired session snapshot must not change a password');
raceCheck(hash_equals($hashAfterA, $repository->require('admin', $adminId)['password_hash']),
'The accepted password hash must remain unchanged after the expired snapshot is rejected');
raceExpectUnauthorized(static fn () => $auth->authenticate('Bearer ' . $tokenC), 'The explicitly expired token must remain rejected');
fwrite(STDOUT, "PASS password-race: {$checks} checks; isolated real SQLite, stale and expired sessions rejected.\n");
} catch (Throwable $error) {
// Never print exception traces, request payloads, passwords, tokens or hash values.
$message = $error instanceof PasswordRaceFailure ? $error->getMessage() : 'Unexpected ' . get_class($error);
fwrite(STDERR, "FAIL password-race: {$message}\n");
$exitCode = 1;
} finally {
foreach ($previousEnvironment as $key => $value) {
putenv($value === false ? $key : $key . '=' . $value);
}
}
exit($exitCode);