Files
zyt/server/tests/GroupReadonlyPermissionTest.php
2026-11-11 13:53:14 +08:00

146 lines
9.3 KiB
PHP

<?php
declare(strict_types=1);
use app\adminapi\http\middleware\AuthMiddleware;
use app\adminapi\logic\auth\AuthLogic;
use app\common\enum\AdminTerminalEnum;
use app\common\service\DataScope\DataScopeService;
use think\facade\Db;
require dirname(__DIR__) . '/vendor/autoload.php';
require_once dirname(__DIR__) . '/vendor/topthink/framework/src/helper.php';
$checks = 0;
$scenarios = 0;
function readonlyCheck(bool $ok, string $message): void
{
global $checks;
if (!$ok) { throw new RuntimeException($message); }
++$checks;
}
try {
if (!extension_loaded('pdo_sqlite')) { throw new RuntimeException('pdo_sqlite is required'); }
$runtime = sys_get_temp_dir() . '/group-readonly-permission-' . bin2hex(random_bytes(10));
if (!mkdir($runtime, 0700, true)) { throw new RuntimeException('Could not create isolated runtime'); }
$app = new class(dirname(__DIR__) . DIRECTORY_SEPARATOR) extends think\App {
public bool $environmentLoadSkipped = false;
public function loadEnv(string $envName = ''): void
{
// This test must never load the real server/.env.
$this->environmentLoadSkipped = true;
}
};
$app->setRuntimePath($runtime . DIRECTORY_SEPARATOR);
$app->initialize();
$app->config->set(['default' => 'readonly_fixture', 'auto_timestamp' => true,
'connections' => ['readonly_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(['data_scope' => ['enabled' => true, 'no_dept_fallback_self' => true, 'exempt_roles' => []]], 'project');
// Synthetic identity represents an employee whose login gates are already satisfied.
// This does not change the real environment or test first-password/WeCom/SSO behavior.
$app->env->set(['WORK_WECHAT_FORCE_BIND_LOGIN' => 'false', 'APP_DEBUG' => false]);
readonlyCheck($app->environmentLoadSkipped, 'Real environment loading was not disabled');
readonlyCheck($app->config->get('database.connections.readonly_fixture.type') === 'sqlite'
&& count($app->config->get('database.connections')) === 1, 'Database is not isolated SQLite');
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,type TEXT,name TEXT,perms TEXT,is_disable INTEGER DEFAULT 0)');
Db::execute('CREATE TABLE f_system_role_menu (role_id INTEGER,menu_id INTEGER,PRIMARY KEY(role_id,menu_id))');
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_dept (id INTEGER PRIMARY KEY,pid INTEGER,name TEXT,status INTEGER)');
$adminId = 7001;
$roleId = 9001;
Db::name('system_role')->insert(['id' => $roleId, 'name' => 'fixture-readonly', 'data_scope' => 4]);
// Original non-personal menu IDs and permission strings; denied routes remain registered.
Db::name('system_menu')->insertAll([
['id' => 6, 'pid' => 4, 'type' => 'C', 'name' => 'menu-list', 'perms' => 'auth.menu/lists'],
['id' => 8, 'pid' => 4, 'type' => 'C', 'name' => 'role-list', 'perms' => 'auth.role/lists'],
['id' => 25, 'pid' => 0, 'type' => 'M', 'name' => 'organization', 'perms' => ''],
['id' => 26, 'pid' => 25, 'type' => 'C', 'name' => 'department-list', 'perms' => 'dept.dept/lists'],
['id' => 45, 'pid' => 26, 'type' => 'A', 'name' => 'department-add', 'perms' => 'dept.dept/add'],
['id' => 46, 'pid' => 26, 'type' => 'A', 'name' => 'department-edit', 'perms' => 'dept.dept/edit'],
['id' => 47, 'pid' => 26, 'type' => 'A', 'name' => 'department-delete', 'perms' => 'dept.dept/delete'],
]);
Db::name('system_role_menu')->insertAll([
['role_id' => $roleId, 'menu_id' => 25], ['role_id' => $roleId, 'menu_id' => 26],
]);
Db::name('admin_role')->insert(['admin_id' => $adminId, 'role_id' => $roleId]);
Db::name('admin_dept')->insert(['admin_id' => $adminId, 'dept_id' => 52]);
Db::name('dept')->insert(['id' => 52, 'pid' => 28, 'name' => 'fixture-statistics', 'status' => 1]);
// Prevent any accidental database mutation during all middleware checks.
Db::execute('PRAGMA query_only = ON');
readonlyCheck((int) Db::query('PRAGMA query_only')[0]['query_only'] === 1, 'Fixture is not query-only');
$adminInfo = ['admin_id' => $adminId, 'root' => 0, 'role_id' => [$roleId], 'dept_id' => [52],
'login_ip' => '198.51.100.42', 'terminal' => AdminTerminalEnum::GROUP_HOSPITAL,
'is_paw' => 1, 'work_wechat_userid' => 'fixture-bound'];
readonlyCheck($adminInfo['root'] === 0, 'Fixture accidentally uses root');
$snapshot = static function (): array {
$rows = [];
foreach (['system_role', 'system_menu', 'system_role_menu', 'admin_role', 'admin_dept', 'dept'] as $table) {
$rows[$table] = Db::name($table)->select()->toArray();
}
return $rows;
};
$before = $snapshot();
readonlyCheck(array_map('intval', Db::name('system_role_menu')->where('role_id', $roleId)->order('menu_id')->column('menu_id')) === [25, 26], 'Wrong role menu IDs');
readonlyCheck(array_map('intval', Db::name('admin_dept')->where('admin_id', $adminId)->column('dept_id')) === [52], 'Wrong employee department');
readonlyCheck(DataScopeService::getEffectiveScope($adminInfo) === 4, 'Employee scope is not SELF');
readonlyCheck(DataScopeService::getVisibleAdminIds($adminId, $adminInfo) === [$adminId], 'SELF scope expanded to another employee');
readonlyCheck(AuthLogic::getAuthByAdminId($adminId) === ['dept.dept/lists'], 'Assigned permission set is not list-only');
$invoke = static function (string $controller, string $action, string $method) use ($app, $adminInfo): array {
$request = (new think\Request())->withServer(['REMOTE_ADDR' => $adminInfo['login_ip'],
'REQUEST_METHOD' => $method, 'HTTP_HOST' => 'fixture.example.test', 'SERVER_PORT' => '443', 'HTTPS' => 'on']);
$request->setMethod($method)->setHost('fixture.example.test')->setController($controller)->setAction($action);
$request->adminInfo = $adminInfo;
$request->controllerObject = new class { public function isNotNeedLogin(): bool { return false; } };
$app->instance('request', $request);
$nextCalls = 0;
$response = (new AuthMiddleware())->handle($request, static function () use (&$nextCalls): string {
++$nextCalls;
return 'fixture-next-only'; // No controller, HTTP request, or business write is executed.
});
return [$response, $nextCalls];
};
[$allowed, $nextCalls] = $invoke('dept.dept', 'lists', 'GET');
++$scenarios;
readonlyCheck($allowed === 'fixture-next-only', 'Department lists was not allowed');
readonlyCheck($nextCalls === 1, 'Department lists did not reach next exactly once');
$denied = [
['dept.dept', 'add', 'POST'], ['dept.dept', 'edit', 'POST'], ['dept.dept', 'delete', 'POST'],
['dept.dept', 'add', 'GET'], ['dept.dept', 'edit', 'GET'], ['dept.dept', 'delete', 'GET'],
['auth.role', 'lists', 'GET'], ['auth.menu', 'lists', 'GET'],
];
$registered = array_map('strtolower', AuthLogic::getAllAuth());
foreach ($denied as [$controller, $action, $method]) {
$label = $method . ' ' . $controller . '/' . $action;
readonlyCheck(in_array(strtolower($controller . '/' . $action), $registered, true), $label . ' is not registered');
[$response, $nextCalls] = $invoke($controller, $action, $method);
++$scenarios;
readonlyCheck($response instanceof think\Response, $label . ' did not return a rejection response');
$data = $response->getData();
readonlyCheck(($data['code'] ?? null) === 0 && ($data['msg'] ?? '') === '权限不足,无法访问或操作'
&& ($data['data'] ?? null) === [], $label . ' returned the wrong denial');
readonlyCheck($nextCalls === 0, $label . ' reached next before rejecting');
}
// Document the legacy boundary with an invented URI and a harmless next closure.
// Passing this case is NOT a security guarantee for unregistered routes.
readonlyCheck(!in_array('fixture.unregistered/probe', $registered, true), 'Legacy boundary probe was unexpectedly registered');
[$legacy, $nextCalls] = $invoke('fixture.unregistered', 'probe', 'GET');
++$scenarios;
readonlyCheck($legacy === 'fixture-next-only' && $nextCalls === 1, 'Legacy unregistered-URI behavior changed; reassess this scope note');
readonlyCheck($snapshot() === $before, 'Middleware changed fixture configuration');
fwrite(STDOUT, "PASS group readonly permissions: {$scenarios} scenarios; {$checks} checks; 1 registered read allowed; 8 registered route/method denials; 1 legacy bypass boundary.\n");
fwrite(STDOUT, "Isolated query-only SQLite and random temporary cache; no real .env, controllers, HTTP writes, or real accounts.\n");
} catch (Throwable $error) {
fwrite(STDERR, 'FAIL group readonly permissions: ' . $error->getMessage() . "\n");
exit(1);
}