Files
zyt/identity-admin/tests/role-access.test.mjs
T
2026-11-11 13:53:14 +08:00

182 lines
16 KiB
JavaScript

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'
const fixture = String.raw`<?php
declare(strict_types=1);
function env(string $key, mixed $default = null): mixed { return $default; }
require getenv('ROLE_ACCESS_PROJECT_ROOT') . '/server/vendor/autoload.php';
use app\exception\ApiError;
use app\service\group\GroupService;
use app\service\group\GroupStore;
use app\service\group\RoleAccessService;
use app\service\shared\SessionStore;
use app\service\shared\SourceApiClient;
$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 $e) { verify($e->status === $status, 'Unexpected status ' . $e->status . ' expected ' . $status); return; } throw new RuntimeException('Expected rejection'); }
function flat(array $nodes): array { $result = []; foreach ($nodes as $node) { $result[] = $node; array_push($result, ...flat($node['children'] ?? [])); } return $result; }
$source = new class extends SourceApiClient {
public function __construct() {}
public function sourceKey(): string { return hash('sha256', 'isolated-role-source'); }
public function request(string $method, string $path, array $data = [], string $token = ''): array { throw new RuntimeException('Role access test must not contact source records'); }
};
$store = new GroupStore($source->sourceKey());
$sessions = new SessionStore(getenv('IAM_RUNTIME_PATH') . '/sessions');
$group = new GroupService($source, $sessions, $store);
$base = ['id' => 2, 'is_root' => 0, 'permissions' => [], 'menus' => [], 'role_id' => [], 'disable' => 0];
$owner = array_replace($base, ['id' => 1, 'is_root' => 1, 'permissions' => ['*']]);
$ordinaryRoot = array_replace($base, ['is_root' => 1, 'permissions' => ['*']]);
$roleEditor = array_replace($base, ['id' => 3, 'permissions' => ['auth.role/edit', 'auth.role/lists']]);
$company = static fn (string $code, int $parent = 0): array => $group->dispatch('group.company.save', $owner, [], '', ['code' => $code, 'name' => $code, 'parent_id' => $parent], []);
$a = $company('alpha'); $b = $company('beta'); $child = $company('child', $a['id']);
$create = static function (string $name, array $data = [], int $company = 2, string $kind = 'menu') use ($group, $owner): array {
$group->dispatchStructure($kind . '.add', $owner, $company, ['name' => $name] + $data, []);
foreach (flat($group->dispatchStructure($kind . '.lists', $owner, $company, [], [])) as $row) { if ($row['name'] === $name) { return $row; } }
throw new RuntimeException('Created node missing');
};
try {
$parent = $create('目录', ['type' => 'M', 'perms' => 'company.alpha.not-inherited']);
$read = $create('部门读取', ['type' => 'C', 'pid' => $parent['id'], 'perms' => 'company.alpha.dept.dept/lists', 'component' => 'system/depts', 'paths' => 'https://attacker.invalid']);
$add = $create('部门新增', ['type' => 'A', 'pid' => $read['id'], 'perms' => 'company.alpha.dept.dept/add']);
$menu = $create('菜单读取', ['type' => 'C', 'perms' => 'company.alpha.auth.menu/lists', 'component' => 'system/menus']);
$custom = $create('自建业务', ['type' => 'C', 'perms' => 'company.alpha.custom/list', 'component' => '../../unsafe', 'paths' => 'javascript:alert(1)', 'params' => '{"redirect":"https://attacker.invalid"}']);
$bpage = $create('乙公司', ['type' => 'C', 'perms' => 'company.beta.custom/list'], $b['id']);
$dept = $create('真实部门', [], $a['id'], 'dept');
$group->replaceRoleNativeMenus($roleEditor, 11, [$read['id'], $custom['id']]);
$group->replaceRoleNativeMenus($roleEditor, 12, [$add['id'], $menu['id']]);
$actor = array_replace($base, ['role_id' => [11, 12]]);
$enriched = $group->enrich($actor);
verify($enriched['source_permissions'] === [] && count($enriched['native_permissions']) === 4, 'Role union mixed source and native permissions');
verify(!in_array('company.alpha.not-inherited', $enriched['permissions'], true), 'Parent display implicitly granted a permission');
verify($enriched['native_company_ids'] === [$a['id']], 'Company scope not derived from effective roles');
$nav = flat($enriched['native_menus']);
verify(count(array_filter($nav, static fn ($row) => $row['type'] === 'A')) === 1, 'Full authorization tree omitted operation buttons');
foreach ($nav as $node) {
verify($node['native'] && $node['company_id'] === $a['id'], 'Native navigation lost company anchor');
verify(str_starts_with($node['paths'], '/company/2/menu/'), 'Stored URL executed as navigation');
verify(in_array($node['component'], ['', 'system/depts', 'system/menus', 'common/custom'], true), 'Unsafe component executed');
verify($node['params'] === '' && $node['selected'] === '', 'Stored routing configuration escaped projection');
}
$byName = array_column($nav, null, 'name');
verify($byName['自建业务']['component'] === 'common/custom' && $byName['部门读取']['component'] === 'system/depts', 'Safe projection incorrect');
verify($byName['目录']['perms'] === '' && $byName['目录']['type'] === 'M', 'Ungrant parent turned into executable page');
verify($group->enrich($enriched)['permissions'] === $enriched['permissions'] && $group->enrich($enriched)['menus'] === $enriched['menus'], 'Enrichment duplicated grants');
$store->execute('UPDATE company_structure_node SET is_show=0 WHERE id=?', [$parent['id'] - RoleAccessService::ID_OFFSET]);
$hiddenTree = flat($group->enrich($actor)['native_menus']);
$hiddenParent = array_values(array_filter($hiddenTree, static fn ($row) => $row['id'] === $parent['id']))[0] ?? null;
verify($hiddenParent !== null && $hiddenParent['is_show'] === 0 && $hiddenParent['type'] === 'M', 'Hidden display ancestor lost its authorized descendants');
verify(in_array($read['id'], array_column($hiddenTree, 'id'), true) && in_array($add['id'], array_column($hiddenTree, 'id'), true), 'Hidden ancestor removed direct-page or operation authorization nodes');
$store->execute('UPDATE company_structure_node SET is_show=1 WHERE id=?', [$parent['id'] - RoleAccessService::ID_OFFSET]);
verify(count($group->dispatchStructure('dept.lists', $actor, $a['id'], [], [])) === 1, 'Role read requires company membership');
$group->dispatchStructure('dept.add', $actor, $a['id'], ['name' => '可新增'], []);
denied(fn () => $group->dispatchStructure('dept.edit', $actor, $a['id'], ['id' => $dept['id'], 'name' => '禁止编辑'], []), 403);
denied(fn () => $group->dispatchStructure('dept.lists', $actor, $b['id'], [], []), 403);
$group->dispatch('group.company.save', $owner, [], '', ['id' => $b['id'], 'name' => $a['name'], 'parent_id' => 0, 'disable' => 0], []);
denied(fn () => $group->dispatchStructure('dept.lists', $actor, $b['id'], [], []), 403);
denied(fn () => $group->dispatchStructure('dept.lists', $ordinaryRoot, $a['id'], [], []), 403);
verify(!$group->enrich($ordinaryRoot)['is_group_admin'] && $group->enrich($ordinaryRoot)['native_menus'] === [], 'Hospital root automatically became native owner');
$store->identity(2);
$store->execute('INSERT INTO membership(company_id,source_id,member_status,can_login,update_time) VALUES(?,2,0,0,?)', [$a['id'], time()]);
verify(count($group->dispatchStructure('dept.lists', $actor, $a['id'], [], [])) === 2, 'Revoked company membership revoked role menu');
$context = $group->context($actor);
verify(array_column($context['companies'], 'id') === [$a['id']], 'Company context leaked membership or ungranted company');
verify(in_array('dept.add', $context['companies'][0]['structure_permissions'], true) && !in_array('dept.edit', $context['companies'][0]['structure_permissions'], true), 'Context capabilities not exact role operations');
$grants = $group->roleNativeMenuIdsForRoles($roleEditor, [11, 12, 99]);
verify(count($grants[11]) === 2 && count($grants[12]) === 2 && $grants[99] === [], 'Bulk role grant loading failed');
$grantTree = flat($group->roleMenuTree($roleEditor));
verify(in_array($bpage['id'], array_column($grantTree, 'id'), true), 'Role editor cannot select another company explicitly');
foreach ($grantTree as $node) { verify(is_int($node['id']) && $node['id'] > RoleAccessService::ID_OFFSET, 'Fake company ID entered grant tree'); }
denied(fn () => $group->roleMenuTree(array_replace($actor, ['permissions' => ['auth.menu/lists']])), 403);
denied(fn () => $group->replaceRoleNativeMenus($actor, 11, [$read['id']]), 403);
foreach ([[$dept['id']], [101], [RoleAccessService::ID_OFFSET], [9007199254740991]] as $ids) { denied(fn () => $group->replaceRoleNativeMenus($roleEditor, 11, $ids), 422); }
verify($group->roleNativeMenuIds($roleEditor, 11) === $grants[11], 'Rejected grant mutation removed old grants');
$group->clearRoleNativeMenus($roleEditor, 11);
denied(fn () => $group->dispatchStructure('dept.lists', $enriched, $a['id'], [], []), 403);
$fresh = $group->enrich($enriched);
verify(!in_array('company.alpha.dept.dept/lists', $fresh['permissions'], true), 'Stale enriched native permission survived revoke');
verify(in_array('company.alpha.dept.dept/add', $fresh['permissions'], true), 'Revoking one role removed another role');
$group->replaceRoleNativeMenus($roleEditor, 11, [$read['id'], $custom['id']]);
$store->execute('UPDATE company_structure_node SET pid=? WHERE id=?', [$bpage['id'] - RoleAccessService::ID_OFFSET, $read['id'] - RoleAccessService::ID_OFFSET]);
denied(fn () => $group->dispatchStructure('dept.lists', $actor, $a['id'], [], []), 403);
$store->execute('UPDATE company_structure_node SET pid=? WHERE id=?', [$parent['id'] - RoleAccessService::ID_OFFSET, $read['id'] - RoleAccessService::ID_OFFSET]);
$store->execute('UPDATE company_structure_node SET pid=? WHERE id=?', [$read['id'] - RoleAccessService::ID_OFFSET, $parent['id'] - RoleAccessService::ID_OFFSET]);
denied(fn () => $group->dispatchStructure('dept.lists', $actor, $a['id'], [], []), 403);
$store->execute('UPDATE company_structure_node SET pid=0 WHERE id=?', [$parent['id'] - RoleAccessService::ID_OFFSET]);
$store->execute('UPDATE company_structure_node SET perms=? WHERE id=?', ['company.beta.dept.dept/lists', $read['id'] - RoleAccessService::ID_OFFSET]);
denied(fn () => $group->dispatchStructure('dept.lists', $actor, $a['id'], [], []), 403);
$store->execute('UPDATE company_structure_node SET perms=? WHERE id=?', ['company.alpha.dept.dept/lists', $read['id'] - RoleAccessService::ID_OFFSET]);
$group->dispatchStructure('menu.edit', $owner, $a['id'], ['id' => $parent['id'], 'disable' => 1], []);
denied(fn () => $group->dispatchStructure('dept.lists', $actor, $a['id'], [], []), 403);
denied(fn () => $group->validateRoleNativeMenuIds($roleEditor, [$read['id']]), 422);
verify(in_array($read['id'], $group->roleNativeMenuIds($roleEditor, 11), true), 'Disabling menu erased persistent role grant');
$group->validateRoleNativeMenuIds($roleEditor, [$read['id'], $custom['id']], 11);
$group->clearRoleNativeMenus($roleEditor, 11);
$group->replaceRoleNativeMenus($roleEditor, 11, [$read['id'], $custom['id']]);
verify($group->roleNativeMenuIds($roleEditor, 11) === $grants[11], 'Trusted existing disabled grant was not retained across fail-closed clearing');
denied(fn () => $group->validateRoleNativeMenuIds($roleEditor, [$read['id']], 99), 422);
denied(fn () => $group->dispatchStructure('dept.lists', $actor, $a['id'], [], []), 403);
$group->dispatchStructure('menu.edit', $owner, $a['id'], ['id' => $parent['id'], 'disable' => 0], []);
$group->dispatch('group.company.save', $owner, [], '', ['id' => $a['id'], 'name' => '停用公司', 'parent_id' => 0, 'disable' => 1], []);
denied(fn () => $group->dispatchStructure('dept.lists', $actor, $a['id'], [], []), 403);
denied(fn () => $group->validateRoleNativeMenuIds($roleEditor, [$custom['id']]), 422);
verify($group->enrich($actor)['native_permissions'] === [], 'Disabled company still grants permissions');
$group->dispatch('group.company.save', $owner, [], '', ['id' => $a['id'], 'name' => '恢复公司', 'parent_id' => 0, 'disable' => 0], []);
$childPage = $create('子公司页面', ['type' => 'C', 'perms' => 'company.child.dept.dept/lists', 'component' => 'system/depts'], $child['id']);
$group->replaceRoleNativeMenus($roleEditor, 13, [$childPage['id']]);
$childActor = array_replace($actor, ['role_id' => [13]]);
verify($group->enrich($childActor)['native_company_ids'] === [$child['id']], 'Child company implicitly granted its parent company');
$group->dispatch('group.company.save', $owner, [], '', ['id' => $a['id'], 'name' => '停用祖先', 'parent_id' => 0, 'disable' => 1], []);
denied(fn () => $group->dispatchStructure('dept.lists', $childActor, $child['id'], [], []), 403);
verify($group->enrich($childActor)['native_permissions'] === [], 'Disabled company ancestor kept descendant grants effective');
$group->dispatch('group.company.save', $owner, [], '', ['id' => $a['id'], 'name' => '恢复祖先', 'parent_id' => 0, 'disable' => 0], []);
$store->execute("CREATE TRIGGER role_audit_failure BEFORE INSERT ON group_audit WHEN NEW.action='role.native-menu.replace' BEGIN SELECT RAISE(ABORT,'isolated audit failure'); END");
try { $group->replaceRoleNativeMenus($roleEditor, 11, [$menu['id']]); throw new RuntimeException('Audit did not fail'); }
catch (PDOException $error) { verify($group->roleNativeMenuIds($roleEditor, 11) === $grants[11], 'Role grants did not roll back with audit'); }
$store->execute('DROP TRIGGER role_audit_failure');
$restart = new GroupService($source, $sessions, new GroupStore($source->sourceKey()));
verify($restart->roleNativeMenuIds($roleEditor, 11) === $grants[11], 'Role grants did not persist');
$group->dispatchStructure('menu.delete', $owner, $a['id'], ['id' => $custom['id']], []);
verify($group->roleNativeMenuIds($roleEditor, 11) === [$read['id']], 'Deleted menu left stale grant');
$hospital = array_replace($actor, ['source_permissions' => ['auth.admin/lists']]);
$store->execute('UPDATE membership SET member_status=0,can_login=0 WHERE company_id=1 AND source_id=2');
$group->requireDirectory($hospital, 1);
$challenge = str_repeat('x', 43);
$authorization = ['client_id' => 'internet-hospital', 'redirect_uri' => GroupService::hospitalEntry(), 'state' => str_repeat('s', 32), 'code_challenge' => $challenge, 'code_challenge_method' => 'S256'];
verify(isset($group->dispatch('group.sso.authorize', $hospital, [], 'isolated-session', $authorization, [])['redirect_url']), 'Membership still gates hospital role access');
denied(fn () => $group->dispatch('group.sso.authorize', $group->enrich($actor), [], 'isolated-session', $authorization, []), 403);
verify($group->context($base)['companies'] === [], 'No-role user receives company menus by default');
echo 'PASS role-access: ' . $checks . " checks; temporary SQLite and synthetic profiles only.\n";
} catch (Throwable $error) {
fwrite(STDERR, 'FAIL role-access: ' . get_class($error) . ': ' . $error->getMessage() . ' at line ' . $error->getLine() . "\n");
exit(1);
}
`
test('源角色显式跨公司授权、多角色并集、撤权即时生效及安全菜单投影', { timeout: 30_000 }, async () => {
const runtime = await mkdtemp(join(tmpdir(), 'iam-role-access-'))
const env = Object.fromEntries(Object.entries(process.env).filter(([key]) => !key.startsWith('IAM_')))
Object.assign(env, {
ROLE_ACCESS_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:19999/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 role-access: \d+ checks/)
process.stdout.write(result.stdout)
} finally {
assert.equal(dirname(resolve(runtime)), resolve(tmpdir()))
assert.ok(basename(runtime).startsWith('iam-role-access-'))
await rm(runtime, { recursive: true, force: true })
}
})