getResponse()->getData()['code'] === $code, 'Unexpected rejection code'); return; } throw new RuntimeException('Expected hospital handoff rejection'); } function hospitalPkce(string $verifier): string { return rtrim(strtr(base64_encode(hash('sha256', $verifier, true)), '+/', '-_'), '='); } try { if (!extension_loaded('pdo_sqlite')) { throw new RuntimeException('pdo_sqlite is required'); } $runtime = sys_get_temp_dir() . '/identity-hospital-sso-' . bin2hex(random_bytes(10)); mkdir($runtime, 0700, true); $app = new class(dirname(__DIR__) . DIRECTORY_SEPARATOR) extends think\App { public function loadEnv(string $envName = ''): void { /* Never read the real .env. */ } }; $app->setRuntimePath($runtime . DIRECTORY_SEPARATOR); $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(['default' => 'file', 'stores' => ['file' => ['type' => 'File', 'path' => $runtime . '/cache/', 'prefix' => '', 'expire' => 0]]], 'cache'); $app->config->set(['unique_identification' => 'fixture-salt', 'admin_token' => ['expire_duration' => 3600, 'be_expire_duration' => 600], 'default_image' => ['admin_avatar' => 'fixture/avatar.png']], 'project'); $app->env->set(['WORK_WECHAT_FORCE_BIND_LOGIN' => false, 'APP_DEBUG' => 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)'); Db::name('system_role')->insert(['id' => 1, 'name' => 'fixture-reader', 'data_scope' => 3]); Db::name('system_menu')->insertAll([['id' => 1, 'perms' => 'auth.admin/lists'], ['id' => 2, 'perms' => 'auth.menu/delete']]); Db::name('system_role_menu')->insert(['role_id' => 1, 'menu_id' => 1]); $cache = new AdminTokenCache(); $requestAt = static function (string $ip, string $method = 'POST') 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'); $app->instance('request', $request); return $request; }; $nextId = 0; $source = static function (int $multipoint = 0) use (&$nextId, $cache, $requestAt): array { $id = ++$nextId; $requestAt('198.51.100.20'); // Group bridge egress, distinct from the hospital browser. Db::name('admin')->insert(['id' => $id, 'name' => 'fixture-' . $id, 'account' => 'fixture-' . $id, 'password' => create_password(bin2hex(random_bytes(12)), 'fixture-salt'), 'multipoint_login' => $multipoint, 'create_time' => time(), 'update_time' => time()]); Db::name('admin_role')->insert(['admin_id' => $id, 'role_id' => 1]); Db::name('admin_dept')->insert(['admin_id' => $id, 'dept_id' => 4]); Db::name('admin_jobs')->insert(['admin_id' => $id, 'jobs_id' => 5]); $token = bin2hex(random_bytes(16)); $sessionId = Db::name('admin_session')->insertGetId(['admin_id' => $id, 'terminal' => 1, 'token' => $token, 'expire_time' => time() + 3600, 'update_time' => time()]); $cache->setAdminInfo($token); return [$id, $token, (int) $sessionId]; }; $clock = time(); $store = new IdentityHospitalSsoTicketStore($runtime . '/tickets', static function () use (&$clock): int { return $clock; }); $service = new IdentityHospitalSsoService($store); $verifier = bin2hex(random_bytes(32)); $pkce = ['code_challenge' => hospitalPkce($verifier), 'code_challenge_method' => 'S256']; $issue = static fn (string $token): string => $service->issue($token, $pkce)['ticket']; $exchange = static fn (string $ticket): array => $service->exchange(['ticket' => $ticket, 'code_verifier' => $verifier]); $permissions = static function (int $id): array { return [Db::name('admin')->where('id', $id)->find(), Db::name('admin_role')->where('admin_id', $id)->select()->toArray(), Db::name('admin_dept')->where('admin_id', $id)->select()->toArray(), Db::name('admin_jobs')->where('admin_id', $id)->select()->toArray(), Db::name('system_role')->select()->toArray(), Db::name('system_role_menu')->select()->toArray(), Db::name('system_menu')->select()->toArray()]; }; foreach ([0, 1] as $multipoint) { [$id, $token, $sessionId] = $source($multipoint); $beforePermissions = $permissions($id); $beforeSession = Db::name('admin_session')->where('id', $sessionId)->find(); $beforeCache = $cache->getAdminInfo($token); $ticket = $issue($token); $stored = (string) file_get_contents($runtime . '/tickets/' . hash('sha256', $ticket) . '.json'); hospitalCheck(!str_contains($stored, $token) && !str_contains($stored, $ticket), 'Private ticket stored a raw credential'); $requestAt('203.0.113.45'); $login = $exchange($ticket); hospitalCheck($login['token'] !== $token && $login['is_paw'] === 1 && $login['need_bind_work_wechat'] === false, 'Invalid hospital login payload'); hospitalCheck($login['role_name'] === 'fixture-reader' && $login['name'] === 'fixture-' . $id && is_string($login['avatar']), 'Original login payload contract changed'); $target = Db::name('admin_session')->where('token', $login['token'])->find(); hospitalCheck((int) $target['terminal'] === AdminTerminalEnum::GROUP_HOSPITAL && (int) $target['admin_id'] === $id, 'Session was not bound to the derived owner and terminal 10'); hospitalCheck(Db::name('admin_session')->where('id', $sessionId)->find() === $beforeSession, 'Hospital login changed the bridge source session'); hospitalCheck($cache->getAdminInfo($token) === $beforeCache, 'Hospital login changed the bridge token cache'); $hospitalInfo = $cache->getAdminInfo($login['token']); hospitalCheck($hospitalInfo['login_ip'] === '203.0.113.45' && $beforeCache['login_ip'] === '198.51.100.20', 'Browser and bridge IP caches were not independent'); hospitalCheck($permissions($id) === $beforePermissions, 'SSO changed original identity, role, department or permissions'); hospitalCheck(!AuthMiddleware::isTrustedRpaServerRequest($hospitalInfo, '198.51.100.20', '198.51.100.20'), 'Terminal 10 gained an RPA IP exemption'); hospitalReject(static fn () => $issue($login['token']), -1); hospitalReject(static fn () => $exchange($ticket)); // Registered hospital permissions still deny a route outside the original reader role. $request = $requestAt('203.0.113.45'); $request->adminInfo = $hospitalInfo; $request->controllerObject = new class { public function isNotNeedLogin(): bool { return false; } }; $request->setController('auth.menu')->setAction('delete'); $permissionResponse = (new AuthMiddleware())->handle($request, static fn () => 'allowed'); hospitalCheck($permissionResponse instanceof think\Response && $permissionResponse->getData()['code'] === 0, 'Hospital SSO expanded original route permissions'); $request = $requestAt('198.51.100.20'); $request->adminInfo = $hospitalInfo; $request->controllerObject = new class { public function isNotNeedLogin(): bool { return false; } }; $request->setController('auth.admin')->setAction('lists'); $ipResponse = (new AuthMiddleware())->handle($request, static fn () => 'allowed'); hospitalCheck($ipResponse instanceof think\Response && $ipResponse->getData()['code'] === -1, 'Original browser IP binding was bypassed'); $requestAt('198.51.100.20'); $repeatTicket = $issue($token); $requestAt('203.0.113.45'); $repeatLogin = $exchange($repeatTicket); hospitalCheck(($repeatLogin['token'] === $login['token']) === ($multipoint === 1), 'Terminal 10 ignored original single/multipoint policy'); hospitalCheck(Db::name('admin_session')->where('id', $sessionId)->find() === $beforeSession, 'Repeated hospital login rotated the bridge session'); hospitalCheck($cache->getAdminInfo($token) === $beforeCache, 'Repeated hospital login overwrote bridge IP cache'); } [$id, $token] = $source(); foreach (['admin_id', 'id', 'root', 'terminal', 'account', 'source_token'] as $field) { hospitalReject(static fn () => $service->issue($token, $pkce + [$field => 1])); hospitalReject(static fn () => $service->exchange(['ticket' => str_repeat('a', 64), 'code_verifier' => $verifier, $field => 1])); } hospitalReject(static fn () => $service->issue('', $pkce), -1); hospitalReject(static fn () => $service->issue(str_repeat('b', 64), $pkce), -1); hospitalReject(static fn () => $service->issue($token, ['code_challenge' => $pkce['code_challenge'], 'code_challenge_method' => 'plain'])); hospitalReject(static fn () => $service->issue($token, ['code_challenge' => 'bad', 'code_challenge_method' => 'S256'])); $wrongVerifierTicket = $issue($token); hospitalReject(static fn () => $service->exchange(['ticket' => $wrongVerifierTicket, 'code_verifier' => bin2hex(random_bytes(32))])); $requestAt('203.0.113.45'); hospitalCheck(is_string($exchange($wrongVerifierTicket)['token']), 'Wrong verifier consumed an otherwise valid ticket'); $requestAt('198.51.100.20'); $expiredTicket = $issue($token); $clock += 31; hospitalReject(static fn () => $exchange($expiredTicket)); foreach (['revoked', 'rotated', 'deleted_session', 'disabled', 'soft_deleted', 'first_password', 'wecom'] as $condition) { [$id, $token, $sessionId] = $source(); $ticket = $issue($token); if ($condition === 'revoked') { Db::name('admin_session')->where('id', $sessionId)->update(['expire_time' => time() - 1]); } if ($condition === 'rotated') { Db::name('admin_session')->where('id', $sessionId)->update(['token' => bin2hex(random_bytes(16))]); } if ($condition === 'deleted_session') { Db::name('admin_session')->where('id', $sessionId)->delete(); } if ($condition === 'disabled') { Db::name('admin')->where('id', $id)->update(['disable' => 1]); } if ($condition === 'soft_deleted') { Db::name('admin')->where('id', $id)->update(['delete_time' => time()]); } if ($condition === 'first_password') { Db::name('admin')->where('id', $id)->update(['is_paw' => 0]); } if ($condition === 'wecom') { $app->env->set(['WORK_WECHAT_FORCE_BIND_LOGIN' => true, 'WORK_WECHAT_CORP_ID' => 'fixture-corp', 'WORK_WECHAT_SECRET' => 'fixture-only', 'WORK_WECHAT_AGENT_ID' => 'fixture-agent']); } $expected = $condition === 'wecom' ? 10 : ($condition === 'first_password' ? 0 : -1); hospitalReject(static fn () => $exchange($ticket), $expected); hospitalCheck(Db::name('admin_session')->where('admin_id', $id)->where('terminal', 10)->count() === 0, 'Invalid source minted a hospital session'); hospitalReject(static fn () => $exchange($ticket)); hospitalReject(static fn () => $issue($token), $expected); $app->env->set(['WORK_WECHAT_FORCE_BIND_LOGIN' => false]); } // 持有异 IP 的真实源 token 不能用交接接口重新建立可用会话。 [$id, $token] = $source(); $beforeSourceCache = $cache->getAdminInfo($token); $beforeTickets = count(glob($runtime . '/tickets/*.json') ?: []); $requestAt('203.0.113.77'); hospitalReject(static fn () => $issue($token), -1); hospitalCheck(count(glob($runtime . '/tickets/*.json') ?: []) === $beforeTickets, 'Cross-IP source produced a ticket'); hospitalCheck($cache->getAdminInfo($token) === $beforeSourceCache, 'Rejected cross-IP issue changed source cache'); hospitalCheck(Db::name('admin_session')->where('admin_id', $id)->where('terminal', 10)->count() === 0, 'Cross-IP issue created a hospital session'); $requestAt('198.51.100.20'); $ticket = $issue($token); $requestAt('203.0.113.77'); $login = $exchange($ticket); hospitalCheck(strlen($login['token']) === 32, 'Hospital token is incompatible with original varchar(32)'); hospitalCheck($cache->getAdminInfo($login['token'])['login_ip'] === '203.0.113.77', 'Legitimate cross-IP target exchange failed'); hospitalCheck($cache->getAdminInfo($token) === $beforeSourceCache, 'Legitimate exchange modified source IP'); // Source-password changes and explicit all-session logout revoke independent terminal 10 as well. [$id, $token] = $source(); $ticket = $issue($token); $requestAt('203.0.113.45'); $login = $exchange($ticket); IdentitySessionService::logout($token, true); hospitalCheck(Db::name('admin_session')->where('admin_id', $id)->where('expire_time', '>', time())->count() === 0, 'All-session logout left the hospital session alive'); hospitalCheck(!$cache->getAdminInfo($login['token']), 'All-session logout left hospital cache alive'); hospitalReject(static fn () => $service->issue($login['token'], $pkce), -1); [$id, $token] = $source(); $oldPassword = 'Fixture-old-' . bin2hex(random_bytes(6)); $newPassword = 'Fixture-new-' . bin2hex(random_bytes(6)); Db::name('admin')->where('id', $id)->update(['password' => create_password($oldPassword, 'fixture-salt')]); $ticket = $issue($token); IdentitySessionService::changePassword($token, ['old_password' => $oldPassword, 'password' => $newPassword, 'password_confirm' => $newPassword]); hospitalReject(static fn () => $exchange($ticket), -1); hospitalCheck(Db::name('admin_session')->where('admin_id', $id)->where('terminal', 10)->count() === 0, 'Password change raced through the source-session check'); $requestAt('203.0.113.45', 'GET'); $controller = new HospitalSsoController($app); hospitalCheck($controller->issue()->getCode() === 405 && $controller->exchange()->getCode() === 405, 'Handoff accepted non-POST methods'); $request = $requestAt('203.0.113.45'); $request->withHeader(['origin' => 'https://other.example.test']); $controller = new HospitalSsoController($app); hospitalCheck($controller->exchange()->getData()['code'] === 0, 'Cross-origin hospital exchange was accepted'); $request = $requestAt('203.0.113.45'); $request->withGet(['admin_id' => 1]); $controller = new HospitalSsoController($app); hospitalCheck($controller->issue()->getData()['code'] === 0, 'Query-string identity injection was accepted'); hospitalCheck(!in_array(AdminTerminalEnum::GROUP_HOSPITAL, AdminTerminalEnum::wecomRpaTerminals(), true), 'Group terminal entered the privileged RPA set'); fwrite(STDOUT, "PASS hospital SSO: {$checks} checks; isolated SQLite and temporary private files only.\n"); } catch (Throwable $error) { $message = $error instanceof HttpResponseException ? ($error->getResponse()->getData()['msg'] ?? 'rejected') : $error->getMessage(); fwrite(STDERR, 'FAIL hospital SSO: ' . $message . "\n"); foreach (array_slice($error->getTrace(), 0, 8) as $frame) { fwrite(STDERR, ($frame['file'] ?? '') . ':' . ($frame['line'] ?? 0) . ' ' . ($frame['function'] ?? '') . "\n"); } exit(1); }