['id' => 'employee-fixture-1', 'oidcSubject' => 'subject-fixture-1', 'status' => $this->employeeStatus], 'access' => ['allowed' => $this->allowed], 'binding' => ['applicationId' => 'zyt', 'externalAccountId' => '1', 'state' => 'verified', 'version' => $this->bindingVersion], 'authentication' => ['sourceApplicationId' => 'iam-admin', 'sessionId' => 'central-fixture-session', 'authMethod' => 'password', 'sessionVersion' => 4, 'authTime' => $this->authTime ?? time() - 20, 'sourceBindingVersion' => 9]]; } public function call(string $method, string $path, array $body = []): array { $this->calls[] = [$method, $path]; if ($path === '/launch-transactions') { if (!preg_match('/^[a-f0-9]{64}$/D', $body['stateHash'] ?? '')) { throw new \RuntimeException('INVALID_STATE'); } $id = 'fixture-' . (count($this->transactions) + 1); $this->transactions[$id] = $body; return ['transactionId' => $id, 'sourceContinueUrl' => 'https://iam-fixture.invalid/continue?transaction_id=' . $id]; } if ($path === '/launch-grants/exchange') { $tx = $this->transactions[$body['transactionId']] ?? null; $challenge = rtrim(strtr(base64_encode(hash('sha256', $body['codeVerifier'], true)), '+/', '-_'), '='); if (!$tx || !hash_equals($tx['codeChallenge'], $challenge)) { throw new \RuntimeException('INVALID_PKCE'); } return $this->result(); } if ($path === '/fixture/assert-linked') { if (!$this->linked || !$this->allowed || $this->employeeStatus !== 'active') { throw new \RuntimeException('NOT_AUTHORIZED'); } return $this->result(); } throw new \RuntimeException('Unexpected fixture central path: ' . $path); } } final class IamV2Manager { public function __construct(private IamV2Client $client) {} public function assertLinked(int $id): array { IamV2Source::admin($id); $result = $this->client->call('GET', '/fixture/assert-linked'); if ($this->client->afterAssert) { $hook = $this->client->afterAssert; $this->client->afterAssert = null; $hook(); } return $result; } } final class IamV2Flow { public static array $rows = []; public static function put(string $kind, string $id, array $value, int $ttl = 300): void { self::$rows[$kind . ':' . $id] = $value + ['expires' => time() + $ttl]; } public static function peek(string $kind, string $id, string $session): array { $row = self::$rows[$kind . ':' . $id] ?? null; if (!$row || $row['expires'] <= time() || !hash_equals($row['sessionId'], $session)) { throw new \RuntimeException('TRANSACTION_EXPIRED'); } return $row; } public static function take(string $kind, string $id, string $session): array { $row = self::peek($kind, $id, $session); unset(self::$rows[$kind . ':' . $id]); return $row; } } /** Observe the production enroll method at its real cookie boundary. */ function setcookie(string $name, string $value, array $options): bool { if (\think\facade\Db::connect()->getPdo()->inTransaction()) { throw new \RuntimeException('ENROLL_BEFORE_COMMIT'); } $row = \think\facade\Db::name('iam_v2_source_session')->where('session_id', $value)->find(); if (!$row || $row['auth_method'] !== 'iam_launch') { throw new \RuntimeException('MISSING_PRODUCTION_ENROLL'); } $GLOBALS['compatEnrollObservations'][] = ['committed' => true, 'method' => $row['auth_method']]; return true; } } namespace app\adminapi\service\iam { final class IamOidcClient { public static int $provisioningCalls = 0; public function __construct(array $settings) {} public function provisioning(string $subject): array { ++self::$provisioningCalls; if ($subject !== 'subject-fixture-1') { throw new \RuntimeException('ACCOUNT_MISMATCH'); } return ['employee' => ['id' => 'employee-fixture-1'], 'externalAccountId' => '1', 'bindingVersion' => 7]; } } final class IamAccountProvisioner { public static int $resolveCalls = 0; public function resolve(IamOidcClient $client, array $settings, string $subject): int { ++self::$resolveCalls; return 1; } } } namespace app\adminapi\logic { function curl_init() { throw new \RuntimeException('NETWORK_FORBIDDEN_IN_COMPAT_TEST'); } } namespace { use app\adminapi\logic\LoginLogic; use app\adminapi\service\iam\v2\IamV2Client; use app\adminapi\service\iam\v2\IamV2Flow; use app\adminapi\service\iam\v2\IamV2Source; use app\adminapi\service\iam\v2\IamV2Target; use app\common\cache\AdminTokenCache; use think\facade\Db; $baseline = in_array('--baseline', $argv, true); $loader = require 'C:/zyt/server/vendor/autoload.php'; $overlay = 'C:/zyt/identity-admin/.test-runtime/deploy-original-overlay/'; $loader->setPsr4('app\\', [$overlay . 'app/', 'C:/zyt/server/app/']); $loader->addClassMap([ 'app\\adminapi\\logic\\LoginLogic' => $overlay . 'app/adminapi/logic/LoginLogic.php', 'app\\adminapi\\service\\AdminTokenService' => $overlay . 'app/adminapi/service/AdminTokenService.php', 'app\\common\\cache\\AdminTokenCache' => $overlay . 'app/common/cache/AdminTokenCache.php', 'app\\common\\enum\\AdminTerminalEnum' => $overlay . 'app/common/enum/AdminTerminalEnum.php', 'app\\adminapi\\service\\iam\\v2\\IamV2Source' => __DIR__ . '/production-IamV2Source.php', 'app\\adminapi\\service\\iam\\v2\\IamV2Target' => __DIR__ . ($baseline ? '/production-IamV2Target.php' : '/compat-IamV2Target.php'), ]); require_once 'C:/zyt/server/vendor/topthink/framework/src/helper.php'; $checks = 0; function check(bool $ok, string $message): void { global $checks; if (!$ok) { throw new \RuntimeException($message); } ++$checks; } function reject(callable $call, string $expected): void { try { $call(); } catch (\RuntimeException $error) { check($error->getMessage() === $expected, 'Wrong rejection: ' . $error->getMessage() . ', expected ' . $expected); return; } throw new \RuntimeException('Expected rejection: ' . $expected); } function rejectPassword(array $params): void { try { (new LoginLogic())->login($params); } catch (\think\exception\HttpResponseException $error) { check($error->getResponse()->getData()['code'] === -1, 'Password failure must retain error code'); return; } throw new \RuntimeException('Password login accepted missing or incorrect password'); } function prepare(IamV2Target $target, string $token = ''): array { $_COOKIE = []; $p = $target->prepare('iam-admin', str_repeat('I', 43), $token); parse_str(parse_url($p['url'], PHP_URL_QUERY), $q); return [$q['transaction_id'], $p['browser']]; } function callback(IamV2Target $target, array $p): array { return $target->callback($p[0], str_repeat('G', 43), $p[1], 'https://iam-fixture.invalid'); } function ticket(IamV2Target $target): array { $p = prepare($target); return [callback($target, $p)['ticket'], $p[1]]; } function sessionCount(): int { return Db::name('admin_session')->count(); } try { $runtime = __DIR__ . '/compat-validation/runtime/' . ($baseline ? 'baseline-' : 'compat-') . bin2hex(random_bytes(8)); mkdir($runtime, 0700, true); $app = new class(__DIR__ . '/compat-validation/') extends \think\App { public function loadEnv(string $envName = ''): void { /* Real environment files are never loaded. */ } }; $app->setRuntimePath($runtime . '/'); $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], 'default_image' => ['admin_avatar' => 'fixture/avatar.png']], 'project'); $app->config->set(['v2_sources' => ['iam-admin' => 'https://iam-fixture.invalid/continue']], 'iam'); $app->env->set(['APP_DEBUG' => false, 'LOCAL_DEBUG_LOGIN_SKIP_PASSWORD' => false, 'WORK_WECHAT_FORCE_BIND_LOGIN' => true, 'WORK_WECHAT_CORP_ID' => 'fixture-corp', 'WORK_WECHAT_SECRET' => 'fixture-only', 'WORK_WECHAT_AGENT_ID' => 'fixture-agent']); $request = (new \think\Request())->withServer(['REMOTE_ADDR' => '198.51.100.61', 'HTTP_HOST' => 'hospital-fixture.invalid', 'HTTPS' => 'on']); $app->instance('request', $request); 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, expire_time INTEGER, update_time 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_system_role (id INTEGER PRIMARY KEY, name TEXT, delete_time INTEGER)'); Db::execute('CREATE TABLE f_config (id INTEGER PRIMARY KEY, type TEXT, name TEXT, value TEXT, create_time INTEGER, update_time INTEGER)'); Db::execute('CREATE TABLE f_iam_v2_binding (admin_id INTEGER, employee_id TEXT, state TEXT, version INTEGER)'); Db::execute('CREATE TABLE f_iam_v2_source_session (session_id TEXT PRIMARY KEY, admin_id INTEGER, business_session_id INTEGER, token_hash TEXT, account_stamp TEXT, auth_method TEXT, auth_time INTEGER, version INTEGER, revoked INTEGER, binding_version INTEGER, employee_id TEXT, expires_at INTEGER)'); Db::execute('CREATE TABLE f_iam_v2_target_session (token_hash TEXT PRIMARY KEY, admin_id INTEGER, employee_id TEXT, source_application_id TEXT, source_binding_version INTEGER, checked_at INTEGER)'); foreach ([1, 2] as $id) { Db::name('admin')->insert(['id' => $id, 'name' => 'fixture-' . $id, 'account' => 'fixture-' . $id, 'password' => create_password('Fixture-password', 'fixture-salt'), 'is_paw' => 0, 'avatar' => $id === 1 ? 'fixture/person.png' : '']); } Db::name('system_role')->insert(['id' => 3, 'name' => 'Fixture role']); Db::name('admin_role')->insert(['admin_id' => 1, 'role_id' => 3]); Db::name('iam_v2_binding')->insert(['admin_id' => 1, 'employee_id' => 'employee-fixture-1', 'state' => 'verified', 'version' => 7]); check(realpath((new \ReflectionClass(LoginLogic::class))->getFileName()) === realpath($overlay . 'app/adminapi/logic/LoginLogic.php'), 'Must load staged strict LoginLogic'); check(str_ends_with((new \ReflectionClass(IamV2Source::class))->getFileName(), 'production-IamV2Source.php'), 'Must load production enroll implementation'); $client = new IamV2Client(); // No resolve/login injection: the production default closures execute. $target = new IamV2Target($client); $t = ticket($target); if ($baseline) { try { $target->exchange($t[0], $t[1], ''); } catch (\think\exception\HttpResponseException $error) { check($error->getResponse()->getData()['code'] === -1, 'Baseline must fail at the strict password gate'); check(sessionCount() === 0, 'Baseline failed login created a session'); fwrite(STDOUT, "PASS baseline reproduces legal IAM launch failure at strict LoginLogic password gate; {$checks} checks.\n"); exit(0); } throw new \RuntimeException('Baseline did not reproduce the compatibility bug'); } check((new \ReflectionMethod(IamV2Target::class, 'loginVerifiedAdmin'))->isPrivate(), 'IAM session issuer must stay private'); $login = $target->exchange($t[0], $t[1], ''); check(array_keys($login) === ['name', 'avatar', 'role_name', 'token', 'is_paw', 'need_bind_work_wechat'], 'Full original login payload changed'); check($login['name'] === 'fixture-1' && $login['role_name'] === 'Fixture role', 'Name or role payload changed'); check(str_ends_with($login['avatar'], '/fixture/person.png'), 'Avatar payload changed'); check($login['is_paw'] === 0 && $login['need_bind_work_wechat'] === true, 'Password/bind gate flags changed'); $session = Db::name('admin_session')->where('token', $login['token'])->find(); check($session && (int) $session['admin_id'] === 1 && (int) $session['terminal'] === 1, 'Legal launch did not mint normal PC session'); check((new AdminTokenCache())->getAdminInfo($login['token']) !== false, 'Legal launch token is unusable'); check(Db::name('admin')->where('id', 1)->value('login_ip') === '198.51.100.61', 'Browser IP not retained'); check((int) Db::name('admin')->where('id', 1)->value('login_time') > 0, 'Login time not updated'); check(count($GLOBALS['compatEnrollObservations'] ?? []) === 1, 'Production enroll must run once after commit'); $source = IamV2Source::current($login['token']); check($source['auth_method'] === 'iam_launch' && (int) $source['auth_time'] >= time() - 30, 'IAM source auth context changed'); check(Db::name('iam_v2_target_session')->where('token_hash', hash('sha256', $login['token']))->count() === 1, 'Target compensation record missing'); check(\app\adminapi\service\iam\IamOidcClient::$provisioningCalls === 1 && \app\adminapi\service\iam\IamAccountProvisioner::$resolveCalls === 1, 'Default resolver was bypassed'); reject(fn () => $target->exchange($t[0], $t[1], ''), 'TRANSACTION_EXPIRED'); $count = sessionCount(); rejectPassword(['account' => 'fixture-1', 'terminal' => 1]); rejectPassword(['account' => 'fixture-1', 'password' => 'incorrect', 'terminal' => 1]); check(sessionCount() === $count, 'Rejected password login created a session'); $password = (new LoginLogic())->login(['account' => 'fixture-1', 'password' => 'Fixture-password', 'terminal' => 1]); check($password === $login, 'IAM payload differs from strict password login payload'); foreach (['disable' => 1, 'delete_time' => time()] as $column => $value) { $t = ticket($target); $enrolls = count($GLOBALS['compatEnrollObservations']); // Change after exchange's live manager read to prove the final locked local recheck. $client->afterAssert = static fn () => Db::name('admin')->where('id', 1)->update([$column => $value]); reject(fn () => $target->exchange($t[0], $t[1], ''), 'ACCOUNT_DISABLED'); check(sessionCount() === $count && count($GLOBALS['compatEnrollObservations']) === $enrolls, $column . ' change minted/enrolled a session'); Db::name('admin')->where('id', 1)->update([$column => $column === 'disable' ? 0 : null]); reject(fn () => $target->exchange($t[0], $t[1], ''), 'TRANSACTION_EXPIRED'); } foreach (['disable' => 1, 'delete_time' => time()] as $column => $value) { $p = prepare($target); Db::name('admin')->where('id', 1)->update([$column => $value]); reject(fn () => callback($target, $p), 'ACCOUNT_DISABLED'); Db::name('admin')->where('id', 1)->update([$column => $column === 'disable' ? 0 : null]); } $p = prepare($target); $client->allowed = false; reject(fn () => callback($target, $p), 'NOT_AUTHORIZED'); $client->allowed = true; $p = prepare($target); $client->employeeStatus = 'disabled'; reject(fn () => callback($target, $p), 'NOT_AUTHORIZED'); $client->employeeStatus = 'active'; $p = prepare($target); $client->authTime = time() + 3600; reject(fn () => callback($target, $p), 'INVALID_AUTHENTICATION'); $client->authTime = null; $t = ticket($target); $client->linked = false; reject(fn () => $target->exchange($t[0], $t[1], ''), 'NOT_AUTHORIZED'); $client->linked = true; $t = ticket($target); $client->bindingVersion = 8; reject(fn () => $target->exchange($t[0], $t[1], ''), 'BINDING_CONFLICT'); $client->bindingVersion = 7; $p = prepare($target); reject(fn () => $target->callback($p[0], str_repeat('G', 43), str_repeat('a', 64), 'https://iam-fixture.invalid'), 'TRANSACTION_EXPIRED'); reject(fn () => $target->callback($p[0], str_repeat('G', 43), $p[1], 'https://attacker-fixture.invalid'), 'INVALID_ORIGIN'); IamV2Flow::$rows['target_launch:' . $p[0]]['verifier'] = str_repeat('f', 64); reject(fn () => callback($target, $p), 'INVALID_PKCE'); $p = prepare($target); $c = callback($target, $p); reject(fn () => callback($target, $p), 'TRANSACTION_EXPIRED'); reject(fn () => $target->exchange($c['ticket'], str_repeat('b', 64), ''), 'TRANSACTION_EXPIRED'); $other = (new LoginLogic())->login(['account' => 'fixture-2', 'password' => 'Fixture-password', 'terminal' => 1]); $p = prepare($target, $other['token']); reject(fn () => callback($target, $p), 'ACCOUNT_MISMATCH'); $t = ticket($target); reject(fn () => $target->exchange($t[0], $t[1], $other['token']), 'ACCOUNT_MISMATCH'); check(sessionCount() === $count + 1, 'Rejected IAM flow minted unexpected business sessions'); check(count($GLOBALS['compatEnrollObservations']) === 1, 'Rejected IAM flow enrolled a source session'); Db::name('admin')->where('id', 1)->update(['avatar' => '', 'root' => 1, 'is_paw' => 1]); $p = prepare($target, $login['token']); $c = callback($target, $p); $rootLogin = $target->exchange($c['ticket'], $p[1], $login['token']); check(str_ends_with($rootLogin['avatar'], '/fixture/avatar.png'), 'Default avatar fallback changed'); check($rootLogin['role_name'] === '系统管理员' && $rootLogin['is_paw'] === 1 && $rootLogin['need_bind_work_wechat'] === false, 'Root/password/bind payload changed'); check((new LoginLogic())->login(['account' => 'fixture-1', 'password' => 'Fixture-password', 'terminal' => 1]) === $rootLogin, 'Root IAM payload differs from password payload'); check(count($GLOBALS['compatEnrollObservations']) === 2 && sessionCount() === $count + 1, 'Expected-admin match did not retain PC shared-session semantics'); fwrite(STDOUT, "PASS IAM launch compatibility: {$checks} checks; default resolve/login closures; actual staged AdminTokenService + production IamV2Source; isolated SQLite; no network.\n"); } catch (\Throwable $error) { fwrite(STDERR, 'FAIL IAM compatibility: ' . get_class($error) . ': ' . $error->getMessage() . "\n" . $error->getTraceAsString() . "\n"); exit(1); } }