import assert from 'node:assert/strict'; import { spawn } from 'node:child_process'; import { once } from 'node:events'; import { mkdtemp, rm } from 'node:fs/promises'; import { createServer } from 'node:net'; import { tmpdir } from 'node:os'; import { dirname, join, resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; import test from 'node:test'; import { createSharedUpstream, fixturePassword, replacementPassword, flattenTree } from './shared-upstream.mjs'; const project = resolve(dirname(fileURLToPath(import.meta.url)), '..'); const php = process.env.IAM_TEST_PHP || 'php'; const sourceLoginUrl = 'https://fixture.invalid/original-admin/login'; const validationStatuses = [400, 409, 422]; const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); async function unusedPort() { const socket = createServer(); socket.listen(0, '127.0.0.1'); await once(socket, 'listening'); const { port } = socket.address(); await new Promise((resolve, reject) => socket.close((error) => error ? reject(error) : resolve())); return port; } async function startBridge(upstream, runtime) { const port = await unusedPort(); // Do not inherit any live database, source URL, or session configuration. const env = Object.fromEntries(Object.entries(process.env).filter(([key]) => !key.startsWith('IAM_'))); Object.assign(env, { IAM_DATA_MODE: 'shared', IAM_SOURCE_API_URL: upstream.url, IAM_GROUP_ENABLED: '0', IAM_SOURCE_LOGIN_URL: sourceLoginUrl, IAM_RUNTIME_PATH: runtime, IAM_DB_PATH: join(runtime, 'must-not-use-standalone.sqlite'), APP_DEBUG: '0', }); const child = spawn(php, ['-d', 'extension=pdo_sqlite', '-S', `127.0.0.1:${port}`, '-t', 'public', resolve(project, 'tests/isolated-api-router.php')], { cwd: join(project, 'server'), env, windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'], }); let startupError; child.once('error', (error) => { startupError = error; }); // Drain process pipes without ever printing private source responses or tokens. child.stdout.resume(); child.stderr.resume(); const base = `http://127.0.0.1:${port}/adminapi`; async function close() { if (child.exitCode !== null || child.signalCode !== null || startupError) return; const stopped = once(child, 'exit'); child.kill(); await stopped; } try { for (let attempt = 0; attempt < 100; attempt += 1) { if (startupError) throw new Error('Cannot launch PHP; set IAM_TEST_PHP to a PHP 8.2+ executable.'); if (child.exitCode !== null) throw new Error(`Isolated PHP test server exited before startup (exit ${child.exitCode}).`); try { const response = await fetch(`${base}/health`, { redirect: 'error', signal: AbortSignal.timeout(300) }); if (response.status === 200) return { base, close }; } catch { /* Allow the isolated server to finish binding. */ } await sleep(100); } throw new Error('Isolated PHP test server did not become ready; check PHP extensions and independent vendor dependencies.'); } catch (error) { await close(); throw error; } } function success(result) { assert.equal(result.status, 200, `${result.method} ${result.path}: expected HTTP 200`); assert.equal(result.envelope.code, 1, `${result.method} ${result.path}: expected a successful envelope`); return result.envelope.data; } function failure(result, statuses) { assert.ok(statuses.includes(result.status), `${result.method} ${result.path}: HTTP ${result.status}; expected ${statuses.join('/')}`); assert.equal(result.envelope.code, 0, `${result.method} ${result.path}: expected an error envelope`); } function numericIds(value) { assert.ok(Array.isArray(value), 'Expected a numeric ID array'); for (const id of value) assert.equal(typeof id, 'number', 'Bridge relation IDs must be numeric'); return [...value].sort((left, right) => left - right); } test('shared mode uses an isolated original-API fixture', { concurrency: false, timeout: 120_000 }, async (t) => { const runtime = await mkdtemp(join(tmpdir(), 'identity-admin-shared-')); const upstream = await createSharedUpstream(); let bridge; try { bridge = await startBridge(upstream, runtime); async function request(path, { method = 'GET', token, body } = {}) { assert.ok(path && !path.startsWith('/') && !path.includes('://'), 'Use a relative test API path'); const response = await fetch(`${bridge.base}/${path}`, { method, redirect: 'error', signal: AbortSignal.timeout(10_000), headers: { Accept: 'application/json', ...(body === undefined ? {} : { 'Content-Type': 'application/json' }), ...(token ? { Authorization: `Bearer ${token}` } : {}), }, ...(body === undefined ? {} : { body: JSON.stringify(body) }), }); const text = await response.text(); for (const secret of upstream.state.sensitiveValues) { assert.ok(!text.includes(secret), 'A private source credential escaped into a browser response'); } let envelope; try { envelope = JSON.parse(text); } catch { assert.fail(`${method} ${path}: bridge returned non-JSON (HTTP ${response.status})`); } assert.ok(envelope && typeof envelope === 'object' && !Array.isArray(envelope), 'Expected a response envelope'); return { status: response.status, envelope, method, path }; } async function login(account = 'OriginalRoot', password = fixturePassword) { const data = success(await request('login/account', { method: 'POST', body: { account, password } })); assert.equal(typeof data?.token, 'string', 'Login must return a bridge token'); assert.ok(data.token.length >= 32, 'Bridge sessions need an unguessable random token'); assert.ok(!upstream.state.sessions.has(data.token), 'The browser must never receive a source token'); return data.token; } async function prepare(account = 'OriginalRoot') { upstream.reset(); return login(account); } await t.test('health advertises shared mode and refuses old demo or missing sessions', async () => { const data = success(await request('health')); assert.equal(data.project, 'identity-admin'); assert.equal(data.data_mode, 'shared'); assert.equal(data.source_login_url, sourceLoginUrl); for (const token of [undefined, 'a'.repeat(64), 'unknown-bridge-session']) { failure(await request('auth.admin/mySelf', { token }), [401]); } assert.equal(upstream.state.log.length, 0, 'Unrecognized bridge tokens must not be forwarded to the source'); }); await t.test('original case-sensitive login produces independent sessions and forces terminal=1', async () => { upstream.reset(); failure(await request('login/account', { method: 'POST', body: { account: 'originalroot', password: fixturePassword }, }), [401]); failure(await request('login/account', { method: 'POST', body: { account: 'OriginalRoot', password: 'deliberately-wrong-password' }, }), [401]); const first = await login(); const second = await login(); assert.ok(first !== second, 'Separate logins must receive separate bridge tokens'); const loginRequest = upstream.last('identity.session/login'); assert.equal(loginRequest.body.account, 'OriginalRoot', 'Account case must reach the original API unchanged'); assert.equal(Number(loginRequest.body.terminal), 1); const loginCount = upstream.requests('identity.session/login').length; assert.ok(upstream.requests('identity.session/login').every((entry) => Number(entry.body.terminal) === 1)); for (const terminal of [1, 11]) { failure(await request('login/account', { method: 'POST', body: { account: 'OriginalRoot', password: fixturePassword, terminal }, }), [422]); } assert.equal(upstream.requests('identity.session/login').length, loginCount, 'Browser terminal overrides must not reach the source'); const self = success(await request('auth.admin/mySelf', { token: first })); assert.equal(self.account, 'OriginalRoot'); assert.equal(Number(self.id), 1); assert.equal(Number(self.is_root), 1); assert.deepEqual(numericIds(self.role_id), [7]); assert.deepEqual(numericIds(self.dept_id), [11]); assert.equal(self.data_mode, 'shared'); assert.equal(self.requires_password_change, false); assert.equal(self.requires_wecom_binding, false); assert.equal(self.source_login_url, sourceLoginUrl); assert.ok(self.permissions.includes('*')); assert.ok(upstream.last('auth.admin/mySelf').hasTokenHeader, 'Source authentication uses its token header'); assert.equal(upstream.last('auth.admin/mySelf').hasAuthorizationHeader, false); }); await t.test('root navigation contains exactly the four local module projections', async () => { const token = await prepare(); const businessPage = structuredClone(upstream.state.menus.find((row) => row.id === 110)); upstream.state.menus.unshift({ ...businessPage, id: 90, name: '面诊进度', paths: 'mianzhen', component: 'doctor/progress', perms: 'auth.admin/lists' }); const sourceMenus = structuredClone(upstream.state.menus); const self = success(await request('auth.admin/mySelf', { token })); const pages = flattenTree(self.menus).filter((row) => row.type === 'C'); assert.deepEqual(pages.map((row) => [row.paths, row.component]).sort(), [ ['/system/depts', 'system/depts'], ['/system/menus', 'system/menus'], ['/system/roles', 'system/roles'], ['/system/users', 'system/users'], ]); assert.ok(!flattenTree(self.menus).some((row) => row.component === 'doctor/consultation/index')); assert.equal(pages.find((row) => row.paths === '/system/users').id, 101, 'Shared read permission must not turn a business page into account management'); assert.deepEqual(upstream.state.menus, sourceMenus, 'Navigation projection must never rewrite original menus'); assert.equal(upstream.state.log.filter((entry) => entry.method !== 'GET' && entry.path !== 'identity.session/login').length, 0); }); await t.test('the four management lists map live source fields and options retain disabled grants', async () => { const token = await prepare(); const users = success(await request('auth.admin/lists?page_no=1&page_size=100', { token })); assert.equal(users.count, upstream.state.users.length); const doctor = users.lists.find((row) => Number(row.id) === 3); assert.ok(doctor, 'A synthetic original user must appear in management'); assert.equal(doctor.account, 'OriginalDoctor'); assert.equal(Number(doctor.is_root), 0); assert.deepEqual(numericIds(doctor.role_id), [7]); assert.deepEqual(numericIds(doctor.dept_id), [11]); assert.deepEqual(doctor.role_names, ['临床医生']); assert.deepEqual(doctor.dept_names, ['总院']); const roles = success(await request('auth.role/lists?page_no=1&page_size=100', { token })); const role = roles.lists.find((row) => Number(row.id) === 7); assert.ok(role); assert.equal(Number(role.disable), 0, 'Original roles have no disabled state'); assert.equal(Number(role.data_scope), 3); assert.deepEqual(numericIds(role.menu_id), [101, 109]); const menus = flattenTree(success(await request('auth.menu/lists', { token }))); const medical = menus.find((row) => Number(row.id) === 110); assert.equal(medical.paths, 'doctor/consultation'); assert.equal(medical.component, 'doctor/consultation/index'); assert.equal(medical.perms, 'doctor.consultation/lists'); assert.equal(Number(menus.find((row) => Number(row.id) === 109).disable), 1); const depts = flattenTree(success(await request('auth.dept/lists', { token }))); assert.equal(Number(depts.find((row) => Number(row.id) === 11).disable), 0); assert.equal(Number(depts.find((row) => Number(row.id) === 12).disable), 1); assert.ok(upstream.requests('dept.dept/lists').length > 0, 'Department requests must use the original namespace'); const options = success(await request('auth/options', { token })); for (const field of ['roles', 'menus', 'depts']) assert.ok(Array.isArray(options[field])); assert.ok(flattenTree(options.menus).some((row) => Number(row.id) === 109), 'Existing disabled menu grants must remain representable'); }); await t.test('keyword and disabled filters apply before local pagination when the source ignores them', async () => { const token = await prepare(); const filtered = success(await request('auth.admin/lists?page_no=1&page_size=1&keyword=OriginalDoctor&disable=0', { token })); assert.equal(filtered.count, 1); assert.equal(filtered.lists.length, 1); assert.equal(filtered.lists[0].account, 'OriginalDoctor'); const empty = success(await request('auth.admin/lists?page_no=1&page_size=100&disable=1', { token })); assert.equal(empty.count, 0); assert.deepEqual(empty.lists, []); const roles = success(await request(`auth.role/lists?page_no=1&page_size=1&keyword=${encodeURIComponent('部门编辑角色')}`, { token })); assert.equal(roles.count, 1); assert.equal(roles.lists[0].name, '部门编辑角色'); const capped = success(await request('auth.admin/lists?page_no=1&page_size=9999', { token })); assert.ok(Number(capped.page_size) <= 100, 'Page size is capped at 100'); assert.ok(upstream.requests('auth.admin/lists').every((entry) => !entry.query.page_size || Number(entry.query.page_size) <= 100)); }); await t.test('every write is denied before the permissive source when original permission is absent', async () => { const token = await prepare('OriginalReader'); for (const kind of ['admin', 'role', 'menu', 'dept']) { for (const operation of ['add', 'edit', 'delete']) { const before = upstream.state.log.length; failure(await request(`auth.${kind}/${operation}`, { method: 'POST', token, body: { id: 3, name: '不得写入' } }), [403]); const called = upstream.state.log.slice(before); assert.ok(called.some((entry) => entry.path === 'auth.admin/mySelf'), 'Each protected request revalidates source identity'); assert.ok(!called.some((entry) => entry.path.endsWith(`/${operation}`)), 'Denied writes must not reach the original API'); } } upstream.state.permissionOverrides.set('OriginalReader', ['auth.admin/lists']); const self = success(await request('auth.admin/mySelf', { token })); assert.deepEqual(flattenTree(self.menus).filter((row) => row.type === 'C').map((row) => row.paths), ['/system/users']); failure(await request('auth.role/lists', { token }), [403]); }); await t.test('department permission aliases authorize only the granted original operation', async () => { const token = await prepare('DepartmentEditor'); const self = success(await request('auth.admin/mySelf', { token })); assert.ok(self.permissions.includes('auth.dept/lists')); assert.ok(self.permissions.includes('auth.dept/edit')); assert.ok(!self.permissions.includes('auth.dept/add')); const pages = flattenTree(self.menus).filter((row) => row.type === 'C'); assert.deepEqual(pages.map((row) => row.paths), ['/system/depts']); success(await request('auth.dept/lists', { token })); success(await request('auth.dept/edit', { method: 'POST', token, body: { id: 12, pid: 11, name: '更新分院', sort: 2, disable: 1 }, })); const edited = upstream.last('dept.dept/edit'); assert.ok(edited); assert.equal(edited.body.leader, '合成分院长'); assert.equal(edited.body.mobile, '13900000002'); assert.equal(Number(edited.body.status), 0); failure(await request('auth.dept/add', { method: 'POST', token, body: { pid: 11, name: '禁止新增', disable: 0 } }), [403]); assert.equal(upstream.requests('dept.dept/add').length, 0); }); await t.test('editing a user merges fresh original detail and preserves all hidden doctor fields', async () => { const token = await prepare(); const original = structuredClone(upstream.state.users.find((row) => row.id === 3)); success(await request('auth.admin/edit', { method: 'POST', token, body: { id: 3, account: 'OriginalDoctor', name: '更新医生', disable: 0, role_id: [7], dept_id: [11], password: '' }, })); assert.ok(upstream.requests('auth.admin/detail').length > 0, 'Preservation must read the current original detail'); const submitted = upstream.last('auth.admin/edit').body; const hidden = [ 'avatar', 'multipoint_login', 'jobs_id', 'gender', 'age', 'phone', 'title', 'department', 'specialty', 'education', 'experience', 'honors', 'license_no', 'qualification_images', 'enable_image_consult', 'enable_video_consult', 'enable_charge', ]; for (const field of hidden) { if (field === 'jobs_id') assert.deepEqual(submitted[field].map(Number), original[field].map(Number)); else if (typeof original[field] === 'number') assert.equal(Number(submitted[field]), original[field], `Hidden user field ${field} must survive an edit`); else assert.deepEqual(submitted[field], original[field], `Hidden user field ${field} must survive an edit`); } assert.equal(submitted.name, '更新医生'); assert.ok(!Object.hasOwn(submitted, 'password_hash'), 'Source hashes must not be written back as editable data'); assert.ok(!Object.hasOwn(submitted, 'token'), 'Source token fields must never be written back'); assert.ok(!Object.hasOwn(submitted, 'password') || submitted.password === '', 'Blank password must leave the source password unchanged'); }); await t.test('editing a source menu preserves relative paths, unknown components and hidden routing values', async () => { const token = await prepare(); const original = structuredClone(upstream.state.menus.find((row) => row.id === 110)); success(await request('auth.menu/edit', { method: 'POST', token, body: { id: 110, pid: 0, type: 'C', name: '更新原医疗页面', paths: original.paths, component: original.component, perms: original.perms, icon: '', sort: 8, is_show: 1, disable: 0, }, })); assert.ok(upstream.requests('auth.menu/detail').length > 0); const submitted = upstream.last('auth.menu/edit').body; for (const field of ['paths', 'component', 'perms', 'selected', 'params', 'is_cache']) { if (field === 'is_cache') assert.equal(Number(submitted[field]), original[field]); else assert.deepEqual(submitted[field], original[field], `Original routing field ${field} must be preserved`); } assert.equal(Number(submitted.is_disable), 0); assert.ok(!Object.hasOwn(submitted, 'disable'), 'The original menu status field is is_disable'); }); await t.test('role edits preserve data_scope when omitted, pass empty grants, and reject unsupported disable=1', async () => { const token = await prepare(); success(await request('auth.role/edit', { method: 'POST', token, body: { id: 7, name: '更新医生角色', desc: '保留范围', sort: 2, menu_id: [] }, })); const submitted = upstream.last('auth.role/edit').body; assert.equal(Number(submitted.data_scope), 3); assert.deepEqual(submitted.menu_id, [], 'Explicit empty authorization must reach the original API'); assert.ok(!Object.hasOwn(submitted, 'disable'), 'Original roles do not accept disable'); assert.deepEqual(upstream.state.roles.find((row) => row.id === 7).menu_id, []); success(await request('auth.role/edit', { method: 'POST', token, body: { id: 7, name: '更新医生角色', desc: '', sort: 2, menu_id: [101, 109], data_scope: 2 }, })); assert.equal(Number(upstream.last('auth.role/edit').body.data_scope), 2); const before = upstream.requests('auth.role/edit').length; failure(await request('auth.role/edit', { method: 'POST', token, body: { id: 7, name: '不可停用', desc: '', sort: 0, menu_id: [], disable: 1 }, }), validationStatuses); assert.equal(upstream.requests('auth.role/edit').length, before, 'Unsupported role state must not silently succeed upstream'); }); await t.test('unknown operations are 404 even when the original API would default-allow them', async () => { const token = await prepare(); for (const path of ['auth.admin/unknownOperation', 'auth.role/exportEverything', 'missing-shared-endpoint']) { failure(await request(path, { token }), [404]); assert.equal(upstream.requests(path).length, 0); } }); await t.test('source revocation is checked on every request and invalidates the bridge', async () => { const token = await prepare(); success(await request('auth.admin/mySelf', { token })); upstream.state.faults.set('auth.admin/mySelf', { code: -1, msg: '原会话已过期' }); failure(await request('auth.admin/lists', { token }), [401]); upstream.state.faults.delete('auth.admin/mySelf'); failure(await request('auth.admin/mySelf', { token }), [401]); assert.equal(upstream.requests('auth.admin/lists').length, 0); }); await t.test('first-password gate allows profile, password and logout while rejecting management', async () => { const token = await prepare('FirstPassword'); const self = success(await request('auth.admin/mySelf', { token })); assert.equal(self.requires_password_change, true); failure(await request('auth.admin/lists', { token }), [403]); failure(await request('auth/options', { token }), [403]); success(await request('auth.admin/password', { method: 'POST', token, body: { password: replacementPassword, password_confirm: replacementPassword }, })); assert.equal(upstream.requests('identity.session/password').length, 1); assert.equal(upstream.requests('login/changeFirstPassword').length, 0); assert.equal(upstream.requests('auth.admin/editSelf').length, 0); assert.equal(upstream.state.sessions.size, 0, 'First-password endpoint revokes original sessions atomically'); failure(await request('auth.admin/mySelf', { token }), [401]); const fresh = await login('FirstPassword', replacementPassword); assert.equal(success(await request('auth.admin/mySelf', { token: fresh })).requires_password_change, false); success(await request('login/logout', { method: 'POST', token: fresh })); }); await t.test('WeCom binding gate stays active and directs users to the original login', async () => { const token = await prepare('WecomBinding'); const self = success(await request('auth.admin/mySelf', { token })); assert.equal(self.requires_wecom_binding, true); assert.equal(self.source_login_url, sourceLoginUrl); failure(await request('auth.dept/lists', { token }), [403]); failure(await request('auth.admin/edit', { method: 'POST', token, body: { id: 3, name: '禁止变更' } }), [403]); assert.equal(upstream.requests('auth.admin/edit').length, 0); success(await request('login/logout', { method: 'POST', token })); failure(await request('auth.admin/mySelf', { token }), [401]); }); await t.test('logout revokes both original and current bridge sessions and leaves another login valid', async () => { const token = await prepare(); const another = await login(); assert.equal(upstream.state.sessions.size, 2); success(await request('login/logout', { method: 'POST', token })); const logout = upstream.last('identity.session/logout'); assert.ok(logout); assert.equal(Number(logout.body.all), 0); assert.equal(upstream.state.sessions.size, 1); failure(await request('auth.admin/mySelf', { token }), [401]); success(await request('auth.admin/mySelf', { token: another })); }); await t.test('normal password changes use the atomic original endpoint and revoke all sessions', async () => { const token = await prepare(); const another = await login(); const original = structuredClone(upstream.state.users.find((row) => row.id === 1)); failure(await request('auth.admin/password', { method: 'POST', token, body: { old_password: 'synthetic-wrong-old-password', password: replacementPassword, password_confirm: replacementPassword }, }), [422]); assert.equal(upstream.state.sessions.size, 2, 'Rejected password changes must preserve both existing sessions'); success(await request('auth.admin/mySelf', { token })); success(await request('auth.admin/password', { method: 'POST', token, body: { old_password: fixturePassword, password: replacementPassword, password_confirm: replacementPassword }, })); const edit = upstream.last('identity.session/password'); assert.ok(edit); assert.equal(upstream.state.users.find((row) => row.id === 1).name, original.name); assert.equal(upstream.state.users.find((row) => row.id === 1).avatar, original.avatar); assert.ok(Object.hasOwn(edit.body, 'old_password'), 'Normal password changes must verify the original password'); assert.ok(Object.hasOwn(edit.body, 'password_confirm')); assert.equal(upstream.requests('auth.admin/editSelf').length, 0); assert.equal(upstream.requests('identity.session/logout').length, 0, 'Password and revocation use a single atomic source operation'); assert.equal(upstream.state.sessions.size, 0); for (const stale of [token, another]) failure(await request('auth.admin/mySelf', { token: stale }), [401]); failure(await request('login/account', { method: 'POST', body: { account: 'OriginalRoot', password: fixturePassword } }), [401]); await login('OriginalRoot', replacementPassword); }); await t.test('source validation and permission envelope codes map to 422 and 403', async () => { const token = await prepare(); for (const [code, status] of [[0, 422], [10, 403], [-1, 401]]) { upstream.state.faults.set('auth.role/lists', { code, msg: '合成源拒绝' }); failure(await request('auth.role/lists', { token }), [status]); } upstream.state.faults.clear(); upstream.state.faults.set('identity.session/login', { code: 10, msg: '请完成企业微信绑定' }); failure(await request('login/account', { method: 'POST', body: { account: 'OriginalRoot', password: fixturePassword } }), [403]); }); await t.test('non-JSON, invalid protocol, redirects and network failures return sanitized 502', async () => { const token = await prepare(); for (const kind of ['non-json', 'protocol', 'redirect', 'network']) { upstream.state.faults.set('auth.role/lists', { kind }); const result = await request('auth.role/lists', { token }); failure(result, [502]); assert.ok(!JSON.stringify(result.envelope).includes('synthetic private upstream diagnostic'), 'Private upstream diagnostics must not be exposed'); upstream.state.faults.clear(); } }); } finally { if (bridge) await bridge.close(); await upstream.close(); // The directory was created by mkdtemp above; never remove a user runtime. assert.ok(resolve(runtime).startsWith(resolve(tmpdir()) + '\\') || resolve(runtime).startsWith(resolve(tmpdir()) + '/')); await rm(runtime, { recursive: true, force: true }); } });