import assert from 'node:assert/strict' import { spawnSync } from 'node:child_process' import { mkdtemp, rm } from 'node:fs/promises' import { tmpdir } from 'node:os' import { basename, dirname, join, resolve } from 'node:path' import { fileURLToPath } from 'node:url' import test from 'node:test' // 执行真实中央服务,仅在 SourceApiClient 的传输边界替换原 API;不启动应用、不读取 .env。 const fixture = String.raw`users = [ 1 => ['id' => 1, 'account' => 'fixture-owner', 'name' => '集团管理员', 'root' => 1, 'disable' => 0, 'role_id' => [], 'dept_id' => [11], 'is_paw' => 1], 2 => ['id' => 2, 'account' => 'fixture-member', 'name' => '医院员工', 'root' => 0, 'disable' => 0, 'role_id' => [7], 'dept_id' => [11], 'is_paw' => 1, 'avatar' => 'fixture-avatar', 'multipoint_login' => 1, 'jobs_id' => [21]], ]; foreach ($this->users as &$user) { $user['password'] = password_hash('Fixture-old-123', PASSWORD_DEFAULT); } unset($user); $this->roles = [7 => ['id' => 7, 'name' => '医院角色', 'menu_id' => [101], 'data_scope' => 3], 8 => ['id' => 8, 'name' => '其他角色', 'menu_id' => [], 'data_scope' => 1]]; } public function revoke(int $id): void { foreach ($this->sessions as $token => $subject) { if ($subject === $id) { unset($this->sessions[$token]); } } } public function count(string $path): int { return count(array_filter($this->requests, static fn (array $row): bool => $row['path'] === $path)); } public function last(string $path): array { $rows = array_values(array_filter($this->requests, static fn (array $row): bool => $row['path'] === $path)); return $rows[count($rows) - 1]; } public function transport(string $method, string $url, array $headers, string $body): array { $path = substr((string) parse_url($url, PHP_URL_PATH), strlen('/adminapi/')); parse_str((string) parse_url($url, PHP_URL_QUERY), $data); if ($method === 'POST') { $data = json_decode($body, true, 32, JSON_THROW_ON_ERROR); } $this->requests[] = ['method' => $method, 'path' => $path, 'data' => $data]; $reply = static fn (array $result = [], int $code = 1): array => ['status' => 200, 'body' => json_encode(['code' => $code, 'data' => $result], JSON_THROW_ON_ERROR)]; if ($method === 'GET' && $this->failReads) { return ['status' => 503, 'body' => '']; } if ($path === 'identity.session/login') { foreach ($this->users as $id => $user) { if ($user['account'] === $data['account'] && $user['disable'] === 0 && password_verify($data['password'], $user['password'])) { $token = 'fixture-source-' . bin2hex(random_bytes(12)); $this->sessions[$token] = $id; return $reply(['token' => $token]); } } return $reply([], 0); } $token = ''; foreach ($headers as $header) { if (str_starts_with($header, 'token: ')) { $token = substr($header, 7); } } $id = $this->sessions[$token] ?? 0; if (!$id) { return $reply([], -1); } $user = $this->users[$id]; if ($path === 'auth.admin/mySelf') { $permissions = $user['root'] === 1 ? ['*'] : []; foreach ($user['role_id'] as $role) { if (in_array(101, $this->roles[$role]['menu_id'], true)) { $permissions[] = 'auth.admin/lists'; } } return $reply(['user' => $user, 'permissions' => array_values(array_unique($permissions)), 'menu' => [['id' => 101, 'pid' => 0, 'name' => '用户管理', 'type' => 'C', 'perms' => 'auth.admin/lists', 'component' => 'permission/admin/index', 'is_disable' => 0]]]); } if ($path === 'auth.admin/detail') { return $reply($this->users[(int) $data['id']] ?? []); } if ($path === 'auth.admin/lists') { return $reply(['lists' => array_values($this->users), 'count' => count($this->users)]); } if ($path === 'auth.role/detail') { return $reply($this->roles[(int) $data['id']] ?? []); } if ($path === 'auth.role/all') { return $reply(array_values($this->roles)); } if ($path === 'dept.dept/all') { return $reply([['id' => 11, 'pid' => 0, 'name' => '医院', 'status' => 1]]); } if ($path === 'auth.menu/lists') { return $reply(['lists' => [['id' => 101, 'pid' => 0, 'name' => '用户管理', 'type' => 'C']]]); } if ($path === 'auth.admin/edit') { $target = (int) $data['id']; $changed = isset($data['password']) || $data['role_id'] !== $this->users[$target]['role_id'] || $data['disable'] !== 0; $values = $data; unset($values['password_confirm']); if (isset($values['password'])) { $values['password'] = password_hash($values['password'], PASSWORD_DEFAULT); } $this->users[$target] = array_replace($this->users[$target], $values); // 此处只模拟已单独测试的原系统撤销契约;本测试证明中央正确依赖该契约。 if ($changed) { $this->revoke($target); } $this->failReads = $this->failReadsAfterWrite; return $reply(); } if ($path === 'auth.role/edit') { $target = (int) $data['id']; $this->roles[$target] = array_replace($this->roles[$target], $data); foreach ($this->users as $subject => $candidate) { if (in_array($target, $candidate['role_id'], true)) { $this->revoke($subject); } } $this->failReads = $this->failReadsAfterWrite; return $reply(); } if ($path === 'identity.session/password') { if (!password_verify($data['old_password'], $user['password']) || $data['password'] !== $data['password_confirm']) { return $reply([], 0); } $this->users[$id]['password'] = password_hash($data['password'], PASSWORD_DEFAULT); $this->revoke($id); return $reply(); } if ($path === 'identity.hospitalSso/issue') { $this->issues++; return $reply(['ticket' => bin2hex(random_bytes(32))]); } throw new RuntimeException('Unexpected isolated source operation'); } } $checks = 0; function verify(bool $condition, string $message): void { global $checks; if (!$condition) { throw new RuntimeException($message); } $checks++; } function denied(callable $action, int $status): void { try { $action(); } catch (ApiError $error) { verify($error->status === $status, 'Unexpected bridge rejection status'); return; } throw new RuntimeException('Bridge accepted a prohibited operation'); } try { $fake = new IsolatedSource(); $source = new SourceApiClient('http://127.0.0.1:1/adminapi', $fake->transport(...)); $sessions = new SessionStore(getenv('IAM_RUNTIME_PATH') . '/sessions'); $bridge = new SharedIdentityService($source, $sessions); $store = new GroupStore($source->sourceKey()); $login = static fn (string $account, string $password = 'Fixture-old-123'): string => $bridge->dispatch('login', '', ['account' => $account, 'password' => $password])['token']; $owner = 'Bearer ' . $login('fixture-owner'); $memberToken = $login('fixture-member'); $member = 'Bearer ' . $memberToken; $gid = $bridge->dispatch('myself', $member)['gid']; $verifier = str_repeat('v', 64); $authorization = ['client_id' => 'internet-hospital', 'redirect_uri' => GroupService::hospitalEntry(), 'state' => str_repeat('s', 64), 'code_challenge' => rtrim(strtr(base64_encode(hash('sha256', $verifier, true)), '+/', '-_'), '='), 'code_challenge_method' => 'S256']; $issue = static function (string $auth) use ($bridge, $authorization): string { $redirect = $bridge->dispatch('group.sso.authorize', $auth, $authorization)['redirect_url']; parse_str((string) parse_url($redirect, PHP_URL_QUERY), $query); return $query['code']; }; $exchange = static fn (string $code): array => $bridge->dispatch('group.sso.exchange', '', ['client_id' => $authorization['client_id'], 'redirect_uri' => $authorization['redirect_uri'], 'code' => $code, 'code_verifier' => $verifier]); // 空密码和省略密码均只编辑同一个源账号;成功写入后原读取故障不应伪报保存失败。 foreach ([[], ['password' => '']] as $passwordFields) { $beforeReads = $fake->count('auth.admin/mySelf'); $fake->failReadsAfterWrite = true; verify($bridge->dispatch('admin.edit', $owner, ['id' => 2, 'name' => '更新医院员工'] + $passwordFields) === [], 'Source write returned unexpected entity'); $post = $fake->last('auth.admin/edit'); verify($post['method'] === 'POST' && $post['data']['id'] === 2 && $post['data']['account'] === 'fixture-member', 'Edit changed source identity'); verify(!isset($post['data']['password']) && !isset($post['data']['password_confirm']), 'Blank password became a reset'); verify($post['data']['avatar'] === 'fixture-avatar' && $post['data']['jobs_id'] === [21], 'Hidden source fields were lost'); verify(end($fake->requests)['path'] === 'auth.admin/edit' && $fake->count('auth.admin/mySelf') === $beforeReads + 1, 'Successful write performed a fallible follow-up read'); $fake->failReads = $fake->failReadsAfterWrite = false; verify(password_verify('Fixture-old-123', $fake->users[2]['password']), 'Blank password changed source credential'); } // 管理员重置密码:真实中央序列化新密码到原 API;旧 bridge 与已签发 code 不能再发医院 ticket。 $otherMember = 'Bearer ' . $login('fixture-member'); $code = $issue($member); $issues = $fake->issues; $bridge->dispatch('admin.edit', $owner, ['id' => 2, 'password' => 'Fixture-reset-123']); $post = $fake->last('auth.admin/edit')['data']; verify($post['password'] === 'Fixture-reset-123' && $post['password_confirm'] === $post['password'], 'Password reset did not reach original API'); verify($post['id'] === 2 && $post['account'] === 'fixture-member', 'Password reset rebound source account'); denied(static fn () => $exchange($code), 401); verify($fake->issues === $issues, 'Revoked code minted a hospital ticket'); denied(static fn () => $bridge->dispatch('myself', $member), 401); denied(static fn () => $bridge->dispatch('myself', $otherMember), 401); denied(static fn () => $sessions->resolve($memberToken, $source->sourceKey()), 401); denied(static fn () => $login('fixture-member'), 401); $member = 'Bearer ' . $login('fixture-member', 'Fixture-reset-123'); verify($bridge->dispatch('myself', $member)['gid'] === $gid, 'Password reset changed GID'); // 调整成员角色走原用户 edit;角色授权走原 role edit,旧会话与 code 都依赖原撤销结果拒绝。 $code = $issue($member); $bridge->dispatch('admin.edit', $owner, ['id' => 2, 'role_id' => [8]]); verify($fake->last('auth.admin/edit')['data']['role_id'] === [8], 'Role assignment did not reach original account'); denied(static fn () => $exchange($code), 401); denied(static fn () => $bridge->dispatch('myself', $member), 401); $member = 'Bearer ' . $login('fixture-member', 'Fixture-reset-123'); $profile = $bridge->dispatch('myself', $member); verify($profile['role_id'] === [8] && $profile['permissions'] === [] && $profile['menus'] === [], 'New role did not immediately replace source permissions'); denied(static fn () => $bridge->dispatch('admin.lists', $member), 403); $bridge->dispatch('admin.edit', $owner, ['id' => 2, 'role_id' => [7]]); $member = 'Bearer ' . $login('fixture-member', 'Fixture-reset-123'); $code = $issue($member); $bridge->dispatch('role.edit', $owner, ['id' => 7, 'menu_id' => []]); $post = $fake->last('auth.role/edit')['data']; verify($post['id'] === 7 && $post['menu_id'] === [] && $post['data_scope'] === 3, 'Role revoke payload lost explicit empty grants or original scope'); denied(static fn () => $exchange($code), 401); denied(static fn () => $bridge->dispatch('myself', $member), 401); $member = 'Bearer ' . $login('fixture-member', 'Fixture-reset-123'); verify($bridge->dispatch('myself', $member)['permissions'] === [], 'Re-login reused stale source permissions'); $fake->roles[7]['menu_id'] = [101]; verify($bridge->dispatch('myself', $member)['permissions'] === ['auth.admin/lists'], 'Bridge cached a permission snapshot between requests'); $fake->roles[7]['menu_id'] = []; $reads = $fake->count('auth.admin/lists'); denied(static fn () => $bridge->dispatch('admin.lists', $member), 403); verify($fake->count('auth.admin/lists') === $reads, 'Stale permission reached original directory API'); $fake->roles[7]['menu_id'] = [101]; // 后续 SSO 场景恢复显式医院角色权限。 // 全局账号按源角色授权,当前公司选择和任职不增减权限。 $company = $bridge->dispatch('group.company.save', $owner, ['code' => 'other-co', 'name' => '其他公司']); $writes = $fake->count('auth.admin/edit'); $bridge->dispatch('admin.edit', $owner, ['id' => 2, 'name' => '全局角色授权修改'], [], $company['id']); $bridge->dispatch('group.member.save', $owner, ['company_id' => $company['id'], 'admin_id' => 1, 'member_status' => 1, 'can_login' => 1]); denied(static fn () => $bridge->dispatch('dept.lists', $member, [], [], $company['id']), 403); verify($fake->count('auth.admin/edit') === $writes + 1, 'Global account update must use the source role permission'); $bridge->dispatch('group.member.save', $owner, ['company_id' => 1, 'admin_id' => 1, 'member_status' => 0, 'can_login' => 0]); $bridge->dispatch('admin.edit', $owner, ['id' => 2, 'name' => '组织归属不改变角色授权']); verify($fake->count('auth.admin/edit') === $writes + 2, 'Membership incorrectly removed source role-authorized global write'); $bridge->dispatch('group.member.save', $owner, ['company_id' => 1, 'admin_id' => 1, 'member_status' => 1, 'can_login' => 1]); // GID 绑定 source_id;账号改名或权限变更不会改 GID,别的身份源不能复用这个映射库。 $bridge->dispatch('admin.edit', $owner, ['id' => 2, 'account' => 'fixture-renamed']); verify($bridge->dispatch('myself', $member)['gid'] === $gid, 'Account rename changed source-id GID mapping'); verify($store->identity(1)['gid'] !== $gid, 'Different source IDs share a GID'); denied(static fn () => new GroupStore(hash('sha256', 'other-isolated-source')), 503); // 本人改密专用原端点与所有本地 bridge 的显式撤销。 $memberToken = $login('fixture-renamed', 'Fixture-reset-123'); $member = 'Bearer ' . $memberToken; $anotherToken = $login('fixture-renamed', 'Fixture-reset-123'); $code = $issue($member); $bridge->dispatch('password', $member, ['old_password' => 'Fixture-reset-123', 'password' => 'Fixture-own-123', 'password_confirm' => 'Fixture-own-123']); verify($fake->last('identity.session/password')['data']['old_password'] === 'Fixture-reset-123', 'Own password change omitted original-password verification'); denied(static fn () => $sessions->resolve($memberToken, $source->sourceKey()), 401); denied(static fn () => $sessions->resolve($anotherToken, $source->sourceKey()), 401); denied(static fn () => $exchange($code), 401); denied(static fn () => $login('fixture-renamed', 'Fixture-reset-123'), 401); verify($bridge->dispatch('myself', 'Bearer ' . $login('fixture-renamed', 'Fixture-own-123'))['gid'] === $gid, 'Own password change rebound identity'); echo 'PASS group-write-through: ' . $checks . " checks; actual central services, isolated source transport and temporary stores.\n"; } catch (Throwable $error) { // 不输出上下游载荷、凭据、会话或堆栈;只保留人工编写的断言信息。 $message = $error instanceof RuntimeException && get_class($error) === RuntimeException::class ? $error->getMessage() : 'Unexpected isolated test failure (' . get_class($error) . ', line ' . $error->getLine() . ')'; file_put_contents('php://stderr', 'FAIL group-write-through: ' . $message . "\n"); exit(1); } ` test('集团密码与角色写穿原系统、旧会话/SSO 拒绝及公司边界', { timeout: 30_000 }, async () => { const runtime = await mkdtemp(join(tmpdir(), 'iam-group-write-through-')) const env = Object.fromEntries(Object.entries(process.env).filter(([key]) => !key.startsWith('IAM_'))) Object.assign(env, { GROUP_BRIDGE_PROJECT_ROOT: fileURLToPath(new URL('../', import.meta.url)), IAM_GROUP_ENABLED: '1', IAM_GROUP_OWNER_IDS: '1', IAM_RUNTIME_PATH: runtime, IAM_GROUP_DB_PATH: join(runtime, 'group.sqlite'), IAM_HOSPITAL_BASE_URL: 'http://127.0.0.1:18090/admin', }) try { const result = spawnSync(process.env.IAM_TEST_PHP || 'php', ['-d', 'extension=pdo_sqlite'], { input: fixture, encoding: 'utf8', env, windowsHide: true, timeout: 25_000, }) assert.ifError(result.error) assert.equal(result.status, 0, `${result.stdout}${result.stderr}`) assert.match(result.stdout, /PASS group-write-through: \d+ checks/) process.stdout.write(result.stdout) } finally { assert.equal(dirname(resolve(runtime)), resolve(tmpdir()), 'Cleanup must remain inside the system temporary directory') assert.ok(basename(runtime).startsWith('iam-group-write-through-'), 'Cleanup must target this test run') await rm(runtime, { recursive: true, force: true }) } })