更新
This commit is contained in:
@@ -0,0 +1,212 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
use app\adminapi\controller\LoginController;
|
||||
use app\adminapi\controller\identity\SessionController;
|
||||
use app\adminapi\http\middleware\AuthMiddleware;
|
||||
use app\adminapi\http\middleware\LoginMiddleware;
|
||||
use app\adminapi\logic\auth\AdminLogic;
|
||||
use app\adminapi\service\IdentityHospitalSsoService;
|
||||
use app\adminapi\service\IdentityHospitalSsoTicketStore;
|
||||
use app\adminapi\service\IdentitySessionService;
|
||||
use app\common\cache\AdminAccountSafeCache;
|
||||
use app\common\cache\AdminTokenCache;
|
||||
use app\common\enum\AdminTerminalEnum;
|
||||
use app\common\service\ConfigService;
|
||||
use think\exception\HttpResponseException;
|
||||
use think\facade\Db;
|
||||
|
||||
require dirname(__DIR__) . '/vendor/autoload.php';
|
||||
require_once dirname(__DIR__) . '/vendor/topthink/framework/src/helper.php';
|
||||
|
||||
$checks = 0;
|
||||
function isolationCheck(bool $ok, string $message): void
|
||||
{
|
||||
global $checks;
|
||||
if (!$ok) { throw new RuntimeException($message); }
|
||||
++$checks;
|
||||
}
|
||||
function isolationReject(callable $operation, string $message): void
|
||||
{
|
||||
try {
|
||||
$response = $operation();
|
||||
if ($response instanceof think\Response && (int) ($response->getData()['code'] ?? 1) !== 1) {
|
||||
isolationCheck(true, $message);
|
||||
return;
|
||||
}
|
||||
} catch (HttpResponseException $error) {
|
||||
isolationCheck((int) ($error->getResponse()->getData()['code'] ?? 1) !== 1, $message);
|
||||
return;
|
||||
}
|
||||
throw new RuntimeException($message);
|
||||
}
|
||||
|
||||
$runtime = sys_get_temp_dir() . '/identity-group-isolation-' . bin2hex(random_bytes(10));
|
||||
mkdir($runtime . '/app', 0700, true);
|
||||
// The test app has no real config, service providers, environment files or database settings.
|
||||
copy(dirname(__DIR__) . '/app/common.php', $runtime . '/app/common.php');
|
||||
register_shutdown_function(static function () use ($runtime): void {
|
||||
try { Db::connect()->close(); } catch (Throwable $error) {}
|
||||
$resolved = realpath($runtime);
|
||||
if (!$resolved || strtolower((string) realpath(dirname($resolved))) !== strtolower((string) realpath(sys_get_temp_dir()))
|
||||
|| !preg_match('/^identity-group-isolation-[a-f0-9]{20}$/D', basename($resolved))) { return; }
|
||||
$files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($resolved, FilesystemIterator::SKIP_DOTS), RecursiveIteratorIterator::CHILD_FIRST);
|
||||
foreach ($files as $file) {
|
||||
if ($file->isDir() && !$file->isLink()) { @rmdir($file->getPathname()); }
|
||||
else { @unlink($file->getPathname()); }
|
||||
}
|
||||
@rmdir($resolved);
|
||||
});
|
||||
|
||||
try {
|
||||
if (!extension_loaded('pdo_sqlite')) { throw new RuntimeException('pdo_sqlite is required'); }
|
||||
$app = new class($runtime . DIRECTORY_SEPARATOR) extends think\App {
|
||||
public function loadEnv(string $envName = ''): void { /* Never load real .env files. */ }
|
||||
};
|
||||
$app->setRuntimePath($runtime . '/runtime/');
|
||||
$app->config->set(['default' => 'file', 'channels' => ['file' => ['type' => 'File', 'path' => $runtime . '/log/']]], 'log');
|
||||
$app->config->set(['default' => 'file', 'stores' => ['file' => ['type' => 'File', 'path' => $runtime . '/cache/', 'prefix' => '']]], 'cache');
|
||||
$app->initialize();
|
||||
$app->config->set(['default' => 'fixture', 'auto_timestamp' => true, 'connections' => ['fixture' => [
|
||||
'type' => 'sqlite', 'database' => $runtime . '/fixture.sqlite', 'prefix' => 'f_',
|
||||
'fields_strict' => true, 'trigger_sql' => false, 'break_reconnect' => false]]], 'database');
|
||||
$app->config->set(['unique_identification' => 'fixture-salt',
|
||||
'admin_token' => ['expire_duration' => 3600, 'be_expire_duration' => 600],
|
||||
'default_image' => ['admin_avatar' => 'fixture/avatar.png'],
|
||||
'admin_login' => ['login_restrictions' => 0, 'password_error_times' => 5, 'limit_login_time' => 30]], 'project');
|
||||
$app->env->set(['APP_DEBUG' => false, 'LOCAL_DEBUG_LOGIN_SKIP_PASSWORD' => false, 'WORK_WECHAT_FORCE_BIND_LOGIN' => false]);
|
||||
Db::execute('CREATE TABLE f_admin (id INTEGER PRIMARY KEY,root INTEGER DEFAULT 0,name TEXT,account TEXT,password TEXT,
|
||||
disable INTEGER DEFAULT 0,is_paw INTEGER DEFAULT 1,work_wechat_userid TEXT DEFAULT "",avatar TEXT DEFAULT "",
|
||||
multipoint_login INTEGER DEFAULT 1,login_time INTEGER,login_ip TEXT,create_time INTEGER,update_time INTEGER,delete_time INTEGER)');
|
||||
Db::execute('CREATE TABLE f_admin_session (id INTEGER PRIMARY KEY AUTOINCREMENT,admin_id INTEGER,terminal INTEGER,
|
||||
token TEXT UNIQUE CHECK(length(token)<=32),expire_time INTEGER,update_time INTEGER,UNIQUE(admin_id,terminal))');
|
||||
Db::execute('CREATE TABLE f_system_role (id INTEGER PRIMARY KEY,name TEXT,data_scope INTEGER,delete_time INTEGER)');
|
||||
Db::execute('CREATE TABLE f_system_menu (id INTEGER PRIMARY KEY,pid INTEGER DEFAULT 0,perms TEXT,is_disable INTEGER DEFAULT 0)');
|
||||
Db::execute('CREATE TABLE f_system_role_menu (role_id INTEGER,menu_id INTEGER)');
|
||||
Db::execute('CREATE TABLE f_admin_role (admin_id INTEGER,role_id INTEGER)');
|
||||
Db::execute('CREATE TABLE f_admin_dept (admin_id INTEGER,dept_id INTEGER)');
|
||||
Db::execute('CREATE TABLE f_admin_jobs (admin_id INTEGER,jobs_id INTEGER)');
|
||||
Db::execute('CREATE TABLE f_config (id INTEGER PRIMARY KEY,type TEXT,name TEXT,value TEXT,create_time INTEGER,update_time INTEGER)');
|
||||
|
||||
$sourceIp = '127.0.0.1';
|
||||
$browserIp = '203.0.113.31';
|
||||
$password = 'Synthetic-group-2026';
|
||||
$requestAt = static function (string $ip, string $method = 'POST', array $data = []) use ($app): think\Request {
|
||||
$request = (new think\Request())->withServer(['REMOTE_ADDR' => $ip, 'REQUEST_METHOD' => $method,
|
||||
'HTTP_HOST' => 'hospital.example.test', 'SERVER_PORT' => '443', 'HTTPS' => 'on']);
|
||||
$request->setMethod($method)->setHost('hospital.example.test')->withPost($data);
|
||||
$app->instance('request', $request);
|
||||
return $request;
|
||||
};
|
||||
$createAccount = static function (int $id, int $multipoint) use ($password): void {
|
||||
Db::name('admin')->insert(['id' => $id, 'name' => 'fixture-' . $id, 'account' => 'fixture-' . $id,
|
||||
'password' => create_password($password, 'fixture-salt'), 'root' => 1, 'multipoint_login' => $multipoint,
|
||||
'create_time' => time(), 'update_time' => time()]);
|
||||
};
|
||||
$login = static function (int $id, int|string $terminal, bool $identity = true) use ($requestAt, $password, $sourceIp, $browserIp, $app): string {
|
||||
$requestAt($identity ? $sourceIp : $browserIp, 'POST', ['account' => 'fixture-' . $id, 'password' => $password, 'terminal' => $terminal]);
|
||||
$response = $identity ? (new SessionController($app))->login() : (new LoginController($app))->account();
|
||||
$data = $response->getData();
|
||||
isolationCheck($data['code'] === 1 && is_string($data['data']['token'] ?? null), 'Synthetic controller login failed');
|
||||
return $data['data']['token'];
|
||||
};
|
||||
$access = static function (string $token, string $ip) use ($requestAt) {
|
||||
$request = $requestAt($ip, 'GET');
|
||||
$request->withHeader(['token' => $token]);
|
||||
$request->setController('auth.admin')->setAction('mySelf');
|
||||
$request->controllerObject = new class { public function isNotNeedLogin(): bool { return false; } };
|
||||
return (new LoginMiddleware())->handle($request, static fn ($current) =>
|
||||
(new AuthMiddleware())->handle($current, static fn () => 'allowed'));
|
||||
};
|
||||
$cache = new AdminTokenCache();
|
||||
foreach ([0, 1] as $multipoint) {
|
||||
$id = $multipoint + 1;
|
||||
$createAccount($id, $multipoint);
|
||||
$group = $login($id, AdminTerminalEnum::GROUP_IDENTITY);
|
||||
$pc = $login($id, AdminTerminalEnum::PC, false);
|
||||
$pcAgain = $login($id, AdminTerminalEnum::PC, false);
|
||||
isolationCheck($group !== $pc && $group !== $pcAgain, 'Group reused the hospital PC token');
|
||||
isolationCheck(($multipoint === 0) === ($pc !== $pcAgain), 'Original PC multipoint policy changed');
|
||||
isolationCheck($access($group, $sourceIp) === 'allowed', 'Hospital re-login invalidated Group');
|
||||
isolationCheck($access($pcAgain, $browserIp) === 'allowed', 'Hospital PC login failed its original IP check');
|
||||
isolationCheck($cache->getAdminInfo($group)['login_ip'] === $sourceIp, 'Hospital login overwrote Group cached IP');
|
||||
isolationCheck($access($group, $browserIp) !== 'allowed', 'Group gained an IP-binding bypass');
|
||||
isolationCheck($access($pcAgain, $sourceIp) !== 'allowed', 'Hospital PC gained a bridge IP bypass');
|
||||
|
||||
$reverseId = $id + 10;
|
||||
$createAccount($reverseId, $multipoint);
|
||||
$firstPc = $login($reverseId, AdminTerminalEnum::PC, false);
|
||||
$reverseGroup = $login($reverseId, '11');
|
||||
isolationCheck($firstPc !== $reverseGroup && $access($firstPc, $browserIp) === 'allowed', 'Group login replaced an existing hospital login');
|
||||
isolationCheck($access($reverseGroup, $sourceIp) === 'allowed', 'Reverse-order Group login failed');
|
||||
|
||||
$verifier = bin2hex(random_bytes(32));
|
||||
$challenge = rtrim(strtr(base64_encode(hash('sha256', $verifier, true)), '+/', '-_'), '=');
|
||||
$sso = new IdentityHospitalSsoService(new IdentityHospitalSsoTicketStore($runtime . '/tickets-' . $id));
|
||||
$requestAt($sourceIp);
|
||||
$ticket = $sso->issue($group, ['code_challenge' => $challenge, 'code_challenge_method' => 'S256'])['ticket'];
|
||||
$requestAt($browserIp);
|
||||
$hospital = $sso->exchange(['ticket' => $ticket, 'code_verifier' => $verifier])['token'];
|
||||
isolationCheck($hospital !== $group && $hospital !== $pcAgain, 'SSO terminal 10 reused Group or PC token');
|
||||
isolationCheck((int) Db::name('admin_session')->where('token', $hospital)->value('terminal') === 10, 'Hospital SSO terminal changed');
|
||||
isolationCheck($access($hospital, $browserIp) === 'allowed' && $access($group, $sourceIp) === 'allowed'
|
||||
&& $access($pcAgain, $browserIp) === 'allowed', 'PC/Group/SSO sessions did not remain independent');
|
||||
|
||||
$requestAt($sourceIp);
|
||||
IdentitySessionService::changePassword($group, ['old_password' => $password, 'password' => 'Changed-synthetic-2026',
|
||||
'password_confirm' => 'Changed-synthetic-2026']);
|
||||
isolationCheck(!$cache->getAdminInfo($group) && !$cache->getAdminInfo($pcAgain) && !$cache->getAdminInfo($hospital),
|
||||
'Password change did not revoke Group/PC/SSO sessions');
|
||||
}
|
||||
|
||||
$createAccount(30, 1);
|
||||
$sessionCount = Db::name('admin_session')->count();
|
||||
$app->env->set(['APP_DEBUG' => true, 'LOCAL_DEBUG_LOGIN_SKIP_PASSWORD' => true]);
|
||||
$requestAt($sourceIp, 'POST', ['account' => 'fixture-30', 'password' => 'incorrect', 'terminal' => 11]);
|
||||
isolationReject(static fn () => (new SessionController($app))->login(), 'Debug bypass minted a Group controller session');
|
||||
isolationReject(static fn () => IdentitySessionService::login(['account' => 'fixture-30', 'password' => 'incorrect', 'terminal' => 11]),
|
||||
'Direct service accepted an incorrect password');
|
||||
$app->env->set(['APP_DEBUG' => false, 'LOCAL_DEBUG_LOGIN_SKIP_PASSWORD' => false]);
|
||||
foreach ([10, 8, 12, true, [11]] as $terminal) {
|
||||
$requestAt($sourceIp, 'POST', ['account' => 'fixture-30', 'password' => $password, 'terminal' => $terminal]);
|
||||
isolationReject(static fn () => (new SessionController($app))->login(), 'Identity controller accepted an invalid terminal');
|
||||
}
|
||||
$requestAt($browserIp, 'POST', ['account' => 'fixture-30', 'password' => $password, 'terminal' => 11]);
|
||||
isolationReject(static fn () => (new LoginController($app))->account(), 'Ordinary login accepted Group terminal 11');
|
||||
$requestAt($sourceIp, 'POST', ['account' => 'fixture-30', 'password' => $password, 'terminal' => 11, 'admin_id' => 1]);
|
||||
isolationReject(static fn () => (new SessionController($app))->login(), 'Group login accepted caller-supplied identity');
|
||||
isolationCheck(Db::name('admin_session')->count() === $sessionCount, 'Rejected controller requests changed source sessions');
|
||||
|
||||
ConfigService::set('admin_login', 'login_restrictions', 1);
|
||||
ConfigService::set('admin_login', 'password_error_times', 1);
|
||||
ConfigService::set('admin_login', 'limit_login_time', 1);
|
||||
$safe = new AdminAccountSafeCache();
|
||||
$safe->relieve();
|
||||
$requestAt($sourceIp, 'POST', ['account' => 'fixture-30', 'password' => 'incorrect', 'terminal' => 11]);
|
||||
isolationReject(static fn () => (new SessionController($app))->login(), 'First incorrect password was accepted');
|
||||
$requestAt($sourceIp, 'POST', ['account' => 'fixture-30', 'password' => $password, 'terminal' => 11]);
|
||||
isolationReject(static fn () => (new SessionController($app))->login(), 'Group terminal bypassed the original login limiter');
|
||||
$safe->relieve();
|
||||
ConfigService::set('admin_login', 'login_restrictions', 0);
|
||||
|
||||
$disabled = $login(30, 11);
|
||||
AdminLogic::expireToken($disabled);
|
||||
isolationCheck(!$cache->getAdminInfo($disabled), 'Explicit source revocation did not revoke Group terminal');
|
||||
$disabled = $login(30, 11);
|
||||
Db::name('admin')->where('id', 30)->update(['disable' => 1]);
|
||||
isolationCheck(!$cache->getAdminInfo($disabled), 'Disabled source account retained Group access');
|
||||
$requestAt($sourceIp, 'POST', ['account' => 'fixture-30', 'password' => $password, 'terminal' => 11]);
|
||||
isolationReject(static fn () => (new SessionController($app))->login(), 'Disabled account signed into Group');
|
||||
Db::name('admin')->where('id', 30)->update(['disable' => 0, 'delete_time' => time()]);
|
||||
isolationReject(static fn () => IdentitySessionService::login(['account' => 'fixture-30', 'password' => $password, 'terminal' => 11]),
|
||||
'Soft-deleted account signed into Group');
|
||||
isolationCheck(!in_array(AdminTerminalEnum::GROUP_IDENTITY, AdminTerminalEnum::wecomRpaTerminals(), true), 'Group terminal gained an RPA exemption');
|
||||
fwrite(STDOUT, "PASS Group source session isolation: {$checks} checks; temporary SQLite/cache, real controllers and IP middleware, no live data.\n");
|
||||
} catch (Throwable $error) {
|
||||
$message = $error instanceof HttpResponseException ? ($error->getResponse()->getData()['msg'] ?? 'rejected') : $error->getMessage();
|
||||
fwrite(STDERR, 'FAIL Group source session isolation: ' . $message . "\n");
|
||||
foreach (array_slice($error->getTrace(), 0, 6) as $frame) {
|
||||
fwrite(STDERR, ($frame['file'] ?? '') . ':' . ($frame['line'] ?? 0) . ' ' . ($frame['function'] ?? '') . "\n");
|
||||
}
|
||||
exit(1);
|
||||
}
|
||||
Reference in New Issue
Block a user